idx int64 0 63k | question stringlengths 53 5.28k | target stringlengths 5 805 |
|---|---|---|
43,000 | def allow_access_for_roles ( roles ) : if isinstance ( roles , Role ) : roles = ( roles , ) valid_roles = frozenset ( roles ) if Anonymous in valid_roles : return allow_anonymous def check_role ( user , roles , ** kwargs ) : from abilian . services import get_service security = get_service ( "security" ) return securit... | Access control helper to check user s roles against a list of valid roles . |
43,001 | def populate_obj ( self , obj , name ) : from abilian . core . models . blob import Blob delete_value = self . allow_delete and self . delete_files_index if not self . has_file ( ) and not delete_value : return state = sa . inspect ( obj ) mapper = state . mapper if name not in mapper . relationships : return super ( )... | Store file . |
43,002 | def keys ( self , prefix = None ) : query = Setting . query if prefix : query = query . filter ( Setting . key . startswith ( prefix ) ) return [ i [ 0 ] for i in query . yield_per ( 1000 ) . values ( Setting . key ) ] | List all keys with optional prefix filtering . |
43,003 | def iteritems ( self , prefix = None ) : query = Setting . query if prefix : query = query . filter ( Setting . key . startswith ( prefix ) ) for s in query . yield_per ( 1000 ) : yield ( s . key , s . value ) | Like dict . iteritems . |
43,004 | def for_entity ( obj , check_commentable = False ) : if check_commentable and not is_commentable ( obj ) : return [ ] return getattr ( obj , ATTRIBUTE ) | Return comments on an entity . |
43,005 | def available ( self , context ) : if not self . _enabled : return False try : return self . pre_condition ( context ) and self . _check_condition ( context ) except Exception : return False | Determine if this actions is available in this context . |
43,006 | def installed ( self , app = None ) : if app is None : app = current_app return self . __EXTENSION_NAME in app . extensions | Return True if the registry has been installed in current applications . |
43,007 | def actions ( self , context = None ) : assert self . installed ( ) , "Actions not enabled on this application" result = { } if context is None : context = self . context for cat , actions in self . _state [ "categories" ] . items ( ) : result [ cat ] = [ a for a in actions if a . available ( context ) ] return result | Return a mapping of category = > actions list . |
43,008 | def for_category ( self , category , context = None ) : assert self . installed ( ) , "Actions not enabled on this application" actions = self . _state [ "categories" ] . get ( category , [ ] ) if context is None : context = self . context return [ a for a in actions if a . available ( context ) ] | Returns actions list for this category in current application . |
43,009 | def get_active_for ( self , user , user_agent = _MARK , ip_address = _MARK ) : conditions = [ LoginSession . user == user ] if user_agent is not _MARK : if user_agent is None : user_agent = request . environ . get ( "HTTP_USER_AGENT" , "" ) conditions . append ( LoginSession . user_agent == user_agent ) if ip_address i... | Return last known session for given user . |
43,010 | def should_handle ( self , event_type , filename ) : return ( event_type in ( "modified" , "created" ) and filename . startswith ( self . searchpath ) and os . path . isfile ( filename ) ) | Check if an event should be handled . |
43,011 | def event_handler ( self , event_type , src_path ) : filename = os . path . relpath ( src_path , self . searchpath ) if self . should_handle ( event_type , src_path ) : print ( "%s %s" % ( event_type , filename ) ) if self . site . is_static ( filename ) : files = self . site . get_dependencies ( filename ) self . site... | Re - render templates if they are modified . |
43,012 | def protect ( view ) : @ wraps ( view ) def csrf_check ( * args , ** kwargs ) : if not FlaskForm ( ) . validate ( ) : raise Forbidden ( "CSRF validation failed." ) return view ( * args , ** kwargs ) return csrf_check | Protects a view agains CSRF attacks by checking csrf_token value in submitted values . Do nothing if config . WTF_CSRF_ENABLED is not set . |
43,013 | def auto_slug_after_insert ( mapper , connection , target ) : if target . slug is None : target . slug = "{name}{sep}{id}" . format ( name = target . entity_class . lower ( ) , sep = target . SLUG_SEPARATOR , id = target . id ) | Generate a slug from entity_type and id unless slug is already set . |
43,014 | def setup_default_permissions ( session , instance ) : if instance not in session . new or not isinstance ( instance , Entity ) : return if not current_app : return _setup_default_permissions ( instance ) | Setup default permissions on newly created entities according to . |
43,015 | def _setup_default_permissions ( instance ) : from abilian . services import get_service security = get_service ( "security" ) for permission , roles in instance . __default_permissions__ : if permission == "create" : continue for role in roles : security . add_permission ( permission , role , obj = instance ) | Separate method to conveniently call it from scripts for example . |
43,016 | def polymorphic_update_timestamp ( session , flush_context , instances ) : for obj in session . dirty : if not isinstance ( obj , Entity ) : continue state = sa . inspect ( obj ) history = state . attrs [ "updated_at" ] . history if not any ( ( history . added , history . deleted ) ) : obj . updated_at = datetime . utc... | This listener ensures an update statement is emited for entity table to update updated_at . |
43,017 | def all_entity_classes ( ) : persistent_classes = Entity . _decl_class_registry . values ( ) return [ cls for cls in persistent_classes if isclass ( cls ) and issubclass ( cls , Entity ) ] | Return the list of all concrete persistent classes that are subclasses of Entity . |
43,018 | def auto_slug ( self ) : slug = self . name if slug is not None : slug = slugify ( slug , separator = self . SLUG_SEPARATOR ) session = sa . orm . object_session ( self ) if not session : return None query = session . query ( Entity . slug ) . filter ( Entity . _entity_type == self . object_type ) if self . id is not N... | This property is used to auto - generate a slug from the name attribute . |
43,019 | def _indexable_tags ( self ) : tags = current_app . extensions . get ( "tags" ) if not tags or not tags . supports_taggings ( self ) : return "" default_ns = tags . entity_default_ns ( self ) return [ t for t in tags . entity_tags ( self ) if t . ns == default_ns ] | Index tag ids for tags defined in this Entity s default tags namespace . |
43,020 | def supported_app_locales ( ) : locale = _get_locale ( ) codes = current_app . config [ "BABEL_ACCEPT_LANGUAGES" ] return ( ( Locale . parse ( code ) , locale . languages . get ( code , code ) ) for code in codes ) | Language codes and labels supported by current application . |
43,021 | def timezones_choices ( ) : utcnow = pytz . utc . localize ( datetime . utcnow ( ) ) locale = _get_locale ( ) for tz in sorted ( pytz . common_timezones ) : tz = get_timezone ( tz ) now = tz . normalize ( utcnow . astimezone ( tz ) ) label = "({}) {}" . format ( get_timezone_gmt ( now , locale = locale ) , tz . zone ) ... | Timezones values and their labels for current locale . |
43,022 | def _get_translations_multi_paths ( ) : ctx = _request_ctx_stack . top if ctx is None : return None translations = getattr ( ctx , "babel_translations" , None ) if translations is None : babel_ext = ctx . app . extensions [ "babel" ] translations = None trs = None for ( dirname , domain ) in reversed ( babel_ext . _tra... | Return the correct gettext translations that should be used for this request . |
43,023 | def localeselector ( ) : user = getattr ( g , "user" , None ) if user is not None : locale = getattr ( user , "locale" , None ) if locale : return locale return request . accept_languages . best_match ( current_app . config [ "BABEL_ACCEPT_LANGUAGES" ] ) | Default locale selector used in abilian applications . |
43,024 | def get_template_i18n ( template_name , locale ) : if locale is None : return [ template_name ] template_list = [ ] parts = template_name . rsplit ( "." , 1 ) root = parts [ 0 ] suffix = parts [ 1 ] if locale . territory is not None : locale_string = "_" . join ( [ locale . language , locale . territory ] ) localized_t... | Build template list with preceding locale if found . |
43,025 | def render_template_i18n ( template_name_or_list , ** context ) : template_list = [ ] if "locale" in context : locale = Locale . parse ( context [ "locale" ] ) else : locale = flask_babel . get_locale ( ) if isinstance ( template_name_or_list , str ) : template_list = get_template_i18n ( template_name_or_list , locale ... | Try to build an ordered list of template to satisfy the current locale . |
43,026 | def add_translations ( self , module_name , translations_dir = "translations" , domain = "messages" ) : module = importlib . import_module ( module_name ) for path in ( Path ( p , translations_dir ) for p in module . __path__ ) : if not ( path . exists ( ) and path . is_dir ( ) ) : continue if not os . access ( str ( p... | Add translations from external module . |
43,027 | def ping_connection ( dbapi_connection , connection_record , connection_proxy ) : cursor = dbapi_connection . cursor ( ) try : cursor . execute ( "SELECT 1" ) except Exception : raise sa . exc . DisconnectionError ( ) cursor . close ( ) | Ensure connections are valid . |
43,028 | def filter_cols ( model , * filtered_columns ) : m = sa . orm . class_mapper ( model ) return list ( { p . key for p in m . iterate_properties if hasattr ( p , "columns" ) } . difference ( filtered_columns ) ) | Return columnsnames for a model except named ones . |
43,029 | def JSONList ( * args , ** kwargs ) : type_ = JSON try : if kwargs . pop ( "unique_sorted" ) : type_ = JSONUniqueListType except KeyError : pass return MutationList . as_mutable ( type_ ( * args , ** kwargs ) ) | Stores a list as JSON on database with mutability support . |
43,030 | def coerce ( cls , key , value ) : if not isinstance ( value , MutationDict ) : if isinstance ( value , dict ) : return MutationDict ( value ) return Mutable . coerce ( key , value ) else : return value | Convert plain dictionaries to MutationDict . |
43,031 | def coerce ( cls , key , value ) : if not isinstance ( value , MutationList ) : if isinstance ( value , list ) : return MutationList ( value ) return Mutable . coerce ( key , value ) else : return value | Convert list to MutationList . |
43,032 | def add_file ( self , user , file_obj , ** metadata ) : user_dir = self . user_dir ( user ) if not user_dir . exists ( ) : user_dir . mkdir ( mode = 0o775 ) handle = str ( uuid1 ( ) ) file_path = user_dir / handle with file_path . open ( "wb" ) as out : for chunk in iter ( lambda : file_obj . read ( CHUNK_SIZE ) , b"" ... | Add a new file . |
43,033 | def get_file ( self , user , handle ) : user_dir = self . user_dir ( user ) if not user_dir . exists ( ) : return None if not is_valid_handle ( handle ) : return None file_path = user_dir / handle if not file_path . exists ( ) and not file_path . is_file ( ) : return None return file_path | Retrieve a file for a user . |
43,034 | def clear_stalled_files ( self ) : CLEAR_AFTER = self . config [ "DELETE_STALLED_AFTER" ] minimum_age = time . time ( ) - CLEAR_AFTER for user_dir in self . UPLOAD_DIR . iterdir ( ) : if not user_dir . is_dir ( ) : logger . error ( "Found non-directory in upload dir: %r" , bytes ( user_dir ) ) continue for content in u... | Scan upload directory and delete stalled files . |
43,035 | def friendly_fqcn ( cls_name ) : if isinstance ( cls_name , type ) : cls_name = fqcn ( cls_name ) return cls_name . rsplit ( "." , 1 ) [ - 1 ] | Friendly name of fully qualified class name . |
43,036 | def local_dt ( dt ) : if not dt . tzinfo : dt = pytz . utc . localize ( dt ) return LOCALTZ . normalize ( dt . astimezone ( LOCALTZ ) ) | Return an aware datetime in system timezone from a naive or aware datetime . |
43,037 | def utc_dt ( dt ) : if not dt . tzinfo : return pytz . utc . localize ( dt ) return dt . astimezone ( pytz . utc ) | Set UTC timezone on a datetime object . |
43,038 | def get_params ( names ) : params = { } for name in names : value = request . form . get ( name ) or request . files . get ( name ) if value is not None : params [ name ] = value return params | Return a dictionary with params from request . |
43,039 | def slugify ( value , separator = "-" ) : if not isinstance ( value , str ) : raise ValueError ( "value must be a Unicode string" ) value = _NOT_WORD_RE . sub ( " " , value ) value = unicodedata . normalize ( "NFKD" , value ) value = value . encode ( "ascii" , "ignore" ) value = value . decode ( "ascii" ) value = value... | Slugify an Unicode string to make it URL friendly . |
43,040 | def luhn ( n ) : r = [ int ( ch ) for ch in str ( n ) ] [ : : - 1 ] return ( sum ( r [ 0 : : 2 ] ) + sum ( sum ( divmod ( d * 2 , 10 ) ) for d in r [ 1 : : 2 ] ) ) % 10 == 0 | Validate that a string made of numeric characters verify Luhn test . Used by siret validator . |
43,041 | def rel_path ( self , uuid ) : _assert_uuid ( uuid ) filename = str ( uuid ) return Path ( filename [ 0 : 2 ] , filename [ 2 : 4 ] , filename ) | Contruct relative path from repository top directory to the file named after this uuid . |
43,042 | def set ( self , uuid , content , encoding = "utf-8" ) : dest = self . abs_path ( uuid ) if not dest . parent . exists ( ) : dest . parent . mkdir ( 0o775 , parents = True ) if hasattr ( content , "read" ) : content = content . read ( ) mode = "tw" if not isinstance ( content , str ) : mode = "bw" encoding = None with ... | Store binary content with uuid as key . |
43,043 | def delete ( self , uuid ) : dest = self . abs_path ( uuid ) if not dest . exists ( ) : raise KeyError ( "No file can be found for this uuid" , uuid ) dest . unlink ( ) | Delete file with given uuid . |
43,044 | def _session_for ( self , model_or_session ) : session = model_or_session if not isinstance ( session , ( Session , sa . orm . scoped_session ) ) : if session is not None : session = sa . orm . object_session ( model_or_session ) if session is None : session = db . session if isinstance ( session , sa . orm . scoped_se... | Return session instance for object parameter . |
43,045 | def commit ( self , session = None ) : if self . __cleared : return if self . _parent : self . _commit_parent ( ) else : self . _commit_repository ( ) self . _clear ( ) | Merge modified objects into parent transaction . |
43,046 | def _add_to ( self , uuid , dest , other ) : _assert_uuid ( uuid ) try : other . remove ( uuid ) except KeyError : pass dest . add ( uuid ) | Add item to dest set ensuring item is not present in other set . |
43,047 | def ns ( ns ) : def setup_ns ( cls ) : setattr ( cls , ENTITY_DEFAULT_NS_ATTR , ns ) return cls return setup_ns | Class decorator that sets default tags namespace to use with its instances . |
43,048 | def entity_tags_form ( self , entity , ns = None ) : if ns is None : ns = self . entity_default_ns ( entity ) field = TagsField ( label = _l ( "Tags" ) , ns = ns ) cls = type ( "EntityNSTagsForm" , ( _TagsForm , ) , { "tags" : field } ) return cls | Construct a form class with a field for tags in namespace ns . |
43,049 | def reindex ( clear : bool , progressive : bool , batch_size : int ) : reindexer = Reindexer ( clear , progressive , batch_size ) reindexer . reindex_all ( ) | Reindex all content ; optionally clear index before . |
43,050 | def url_for_hit ( hit , default = "#" ) : try : object_type = hit [ "object_type" ] object_id = int ( hit [ "id" ] ) return current_app . default_view . url_for ( hit , object_type , object_id ) except KeyError : return default except Exception : logger . error ( "Error building URL for search result" , exc_info = True... | Helper for building URLs from results . |
43,051 | def init_indexes ( self ) : state = self . app_state for name , schema in self . schemas . items ( ) : if current_app . testing : storage = TestingStorage ( ) else : index_path = ( Path ( state . whoosh_base ) / name ) . absolute ( ) if not index_path . exists ( ) : index_path . mkdir ( parents = True ) storage = FileS... | Create indexes for schemas . |
43,052 | def clear ( self ) : logger . info ( "Resetting indexes" ) state = self . app_state for _name , idx in state . indexes . items ( ) : writer = AsyncWriter ( idx ) writer . commit ( merge = True , optimize = True , mergetype = CLEAR ) state . indexes . clear ( ) state . indexed_classes . clear ( ) state . indexed_fqcn . ... | Remove all content from indexes and unregister all classes . |
43,053 | def register_class ( self , cls , app_state = None ) : state = app_state if app_state is not None else self . app_state for Adapter in self . adapters_cls : if Adapter . can_adapt ( cls ) : break else : return cls_fqcn = fqcn ( cls ) self . adapted [ cls_fqcn ] = Adapter ( cls , self . schemas [ "default" ] ) state . i... | Register a model class . |
43,054 | def after_commit ( self , session ) : if ( not self . running or session . transaction . nested or session is not db . session ( ) ) : return primary_field = "id" state = self . app_state items = [ ] for op , obj in state . to_update : model_name = fqcn ( obj . __class__ ) if model_name not in self . adapted or not sel... | Any db updates go through here . |
43,055 | def index_objects ( self , objects , index = "default" ) : if not objects : return index_name = index index = self . app_state . indexes [ index_name ] indexed = set ( ) with index . writer ( ) as writer : for obj in objects : document = self . get_document ( obj ) if document is None : continue object_key = document [... | Bulk index a list of objects . |
43,056 | def linkify_url ( value ) : value = value . strip ( ) rjs = r"[\s]*(&#x.{1,7})?" . join ( list ( "javascript:" ) ) rvb = r"[\s]*(&#x.{1,7})?" . join ( list ( "vbscript:" ) ) re_scripts = re . compile ( f"({rjs})|({rvb})" , re . IGNORECASE ) value = re_scripts . sub ( "" , value ) url = value if not url . startswith ( "... | Tranform an URL pulled from the database to a safe HTML fragment . |
43,057 | def get_preferences ( self , user = None ) : if user is None : user = current_user return { pref . key : pref . value for pref in user . preferences } | Return a string - > value dictionnary representing the given user preferences . |
43,058 | def set_preferences ( self , user = None , ** kwargs ) : if user is None : user = current_user d = { pref . key : pref for pref in user . preferences } for k , v in kwargs . items ( ) : if k in d : d [ k ] . value = v else : d [ k ] = UserPreference ( user = user , key = k , value = v ) db . session . add ( d [ k ] ) | Set preferences from keyword arguments . |
43,059 | def do_access_control ( self ) : from abilian . services import get_service if current_app . testing and current_app . config . get ( "NO_LOGIN" ) : user = User . query . get ( 0 ) login_user ( user , force = True ) return state = self . app_state user = unwrap ( current_user ) if current_app . testing and getattr ( us... | before_request handler to check if user should be redirected to login page . |
43,060 | def get_entities_for_reindex ( tags ) : if isinstance ( tags , Tag ) : tags = ( tags , ) session = db . session ( ) indexing = get_service ( "indexing" ) tbl = Entity . __table__ tag_ids = [ t . id for t in tags ] query = ( sa . sql . select ( [ tbl . c . entity_type , tbl . c . id ] ) . select_from ( tbl . join ( enti... | Collect entities for theses tags . |
43,061 | def check_output ( * args , ** kwargs ) : if hasattr ( subprocess , 'check_output' ) : return subprocess . check_output ( stderr = subprocess . STDOUT , universal_newlines = True , * args , ** kwargs ) else : process = subprocess . Popen ( * args , stdout = subprocess . PIPE , stderr = subprocess . STDOUT , universal_n... | Compatibility wrapper for Python 2 . 6 missin g subprocess . check_output |
43,062 | def form_valid ( self , redirect_to = None ) : session = db . session ( ) with session . no_autoflush : self . before_populate_obj ( ) self . form . populate_obj ( self . obj ) session . add ( self . obj ) self . after_populate_obj ( ) try : session . flush ( ) self . send_activity ( ) session . commit ( ) except Valid... | Save object . |
43,063 | def get_item ( self , obj ) : return { "id" : obj . id , "text" : self . get_label ( obj ) , "name" : obj . name } | Return a result item . |
43,064 | def pip ( name ) : with io . open ( os . path . join ( 'requirements' , '{0}.pip' . format ( name ) ) ) as f : return f . readlines ( ) | Parse requirements file |
43,065 | def convert ( self , blob , size = 500 ) : file_list = [ ] with make_temp_file ( blob ) as in_fn , make_temp_file ( ) as out_fn : try : subprocess . check_call ( [ "pdftoppm" , "-jpeg" , in_fn , out_fn ] ) file_list = sorted ( glob . glob ( f"{out_fn}-*.jpg" ) ) converted_images = [ ] for fn in file_list : converted = ... | Size is the maximum horizontal size . |
43,066 | def convert ( self , blob , ** kw ) : timeout = self . run_timeout with make_temp_file ( blob ) as in_fn , make_temp_file ( prefix = "tmp-unoconv-" , suffix = ".pdf" ) as out_fn : args = [ "-f" , "pdf" , "-o" , out_fn , in_fn ] if Path ( "/Applications/LibreOffice.app/Contents/program/python" ) . exists ( ) : cmd = [ "... | Convert using unoconv converter . |
43,067 | def convert ( self , blob , ** kw ) : timeout = self . run_timeout with make_temp_file ( blob ) as in_fn : cmd = [ self . soffice , "--headless" , "--convert-to" , "pdf" , in_fn ] def run_soffice ( ) : try : self . _process = subprocess . Popen ( cmd , close_fds = True , cwd = bytes ( self . tmp_dir ) ) self . _process... | Convert using soffice converter . |
43,068 | def autoescape ( filter_func ) : @ evalcontextfilter @ wraps ( filter_func ) def _autoescape ( eval_ctx , * args , ** kwargs ) : result = filter_func ( * args , ** kwargs ) if eval_ctx . autoescape : result = Markup ( result ) return result return _autoescape | Decorator to autoescape result from filters . |
43,069 | def paragraphs ( value ) : result = "\n\n" . join ( "<p>{}</p>" . format ( p . strip ( ) . replace ( "\n" , Markup ( "<br />\n" ) ) ) for p in _PARAGRAPH_RE . split ( escape ( value ) ) ) return result | Blank lines delimitates paragraphs . |
43,070 | def roughsize ( size , above = 20 , mod = 10 ) : if size < above : return str ( size ) return "{:d}+" . format ( size - size % mod ) | 6 - > 6 15 - > 15 134 - > 130 + . |
43,071 | def datetimeparse ( s ) : try : dt = dateutil . parser . parse ( s ) except ValueError : return None return utc_dt ( dt ) | Parse a string date time to a datetime object . |
43,072 | def start ( self , ignore_state = False ) : self . logger . debug ( "Start service" ) self . _toggle_running ( True , ignore_state ) | Starts the service . |
43,073 | def app_state ( self ) : try : return current_app . extensions [ self . name ] except KeyError : raise ServiceNotRegistered ( self . name ) | Current service state in current application . |
43,074 | def if_running ( meth ) : @ wraps ( meth ) def check_running ( self , * args , ** kwargs ) : if not self . running : return return meth ( self , * args , ** kwargs ) return check_running | Decorator for service methods that must be ran only if service is in running state . |
43,075 | def clean ( self ) : if self . config . clean : logger . info ( 'Cleaning' ) self . execute ( self . config . clean ) | Clean the workspace |
43,076 | def publish ( self ) : if self . config . publish : logger . info ( 'Publish' ) self . execute ( self . config . publish ) | Publish the current release to PyPI |
43,077 | def deps ( ctx ) : header ( deps . __doc__ ) with ctx . cd ( ROOT ) : ctx . run ( 'pip install -r requirements/develop.pip -r requirements/doc.pip' , pty = True ) | Install or update development dependencies |
43,078 | def doc ( ctx ) : header ( doc . __doc__ ) with ctx . cd ( os . path . join ( ROOT , 'doc' ) ) : ctx . run ( 'make html' , pty = True ) success ( 'Documentation available in doc/_build/html' ) | Build the documentation |
43,079 | def completion ( ctx ) : header ( completion . __doc__ ) with ctx . cd ( ROOT ) : ctx . run ( '_bumpr_COMPLETE=source bumpr > bumpr-complete.sh' , pty = True ) success ( 'Completion generated in bumpr-complete.sh' ) | Generate bash completion script |
43,080 | def for_entity ( obj , check_support_attachments = False ) : if check_support_attachments and not supports_attachments ( obj ) : return [ ] return getattr ( obj , ATTRIBUTE ) | Return attachments on an entity . |
43,081 | def strip_label ( mapper , connection , target ) : if target . label is not None : target . label = target . label . strip ( ) | Strip labels at ORM level so the unique = True means something . |
43,082 | def _before_insert ( mapper , connection , target ) : if target . position is None : func = sa . sql . func stmt = sa . select ( [ func . coalesce ( func . max ( mapper . mapped_table . c . position ) , - 1 ) ] ) target . position = connection . execute ( stmt ) . scalar ( ) + 1 | Set item to last position if position not defined . |
43,083 | def init_sentry ( self ) : dsn = self . config . get ( "SENTRY_DSN" ) if not dsn : return try : import sentry_sdk except ImportError : logger . error ( 'SENTRY_DSN is defined in config but package "sentry-sdk"' " is not installed." ) return from sentry_sdk . integrations . flask import FlaskIntegration sentry_sdk . ini... | Install Sentry handler if config defines SENTRY_DSN . |
43,084 | def install_default_handler ( self , http_error_code ) : logger . debug ( "Set Default HTTP error handler for status code %d" , http_error_code ) handler = partial ( self . handle_http_error , http_error_code ) self . errorhandler ( http_error_code ) ( handler ) | Install a default error handler for http_error_code . |
43,085 | def register ( self , entity , url_func ) : if not inspect . isclass ( entity ) : entity = entity . __class__ assert issubclass ( entity , db . Model ) self . _map [ entity . entity_type ] = url_func | Associate a url_func with entity s type . |
43,086 | def url_for ( self , entity = None , object_type = None , object_id = None , ** kwargs ) : if object_type is None : assert isinstance ( entity , ( db . Model , Hit , dict ) ) getter = attrgetter if isinstance ( entity , db . Model ) else itemgetter object_id = getter ( "id" ) ( entity ) object_type = getter ( "object_t... | Return canonical view URL for given entity instance . |
43,087 | def value ( self ) : v = self . file return v . open ( "rb" ) . read ( ) if v is not None else v | Binary value content . |
43,088 | def value ( self ) : from abilian . services . repository import session_repository as repository repository . delete ( self , self . uuid ) | Remove value from repository . |
43,089 | def md5 ( self ) : md5 = self . meta . get ( "md5" ) if md5 is None : md5 = str ( hashlib . md5 ( self . value ) . hexdigest ( ) ) return md5 | Return md5 from meta or compute it if absent . |
43,090 | def forgotten_pw ( new_user = False ) : email = request . form . get ( "email" , "" ) . lower ( ) action = request . form . get ( "action" ) if action == "cancel" : return redirect ( url_for ( "login.login_form" ) ) if not email : flash ( _ ( "You must provide your email address." ) , "error" ) return render_template (... | Reset password for users who have already activated their accounts . |
43,091 | def send_reset_password_instructions ( user ) : token = generate_reset_password_token ( user ) url = url_for ( "login.reset_password" , token = token ) reset_link = request . url_root [ : - 1 ] + url subject = _ ( "Password reset instruction for {site_name}" ) . format ( site_name = current_app . config . get ( "SITE_N... | Send the reset password instructions email for the specified user . |
43,092 | def generate_reset_password_token ( user ) : data = [ str ( user . id ) , md5 ( user . password ) ] return get_serializer ( "reset" ) . dumps ( data ) | Generate a unique reset password token for the specified user . |
43,093 | def send_mail ( subject , recipient , template , ** context ) : config = current_app . config sender = config [ "MAIL_SENDER" ] msg = Message ( subject , sender = sender , recipients = [ recipient ] ) template_name = f"login/email/{template}.txt" msg . body = render_template_i18n ( template_name , ** context ) mail = c... | Send an email using the Flask - Mail extension . |
43,094 | def register_plugin ( self , name ) : logger . info ( "Registering plugin: " + name ) module = importlib . import_module ( name ) module . register_plugin ( self ) | Load and register a plugin given its package name . |
43,095 | def register_plugins ( self ) : registered = set ( ) for plugin_fqdn in chain ( self . APP_PLUGINS , self . config [ "PLUGINS" ] ) : if plugin_fqdn not in registered : self . register_plugin ( plugin_fqdn ) registered . add ( plugin_fqdn ) | Load plugins listed in config variable PLUGINS . |
43,096 | def init_breadcrumbs ( self ) : g . breadcrumb . append ( BreadcrumbItem ( icon = "home" , url = "/" + request . script_root ) ) | Insert the first element in breadcrumbs . |
43,097 | def check_instance_folder ( self , create = False ) : path = Path ( self . instance_path ) err = None eno = 0 if not path . exists ( ) : if create : logger . info ( "Create instance folder: %s" , path ) path . mkdir ( 0o775 , parents = True ) else : err = "Instance folder does not exists" eno = errno . ENOENT elif not ... | Verify instance folder exists is a directory and has necessary permissions . |
43,098 | def init_extensions ( self ) : extensions . redis . init_app ( self ) extensions . mail . init_app ( self ) extensions . deferred_js . init_app ( self ) extensions . upstream_info . extension . init_app ( self ) actions . init_app ( self ) auth_service . init_app ( self ) self . setup_asset_extension ( ) self . registe... | Initialize flask extensions helpers and services . |
43,099 | def add_access_controller ( self , name : str , func : Callable , endpoint : bool = False ) : auth_state = self . extensions [ auth_service . name ] adder = auth_state . add_bp_access_controller if endpoint : adder = auth_state . add_endpoint_access_controller if not isinstance ( name , str ) : msg = "{} is not a valid... | Add an access controller . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.