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 security . has_role ( user , valid_roles ) return check_role | 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 ( ) . populate_obj ( obj , name ) rel = getattr ( mapper . relationships , name ) if rel . uselist : raise ValueError ( "Only single target supported; else use ModelFieldList" ) if delete_value : setattr ( obj , name , None ) return cls = rel . mapper . class_ val = getattr ( obj , name ) if val is None : val = cls ( ) setattr ( obj , name , val ) data = "" if self . has_file ( ) : data = self . data if not issubclass ( cls , Blob ) : data = data . read ( ) setattr ( val , self . blob_attr , data ) | 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 is not _MARK : if ip_address is None : ip_addresses = request . headers . getlist ( "X-Forwarded-For" ) ip_address = ip_addresses [ 0 ] if ip_addresses else request . remote_addr conditions . append ( LoginSession . ip_address == ip_address ) session = ( LoginSession . query . filter ( * conditions ) . order_by ( LoginSession . id . desc ( ) ) . first ( ) ) return session | 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 . copy_static ( files ) else : templates = self . site . get_dependencies ( filename ) self . site . render_templates ( templates ) | 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 . utcnow ( ) | 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 None : query = query . filter ( Entity . id != self . id ) slug_re = re . compile ( re . escape ( slug ) + r"-?(-\d+)?" ) results = [ int ( m . group ( 1 ) or 0 ) for m in ( slug_re . match ( s . slug ) for s in query . all ( ) if s . slug ) if m ] max_id = max ( - 1 , - 1 , * results ) + 1 if max_id : slug = f"{slug}-{max_id}" return slug | 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 ) yield ( tz , label ) | 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 . _translations_paths ) : trs = Translations . load ( dirname , locales = [ flask_babel . get_locale ( ) ] , domain = domain ) if not trs or not hasattr ( trs , "merge" ) : continue elif translations is not None and hasattr ( translations , "merge" ) : translations . merge ( trs ) else : translations = trs if translations is None : translations = trs ctx . babel_translations = translations return translations | 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_template_path = "." . join ( [ root , locale_string , suffix ] ) template_list . append ( localized_template_path ) localized_template_path = "." . join ( [ root , locale . language , suffix ] ) template_list . append ( localized_template_path ) template_list . append ( template_name ) return template_list | 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 ) else : for template in template_name_or_list : template_list . extend ( get_template_i18n ( template , locale ) ) with ensure_request_context ( ) , force_locale ( locale ) : return render_template ( template_list , ** context ) | 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 ( path ) , os . R_OK ) : self . app . logger . warning ( "Babel translations: read access not allowed {}, skipping." "" . format ( repr ( str ( path ) . encode ( "utf-8" ) ) ) ) continue self . _translations_paths . append ( ( str ( path ) , domain ) ) | 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"" ) : out . write ( chunk ) if metadata : meta_file = user_dir / f"{handle}.metadata" with meta_file . open ( "wb" ) as out : metadata_json = json . dumps ( metadata , skipkeys = True ) . encode ( "ascii" ) out . write ( metadata_json ) return handle | 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 user_dir . iterdir ( ) : if not content . is_file ( ) : logger . error ( "Found non-file in user upload dir: %r" , bytes ( content ) ) continue if content . stat ( ) . st_ctime < minimum_age : content . unlink ( ) | 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 . strip ( ) . lower ( ) value = re . sub ( fr"[{separator}_\s]+" , separator , value ) return 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 dest . open ( mode , encoding = encoding ) as f : f . write ( content ) | 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_session ) : session = session ( ) return session | 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 ) return default | 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 = FileStorage ( str ( index_path ) ) if storage . index_exists ( name ) : index = FileIndex ( storage , schema , name ) else : index = FileIndex . create ( storage , schema , name ) state . indexes [ name ] = index | 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 . clear ( ) self . clear_update_queue ( ) if self . running : self . stop ( ) | 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 . indexed_classes . add ( cls ) state . indexed_fqcn . add ( cls_fqcn ) | 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 self . adapted [ model_name ] . indexable : continue if sa . orm . object_session ( obj ) is not None : items . append ( ( op , model_name , getattr ( obj , primary_field ) , { } ) ) if items : index_update . apply_async ( kwargs = { "index" : "default" , "items" : items } ) self . clear_update_queue ( ) | 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 [ "object_key" ] if object_key in indexed : continue writer . delete_by_term ( "object_key" , object_key ) try : writer . add_document ( ** document ) except ValueError : logger . error ( "writer.add_document(%r)" , document , exc_info = True ) raise indexed . add ( object_key ) | 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 ( "http://" ) and not url . startswith ( "https://" ) : url = "http://" + url url = parse . urlsplit ( url ) . geturl ( ) if '"' in url : url = url . split ( '"' ) [ 0 ] if "<" in url : url = url . split ( "<" ) [ 0 ] if value . startswith ( "http://" ) : value = value [ len ( "http://" ) : ] elif value . startswith ( "https://" ) : value = value [ len ( "https://" ) : ] if value . count ( "/" ) == 1 and value . endswith ( "/" ) : value = value [ 0 : - 1 ] return '<a href="{}">{}</a> <i class="fa fa-external-link"></i>' . format ( url , value ) | 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 ( user , "is_admin" , False ) : return security = get_service ( "security" ) user_roles = frozenset ( security . get_roles ( user ) ) endpoint = request . endpoint blueprint = request . blueprint access_controllers = [ ] access_controllers . extend ( state . bp_access_controllers . get ( None , [ ] ) ) if blueprint and blueprint in state . bp_access_controllers : access_controllers . extend ( state . bp_access_controllers [ blueprint ] ) if endpoint and endpoint in state . endpoint_access_controllers : access_controllers . extend ( state . endpoint_access_controllers [ endpoint ] ) for access_controller in reversed ( access_controllers ) : verdict = access_controller ( user = user , roles = user_roles ) if verdict is None : continue elif verdict is True : return else : if user . is_anonymous : return self . redirect_to_login ( ) raise Forbidden ( ) if current_app . config . get ( "PRIVATE_SITE" ) and user . is_anonymous : return self . redirect_to_login ( ) | 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 ( entity_tag_tbl , entity_tag_tbl . c . entity_id == tbl . c . id ) ) . where ( entity_tag_tbl . c . tag_id . in_ ( tag_ids ) ) ) entities = set ( ) with session . no_autoflush : for entity_type , entity_id in session . execute ( query ) : if entity_type not in indexing . adapted : logger . debug ( "%r is not indexed, skipping" , entity_type ) item = ( "changed" , entity_type , entity_id , ( ) ) entities . add ( item ) return entities | 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_newlines = True , ** kwargs ) output , _ = process . communicate ( ) retcode = process . poll ( ) if retcode : error = subprocess . CalledProcessError ( retcode , args [ 0 ] ) error . output = output raise error return output | 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 ValidationError as e : rv = self . handle_commit_exception ( e ) if rv is not None : return rv session . rollback ( ) flash ( str ( e ) , "error" ) return self . get ( ) except sa . exc . IntegrityError as e : rv = self . handle_commit_exception ( e ) if rv is not None : return rv session . rollback ( ) logger . error ( e ) flash ( _ ( "An entity with this name already exists in the system." ) , "error" ) return self . get ( ) else : self . commit_success ( ) flash ( self . message_success ( ) , "success" ) if redirect_to : return redirect ( redirect_to ) else : return self . redirect_to_view ( ) | 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 = resize ( open ( fn , "rb" ) . read ( ) , size , size ) converted_images . append ( converted ) return converted_images except Exception as e : raise ConversionError ( "pdftoppm failed" ) from e finally : for fn in file_list : try : os . remove ( fn ) except OSError : pass | 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 = [ "/Applications/LibreOffice.app/Contents/program/python" , "/usr/local/bin/unoconv" , ] + args else : cmd = [ self . unoconv ] + args def run_uno ( ) : try : self . _process = subprocess . Popen ( cmd , close_fds = True , cwd = bytes ( self . tmp_dir ) ) self . _process . communicate ( ) except Exception as e : logger . error ( "run_uno error: %s" , bytes ( e ) , exc_info = True ) raise ConversionError ( "unoconv failed" ) from e run_thread = threading . Thread ( target = run_uno ) run_thread . start ( ) run_thread . join ( timeout ) try : if run_thread . is_alive ( ) : self . _process . terminate ( ) if self . _process . poll ( ) is not None : try : self . _process . kill ( ) except OSError : logger . warning ( "Failed to kill process %s" , self . _process ) self . _process = None raise ConversionError ( f"Conversion timeout ({timeout})" ) converted = open ( out_fn ) . read ( ) return converted finally : self . _process = None | 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 . communicate ( ) except Exception as e : logger . error ( "soffice error: %s" , bytes ( e ) , exc_info = True ) raise ConversionError ( "soffice conversion failed" ) from e run_thread = threading . Thread ( target = run_soffice ) run_thread . start ( ) run_thread . join ( timeout ) try : if run_thread . is_alive ( ) : self . _process . terminate ( ) if self . _process . poll ( ) is not None : try : self . _process . kill ( ) except OSError : logger . warning ( "Failed to kill process %s" , self . _process ) self . _process = None raise ConversionError ( f"Conversion timeout ({timeout})" ) out_fn = os . path . splitext ( in_fn ) [ 0 ] + ".pdf" converted = open ( out_fn , "rb" ) . read ( ) return converted finally : self . _process = None | 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 . init ( dsn = dsn , integrations = [ FlaskIntegration ( ) ] ) | 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_type" ) ( entity ) url_func = self . _map . get ( object_type ) if url_func is not None : return url_func ( entity , object_type , object_id , ** kwargs ) try : return url_for ( "{}.view" . format ( object_type . rsplit ( "." ) [ - 1 ] . lower ( ) ) , object_id = object_id , ** kwargs ) except Exception : raise KeyError ( object_type ) | 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 ( "login/forgotten_password.html" ) try : user = User . query . filter ( sql . func . lower ( User . email ) == email , User . can_login == True ) . one ( ) except NoResultFound : flash ( _ ( "Sorry, we couldn't find an account for " "email '{email}'." ) . format ( email = email ) , "error" , ) return render_template ( "login/forgotten_password.html" ) , 401 if user . can_login and not user . password : user . set_password ( random_password ( ) ) db . session . commit ( ) send_reset_password_instructions ( user ) flash ( _ ( "Password reset instructions have been sent to your email address." ) , "info" ) return redirect ( url_for ( "login.login_form" ) ) | 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_NAME" ) ) mail_template = "password_reset_instructions" send_mail ( subject , user . email , mail_template , user = user , reset_link = reset_link ) | 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 = current_app . extensions . get ( "mail" ) current_app . logger . debug ( "Sending mail..." ) mail . send ( msg ) | 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 path . is_dir ( ) : err = "Instance folder is not a directory" eno = errno . ENOTDIR elif not os . access ( str ( path ) , os . R_OK | os . W_OK | os . X_OK ) : err = 'Require "rwx" access rights, please verify permissions' eno = errno . EPERM if err : raise OSError ( eno , err , str ( path ) ) | 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 . register_base_assets ( ) babel = abilian . i18n . babel babel . locale_selector_func = None babel . timezone_selector_func = None babel . init_app ( self ) babel . add_translations ( "wtforms" , translations_dir = "locale" , domain = "wtforms" ) babel . add_translations ( "abilian" ) babel . localeselector ( abilian . i18n . localeselector ) babel . timezoneselector ( abilian . i18n . timezoneselector ) Migrate ( self , db ) if self . config . get ( "WTF_CSRF_ENABLED" ) : extensions . csrf . init_app ( self ) self . extensions [ "csrf" ] = extensions . csrf extensions . abilian_csrf . init_app ( self ) self . register_blueprint ( csrf . blueprint ) from . web . views . images import blueprint as images_bp self . register_blueprint ( images_bp ) security_service . init_app ( self ) repository_service . init_app ( self ) session_repository_service . init_app ( self ) audit_service . init_app ( self ) index_service . init_app ( self ) activity_service . init_app ( self ) preferences_service . init_app ( self ) conversion_service . init_app ( self ) vocabularies_service . init_app ( self ) antivirus . init_app ( self ) from . web . preferences . user import UserPreferencesPanel preferences_service . register_panel ( UserPreferencesPanel ( ) , self ) from . web . coreviews import users self . register_blueprint ( users . blueprint ) Admin ( ) . init_app ( self ) if getattr ( self , "celery_app_cls" , None ) : celery_app = self . extensions [ "celery" ] = self . celery_app_cls ( ) celery_app . conf celery_app . set_default ( ) if self . debug : http_error_pages = Blueprint ( "http_error_pages" , __name__ ) @ http_error_pages . route ( "/<int:code>" ) def error_page ( code ) : abort ( code ) self . register_blueprint ( http_error_pages , url_prefix = "/http_error" ) | 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 endpoint name" . format ( repr ( name ) ) raise ValueError ( msg ) adder ( name , func ) | Add an access controller . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.