idx int64 0 63k | question stringlengths 53 5.28k | target stringlengths 5 805 |
|---|---|---|
40,800 | def get ( cls , action , suffix = None ) : action_id = _action_id ( action , suffix ) if action_id not in cls . _HANDLERS : if LOG_OPTS [ 'register' ] : hookenv . log ( 'Registering reactive handler for %s' % _short_action_id ( action , suffix ) , level = hookenv . DEBUG ) cls . _HANDLERS [ action_id ] = cls ( action , suffix ) return cls . _HANDLERS [ action_id ] | Get or register a handler for the given action . |
40,801 | def add_predicate ( self , predicate ) : _predicate = predicate if isinstance ( predicate , partial ) : _predicate = 'partial(%s, %s, %s)' % ( predicate . func , predicate . args , predicate . keywords ) if LOG_OPTS [ 'register' ] : hookenv . log ( ' Adding predicate for %s: %s' % ( self . id ( ) , _predicate ) , level = hookenv . DEBUG ) self . _predicates . append ( predicate ) | Add a new predicate callback to this handler . |
40,802 | def _get_args ( self ) : if not hasattr ( self , '_args_evaled' ) : self . _args_evaled = list ( chain . from_iterable ( self . _args ) ) return self . _args_evaled | Lazily evaluate the args . |
40,803 | def invoke ( self ) : args = self . _get_args ( ) self . _action ( * args ) for callback in self . _post_callbacks : callback ( ) | Invoke this handler . |
40,804 | def register_flags ( self , flags ) : self . _CONSUMED_FLAGS . update ( flags ) self . _flags . update ( flags ) | Register flags as being relevant to this handler . |
40,805 | def invoke ( self ) : unitdata . kv ( ) . flush ( ) subprocess . check_call ( [ self . _filepath , '--invoke' , self . _test_output ] , env = os . environ ) | Call the external handler to be invoked . |
40,806 | def hook ( * hook_patterns ) : def _register ( action ) : def arg_gen ( ) : rel = endpoint_from_name ( hookenv . relation_type ( ) ) if rel : yield rel handler = Handler . get ( action ) handler . add_predicate ( partial ( _hook , hook_patterns ) ) handler . add_args ( arg_gen ( ) ) return action return _register | Register the decorated function to run when the current hook matches any of the hook_patterns . |
40,807 | def when_file_changed ( * filenames , ** kwargs ) : def _register ( action ) : handler = Handler . get ( action ) handler . add_predicate ( partial ( any_file_changed , filenames , ** kwargs ) ) return action return _register | Register the decorated function to run when one or more files have changed . |
40,808 | def not_unless ( * desired_flags ) : def _decorator ( func ) : action_id = _action_id ( func ) short_action_id = _short_action_id ( func ) @ wraps ( func ) def _wrapped ( * args , ** kwargs ) : active_flags = get_flags ( ) missing_flags = [ flag for flag in desired_flags if flag not in active_flags ] if missing_flags : hookenv . log ( '%s called before flag%s: %s' % ( short_action_id , 's' if len ( missing_flags ) > 1 else '' , ', ' . join ( missing_flags ) ) , hookenv . WARNING ) return func ( * args , ** kwargs ) _wrapped . _action_id = action_id _wrapped . _short_action_id = short_action_id return _wrapped return _decorator | Assert that the decorated function can only be called if the desired_flags are active . |
40,809 | def collect_metrics ( ) : def _register ( action ) : handler = Handler . get ( action ) handler . add_predicate ( partial ( _restricted_hook , 'collect-metrics' ) ) return action return _register | Register the decorated function to run for the collect_metrics hook . |
40,810 | def _is_endpoint_method ( handler ) : params = signature ( handler ) . parameters has_self = len ( params ) == 1 and list ( params . keys ( ) ) [ 0 ] == 'self' has_endpoint_class = any ( isclass ( g ) and issubclass ( g , Endpoint ) for g in handler . __globals__ . values ( ) ) return has_self and has_endpoint_class | from the context . Unfortunately we can t directly detect whether a handler is an Endpoint method because at the time of decoration the class doesn t actually exist yet so it s impossible to get a reference to it . So we use the heuristic of seeing if the handler takes only a single self param and there is an Endpoint class in the handler s globals . |
40,811 | def any_hook ( * hook_patterns ) : current_hook = hookenv . hook_name ( ) i_pat = re . compile ( r'{([^:}]+):([^}]+)}' ) hook_patterns = _expand_replacements ( i_pat , hookenv . role_and_interface_to_relations , hook_patterns ) c_pat = re . compile ( r'{((?:[^:,}]+,?)+)}' ) hook_patterns = _expand_replacements ( c_pat , lambda v : v . split ( ',' ) , hook_patterns ) return current_hook in hook_patterns | Assert that the currently executing hook matches one of the given patterns . |
40,812 | def any_file_changed ( filenames , hash_type = 'md5' ) : changed = False for filename in filenames : if callable ( filename ) : filename = str ( filename ( ) ) else : filename = str ( filename ) old_hash = unitdata . kv ( ) . get ( 'reactive.files_changed.%s' % filename ) new_hash = host . file_hash ( filename , hash_type = hash_type ) if old_hash != new_hash : unitdata . kv ( ) . set ( 'reactive.files_changed.%s' % filename , new_hash ) changed = True return changed | Check if any of the given files have changed since the last time this was called . |
40,813 | def load_hook_files ( pathname ) : global hooks if sys . version_info [ 0 ] > 2 and sys . version_info [ 1 ] > 4 : fsglob = sorted ( glob . iglob ( pathname , recursive = True ) ) else : fsglob = sorted ( glob . iglob ( pathname ) ) for path in fsglob : real_path = os . path . realpath ( path ) if os . path . dirname ( real_path ) not in sys . path : sys . path . append ( os . path . dirname ( real_path ) ) module = imp . load_source ( os . path . basename ( path ) , real_path ) for name in dir ( module ) : obj = getattr ( module , name ) if hasattr ( obj , 'dredd_hooks' ) and callable ( obj ) : func_hooks = getattr ( obj , 'dredd_hooks' ) for hook , name in func_hooks : if hook == BEFORE_ALL : hooks . _before_all . append ( obj ) if hook == AFTER_ALL : hooks . _after_all . append ( obj ) if hook == BEFORE_EACH : hooks . _before_each . append ( obj ) if hook == AFTER_EACH : hooks . _after_each . append ( obj ) if hook == BEFORE_EACH_VALIDATION : hooks . _before_each_validation . append ( obj ) if hook == BEFORE_VALIDATION : add_named_hook ( hooks . _before_validation , obj , name ) if hook == BEFORE : add_named_hook ( hooks . _before , obj , name ) if hook == AFTER : add_named_hook ( hooks . _after , obj , name ) | Loads files either defined as a glob or a single file path sorted by filenames . |
40,814 | def from_flag ( cls , flag ) : if not is_flag_set ( flag ) or '.' not in flag : return None parts = flag . split ( '.' ) if parts [ 0 ] == 'endpoint' : return cls . from_name ( parts [ 1 ] ) else : return cls . from_name ( parts [ 0 ] ) | Return an Endpoint subclass instance based on the given flag . |
40,815 | def _startup ( cls ) : for endpoint_name in sorted ( hookenv . relation_types ( ) ) : relf = relation_factory ( endpoint_name ) if not relf or not issubclass ( relf , cls ) : continue rids = sorted ( hookenv . relation_ids ( endpoint_name ) ) rids = [ '{}:{}' . format ( endpoint_name , rid ) if ':' not in rid else rid for rid in rids ] endpoint = relf ( endpoint_name , rids ) cls . _endpoints [ endpoint_name ] = endpoint endpoint . register_triggers ( ) endpoint . _manage_departed ( ) endpoint . _manage_flags ( ) for relation in endpoint . relations : hookenv . atexit ( relation . _flush_data ) | Create Endpoint instances and manage automatic flags . |
40,816 | def expand_name ( self , flag ) : if '{endpoint_name}' not in flag : flag = 'endpoint.{endpoint_name}.' + flag return flag . replace ( '{endpoint_name}' , self . endpoint_name ) | Complete a flag for this endpoint by expanding the endpoint name . |
40,817 | def _manage_flags ( self ) : already_joined = is_flag_set ( self . expand_name ( 'joined' ) ) hook_name = hookenv . hook_name ( ) rel_hook = hook_name . startswith ( self . endpoint_name + '-relation-' ) departed_hook = rel_hook and hook_name . endswith ( '-departed' ) toggle_flag ( self . expand_name ( 'joined' ) , self . is_joined ) if departed_hook : set_flag ( self . expand_name ( 'departed' ) ) elif self . is_joined : clear_flag ( self . expand_name ( 'departed' ) ) if already_joined and not rel_hook : return for unit in self . all_units : for key , value in unit . received . items ( ) : data_key = 'endpoint.{}.{}.{}.{}' . format ( self . endpoint_name , unit . relation . relation_id , unit . unit_name , key ) if data_changed ( data_key , value ) : set_flag ( self . expand_name ( 'changed' ) ) set_flag ( self . expand_name ( 'changed.{}' . format ( key ) ) ) | Manage automatic relation flags . |
40,818 | def all_departed_units ( self ) : if self . _all_departed_units is None : self . _all_departed_units = CachedKeyList . load ( 'reactive.endpoints.departed.{}' . format ( self . endpoint_name ) , RelatedUnit . _deserialize , 'unit_name' ) return self . _all_departed_units | Collection of all units that were previously part of any relation on this endpoint but which have since departed . |
40,819 | def application_name ( self ) : if self . _application_name is None and self . units : self . _application_name = self . units [ 0 ] . unit_name . split ( '/' ) [ 0 ] return self . _application_name | The name of the remote application for this relation or None . |
40,820 | def joined_units ( self ) : if self . _units is None : self . _units = CombinedUnitsView ( [ RelatedUnit ( self , unit_name ) for unit_name in sorted ( hookenv . related_units ( self . relation_id ) ) ] ) return self . _units | A list view of all the units joined on this relation . |
40,821 | def _flush_data ( self ) : if self . _data and self . _data . modified : hookenv . relation_set ( self . relation_id , dict ( self . to_publish . data ) ) | If this relation s local unit data has been modified publish it on the relation . This should be automatically called . |
40,822 | def load ( cls , cache_key , deserializer , key_attr ) : items = unitdata . kv ( ) . get ( cache_key ) or [ ] return cls ( cache_key , [ deserializer ( item ) for item in items ] , key_attr ) | Load the persisted cache and return a new instance of this class . |
40,823 | def AuthorizingClient ( domain , auth , user_agent = None ) : http_transport = transport . HttpTransport ( domain , build_headers ( auth , user_agent ) ) return client . Client ( http_transport ) | Creates a Podio client using an auth object . |
40,824 | def write_this ( func ) : @ wraps ( func ) def wrapper ( self , * args , ** kwargs ) : byte_array = func ( self , * args , ** kwargs ) self . write_bytes ( byte_array ) return wrapper | Decorator that writes the bytes to the wire |
40,825 | def print_images ( self , * printable_images ) : printable_image = reduce ( lambda x , y : x . append ( y ) , list ( printable_images ) ) self . print_image ( printable_image ) | This method allows printing several images in one shot . This is useful if the client code does not want the printer to make pause during printing |
40,826 | def from_file ( cls , paramname , filename ) : return cls ( paramname , filename = os . path . basename ( filename ) , filetype = mimetypes . guess_type ( filename ) [ 0 ] , filesize = os . path . getsize ( filename ) , fileobj = open ( filename , "rb" ) ) | Returns a new MultipartParam object constructed from the local file at filename . |
40,827 | def from_params ( cls , params ) : if hasattr ( params , 'items' ) : params = params . items ( ) retval = [ ] for item in params : if isinstance ( item , cls ) : retval . append ( item ) continue name , value = item if isinstance ( value , cls ) : assert value . name == name retval . append ( value ) continue if hasattr ( value , 'read' ) : filename = getattr ( value , 'name' , None ) if filename is not None : filetype = mimetypes . guess_type ( filename ) [ 0 ] else : filetype = None retval . append ( cls ( name = name , filename = filename , filetype = filetype , fileobj = value ) ) else : retval . append ( cls ( name , value ) ) return retval | Returns a list of MultipartParam objects from a sequence of name value pairs MultipartParam instances or from a mapping of names to values |
40,828 | def encode_hdr ( self , boundary ) : boundary = encode_and_quote ( boundary ) headers = [ "--%s" % boundary ] if self . filename : disposition = 'form-data; name="%s"; filename="%s"' % ( self . name , self . filename ) else : disposition = 'form-data; name="%s"' % self . name headers . append ( "Content-Disposition: %s" % disposition ) if self . filetype : filetype = self . filetype else : filetype = "text/plain; charset=utf-8" headers . append ( "Content-Type: %s" % filetype ) headers . append ( "" ) headers . append ( "" ) return "\r\n" . join ( headers ) | Returns the header of the encoding of this parameter |
40,829 | def encode ( self , boundary ) : if self . value is None : value = self . fileobj . read ( ) else : value = self . value if re . search ( "^--%s$" % re . escape ( boundary ) , value , re . M ) : raise ValueError ( "boundary found in encoded string" ) return "%s%s\r\n" % ( self . encode_hdr ( boundary ) , value ) | Returns the string encoding of this parameter |
40,830 | def iter_encode ( self , boundary , blocksize = 4096 ) : total = self . get_size ( boundary ) current = 0 if self . value is not None : block = self . encode ( boundary ) current += len ( block ) yield block if self . cb : self . cb ( self , current , total ) else : block = self . encode_hdr ( boundary ) current += len ( block ) yield block if self . cb : self . cb ( self , current , total ) last_block = "" encoded_boundary = "--%s" % encode_and_quote ( boundary ) boundary_exp = re . compile ( "^%s$" % re . escape ( encoded_boundary ) , re . M ) while True : block = self . fileobj . read ( blocksize ) if not block : current += 2 yield "\r\n" if self . cb : self . cb ( self , current , total ) break last_block += block if boundary_exp . search ( last_block ) : raise ValueError ( "boundary found in file data" ) last_block = last_block [ - len ( encoded_boundary ) - 2 : ] current += len ( block ) yield block if self . cb : self . cb ( self , current , total ) | Yields the encoding of this parameter If self . fileobj is set then blocks of blocksize bytes are read and yielded . |
40,831 | def get_size ( self , boundary ) : if self . filesize is not None : valuesize = self . filesize else : valuesize = len ( self . value ) return len ( self . encode_hdr ( boundary ) ) + 2 + valuesize | Returns the size in bytes that this param will be when encoded with the given boundary . |
40,832 | def get_options ( silent = False , hook = True ) : options_ = { } if silent : options_ [ 'silent' ] = silent if not hook : options_ [ 'hook' ] = hook if options_ : return '?' + urlencode ( options_ ) . lower ( ) else : return '' | Generate a query string with the appropriate options . |
40,833 | def find_by_url ( self , space_url , id_only = True ) : resp = self . transport . GET ( url = '/space/url?%s' % urlencode ( { 'url' : space_url } ) ) if id_only : return resp [ 'space_id' ] return resp | Returns a space ID given the URL of the space . |
40,834 | def find_by_ref ( self , ref_type , ref_id ) : return self . transport . GET ( url = '/stream/%s/%s' % ( ref_type , ref_id ) ) | Returns an object of type item status or task as a stream object . This is useful when a new status has been posted and should be rendered directly in the stream without reloading the entire stream . |
40,835 | def find_raw ( self , file_id ) : raw_handler = lambda resp , data : data return self . transport . GET ( url = '/file/%d/raw' % file_id , handler = raw_handler ) | Returns raw file as string . Pass to a file object |
40,836 | def create ( self , filename , filedata ) : attributes = { 'filename' : filename , 'source' : filedata } return self . transport . POST ( url = '/file/v2/' , body = attributes , type = 'multipart/form-data' ) | Create a file from raw data |
40,837 | def get ( self , app_id , view_specifier ) : return self . transport . GET ( url = '/view/app/{}/{}' . format ( app_id , view_specifier ) ) | Retrieve the definition of a given view provided the app_id and the view_id |
40,838 | def get_views ( self , app_id , include_standard_views = False ) : include_standard = "true" if include_standard_views is True else "false" return self . transport . GET ( url = '/view/app/{}/?include_standard_views={}' . format ( app_id , include_standard ) ) | Get all of the views for the specified app |
40,839 | def update_last_view ( self , app_id , attributes ) : if not isinstance ( attributes , dict ) : raise TypeError ( 'Must be of type dict' ) attribute_data = json . dumps ( attributes ) return self . transport . PUT ( url = '/view/app/{}/last' . format ( app_id ) , body = attribute_data , type = 'application/json' ) | Updates the last view for the active user |
40,840 | def update_view ( self , view_id , attributes ) : if not isinstance ( attributes , dict ) : raise TypeError ( 'Must be of type dict' ) attribute_data = json . dumps ( attributes ) return self . transport . PUT ( url = '/view/{}' . format ( view_id ) , body = attribute_data , type = 'application/json' ) | Update an existing view using the details supplied via the attributes parameter |
40,841 | def query ( self , sql , timeout = 10 ) : if not sql : raise QueryError ( 'No query passed to drill.' ) result = ResultQuery ( * self . perform_request ( ** { 'method' : 'POST' , 'url' : '/query.json' , 'body' : { "queryType" : "SQL" , "query" : sql } , 'params' : { 'request_timeout' : timeout } } ) ) return result | Submit a query and return results . |
40,842 | def storage_detail ( self , name , timeout = 10 ) : result = Result ( * self . perform_request ( ** { 'method' : 'GET' , 'url' : '/storage/{0}.json' . format ( name ) , 'params' : { 'request_timeout' : timeout } } ) ) return result | Get the definition of the named storage plugin . |
40,843 | def storage_enable ( self , name , value = True , timeout = 10 ) : value = 'true' if value else 'false' result = Result ( * self . perform_request ( ** { 'method' : 'GET' , 'url' : '/storage/{0}/enable/{1}' . format ( name , value ) , 'params' : { 'request_timeout' : timeout } } ) ) return result | Enable or disable the named storage plugin . |
40,844 | def storage_update ( self , name , config , timeout = 10 ) : result = Result ( * self . perform_request ( ** { 'method' : 'POST' , 'url' : '/storage/{0}.json' . format ( name ) , 'body' : config , 'params' : { 'request_timeout' : timeout } } ) ) return result | Create or update a storage plugin configuration . |
40,845 | def storage_delete ( self , name , timeout = 10 ) : result = Result ( * self . perform_request ( ** { 'method' : 'DELETE' , 'url' : '/storage/{0}.json' . format ( name ) , 'params' : { 'request_timeout' : timeout } } ) ) return result | Delete a storage plugin configuration . |
40,846 | def profile ( self , query_id , timeout = 10 ) : result = Result ( * self . perform_request ( ** { 'method' : 'GET' , 'url' : '/profiles/{0}.json' . format ( query_id ) , 'params' : { 'request_timeout' : timeout } } ) ) return result | Get the profile of the query that has the given queryid . |
40,847 | def profile_cancel ( self , query_id , timeout = 10 ) : result = Result ( * self . perform_request ( ** { 'method' : 'GET' , 'url' : '/profiles/cancel/{0}' . format ( query_id ) , 'params' : { 'request_timeout' : timeout } } ) ) return result | Cancel the query that has the given queryid . |
40,848 | def perform_request ( self , method , url , params = None , body = None ) : if body is not None : body = self . serializer . dumps ( body ) if method in ( 'HEAD' , 'GET' ) and self . send_get_body_as != 'GET' : if self . send_get_body_as == 'POST' : method = 'POST' elif self . send_get_body_as == 'source' : if params is None : params = { } params [ 'source' ] = body body = None if body is not None : try : body = body . encode ( 'utf-8' ) except ( UnicodeDecodeError , AttributeError ) : pass ignore = ( ) timeout = None if params : timeout = params . pop ( 'request_timeout' , None ) ignore = params . pop ( 'ignore' , ( ) ) if isinstance ( ignore , int ) : ignore = ( ignore , ) for attempt in range ( self . max_retries + 1 ) : connection = self . get_connection ( ) try : response , data , duration = connection . perform_request ( method , url , params , body , ignore = ignore , timeout = timeout ) except TransportError as e : retry = False if isinstance ( e , ConnectionTimeout ) : retry = self . retry_on_timeout elif isinstance ( e , ConnectionError ) : retry = True elif e . status_code in self . retry_on_status : retry = True if retry : if attempt == self . max_retries : raise else : raise else : if data : data = self . deserializer . loads ( data , mimetype = response . headers . get ( 'Content-Type' ) ) else : data = { } return response , data , duration | Perform the actual request . Retrieve a connection . Pass all the information to it s perform_request method and return the data . |
40,849 | def check_security_settings ( ) : in_production = not ( current_app . debug or current_app . testing ) secure = current_app . config . get ( 'SESSION_COOKIE_SECURE' ) if in_production and not secure : current_app . logger . warning ( "SESSION_COOKIE_SECURE setting must be set to True to prevent the " "session cookie from being leaked over an insecure channel." ) | Warn if session cookie is not secure in production . |
40,850 | def jwt_proccessor ( ) : def jwt ( ) : token = current_accounts . jwt_creation_factory ( ) return Markup ( render_template ( current_app . config [ 'ACCOUNTS_JWT_DOM_TOKEN_TEMPLATE' ] , token = token ) ) def jwt_token ( ) : return current_accounts . jwt_creation_factory ( ) return { 'jwt' : jwt , 'jwt_token' : jwt_token , } | Context processor for jwt . |
40,851 | def _to_binary ( val ) : if isinstance ( val , text_type ) : return val . encode ( 'utf-8' ) assert isinstance ( val , binary_type ) return val | Convert to binary . |
40,852 | def _to_string ( val ) : if isinstance ( val , binary_type ) : return val . decode ( 'utf-8' ) assert isinstance ( val , text_type ) return val | Convert to text . |
40,853 | def _mysql_aes_key ( key ) : final_key = bytearray ( 16 ) for i , c in enumerate ( key ) : final_key [ i % 16 ] ^= key [ i ] if PY3 else ord ( key [ i ] ) return bytes ( final_key ) | Format key . |
40,854 | def _mysql_aes_unpad ( val ) : val = _to_string ( val ) pad_value = ord ( val [ - 1 ] ) return val [ : - pad_value ] | Reverse padding . |
40,855 | def mysql_aes_encrypt ( val , key ) : assert isinstance ( val , binary_type ) or isinstance ( val , text_type ) assert isinstance ( key , binary_type ) or isinstance ( key , text_type ) k = _mysql_aes_key ( _to_binary ( key ) ) v = _mysql_aes_pad ( _to_binary ( val ) ) e = _mysql_aes_engine ( k ) . encryptor ( ) return e . update ( v ) + e . finalize ( ) | Mysql AES encrypt value with secret key . |
40,856 | def mysql_aes_decrypt ( encrypted_val , key ) : assert isinstance ( encrypted_val , binary_type ) or isinstance ( encrypted_val , text_type ) assert isinstance ( key , binary_type ) or isinstance ( key , text_type ) k = _mysql_aes_key ( _to_binary ( key ) ) d = _mysql_aes_engine ( _to_binary ( k ) ) . decryptor ( ) return _mysql_aes_unpad ( d . update ( _to_binary ( encrypted_val ) ) + d . finalize ( ) ) | Mysql AES decrypt value with secret key . |
40,857 | def from_string ( cls , hash , ** context ) : salt , checksum = parse_mc2 ( hash , cls . ident , handler = cls ) return cls ( salt = salt , checksum = checksum ) | Parse instance from configuration string in Modular Crypt Format . |
40,858 | def _calc_checksum ( self , secret ) : return str_to_uascii ( hashlib . sha256 ( mysql_aes_encrypt ( self . salt , secret ) ) . hexdigest ( ) ) | Calculate string . |
40,859 | def _ip2country ( ip ) : if ip : match = geolite2 . reader ( ) . get ( ip ) return match . get ( 'country' , { } ) . get ( 'iso_code' ) if match else None | Get user country . |
40,860 | def _extract_info_from_useragent ( user_agent ) : parsed_string = user_agent_parser . Parse ( user_agent ) return { 'os' : parsed_string . get ( 'os' , { } ) . get ( 'family' ) , 'browser' : parsed_string . get ( 'user_agent' , { } ) . get ( 'family' ) , 'browser_version' : parsed_string . get ( 'user_agent' , { } ) . get ( 'major' ) , 'device' : parsed_string . get ( 'device' , { } ) . get ( 'family' ) , } | Extract extra informations from user . |
40,861 | def add_session ( session = None ) : r user_id , sid_s = session [ 'user_id' ] , session . sid_s with db . session . begin_nested ( ) : session_activity = SessionActivity ( user_id = user_id , sid_s = sid_s , ip = request . remote_addr , country = _ip2country ( request . remote_addr ) , ** _extract_info_from_useragent ( request . headers . get ( 'User-Agent' , '' ) ) ) db . session . merge ( session_activity ) | r Add a session to the SessionActivity table . |
40,862 | def login_listener ( app , user ) : @ after_this_request def add_user_session ( response ) : session . regenerate ( ) app . session_interface . save_session ( app , session , response ) add_session ( session ) current_accounts . datastore . commit ( ) return response | Connect to the user_logged_in signal for table population . |
40,863 | def logout_listener ( app , user ) : @ after_this_request def _commit ( response = None ) : if hasattr ( session , 'sid_s' ) : delete_session ( session . sid_s ) session . regenerate ( ) current_accounts . datastore . commit ( ) return response | Connect to the user_logged_out signal . |
40,864 | def delete_session ( sid_s ) : _sessionstore . delete ( sid_s ) with db . session . begin_nested ( ) : SessionActivity . query . filter_by ( sid_s = sid_s ) . delete ( ) return 1 | Delete entries in the data - and kvsessionstore with the given sid_s . |
40,865 | def delete_user_sessions ( user ) : with db . session . begin_nested ( ) : for s in user . active_sessions : _sessionstore . delete ( s . sid_s ) SessionActivity . query . filter_by ( user = user ) . delete ( ) return True | Delete all active user sessions . |
40,866 | def confirm_register_form_factory ( Form , app ) : if app . config . get ( 'RECAPTCHA_PUBLIC_KEY' ) and app . config . get ( 'RECAPTCHA_PRIVATE_KEY' ) : class ConfirmRegisterForm ( Form ) : recaptcha = FormField ( RegistrationFormRecaptcha , separator = '.' ) return ConfirmRegisterForm return Form | Return confirmation for extended registration form . |
40,867 | def register_form_factory ( Form , app ) : if app . config . get ( 'RECAPTCHA_PUBLIC_KEY' ) and app . config . get ( 'RECAPTCHA_PRIVATE_KEY' ) : class RegisterForm ( Form ) : recaptcha = FormField ( RegistrationFormRecaptcha , separator = '.' ) return RegisterForm return Form | Return extended registration form . |
40,868 | def login_form_factory ( Form , app ) : class LoginForm ( Form ) : def __init__ ( self , * args , ** kwargs ) : super ( LoginForm , self ) . __init__ ( * args , ** kwargs ) self . remember . data = False return LoginForm | Return extended login form . |
40,869 | def on_model_change ( self , form , User , is_created ) : if form . password . data is not None : pwd_ctx = current_app . extensions [ 'security' ] . pwd_context if pwd_ctx . identify ( form . password . data ) is None : User . password = hash_password ( form . password . data ) | Hash password when saving . |
40,870 | def after_model_change ( self , form , User , is_created ) : if is_created and form . notification . data is True : send_reset_password_instructions ( User ) | Send password instructions if desired . |
40,871 | def delete_model ( self , model ) : if SessionActivity . is_current ( sid_s = model . sid_s ) : flash ( 'You could not remove your current session' , 'error' ) return delete_session ( sid_s = model . sid_s ) db . session . commit ( ) | Delete a specific session . |
40,872 | def action_delete ( self , ids ) : is_current = any ( SessionActivity . is_current ( sid_s = id_ ) for id_ in ids ) if is_current : flash ( 'You could not remove your current session' , 'error' ) return for id_ in ids : delete_session ( sid_s = id_ ) db . session . commit ( ) | Delete selected sessions . |
40,873 | def send_security_email ( data ) : msg = Message ( ) msg . __dict__ . update ( data ) current_app . extensions [ 'mail' ] . send ( msg ) | Celery task to send security email . |
40,874 | def clean_session_table ( ) : sessions = SessionActivity . query_by_expired ( ) . all ( ) for session in sessions : delete_session ( sid_s = session . sid_s ) db . session . commit ( ) | Automatically clean session table . |
40,875 | def jwt_create_token ( user_id = None , additional_data = None ) : uid = str ( uuid . uuid4 ( ) ) now = datetime . utcnow ( ) token_data = { 'exp' : now + current_app . config [ 'ACCOUNTS_JWT_EXPIRATION_DELTA' ] , 'sub' : user_id or current_user . get_id ( ) , 'jti' : uid , } if additional_data is not None : token_data . update ( additional_data ) encoded_token = encode ( token_data , current_app . config [ 'ACCOUNTS_JWT_SECRET_KEY' ] , current_app . config [ 'ACCOUNTS_JWT_ALOGORITHM' ] ) . decode ( 'utf-8' ) return encoded_token | Encode the JWT token . |
40,876 | def jwt_decode_token ( token ) : try : return decode ( token , current_app . config [ 'ACCOUNTS_JWT_SECRET_KEY' ] , algorithms = [ current_app . config [ 'ACCOUNTS_JWT_ALOGORITHM' ] ] ) except DecodeError as exc : raise_from ( JWTDecodeError ( ) , exc ) except ExpiredSignatureError as exc : raise_from ( JWTExpiredToken ( ) , exc ) | Decode the JWT token . |
40,877 | def set_session_info ( app , response , ** extra ) : session_id = getattr ( session , 'sid_s' , None ) if session_id : response . headers [ 'X-Session-ID' ] = session_id if current_user . is_authenticated : response . headers [ 'X-User-ID' ] = current_user . get_id ( ) | Add X - Session - ID and X - User - ID to http response . |
40,878 | def security ( ) : sessions = SessionActivity . query_by_user ( user_id = current_user . get_id ( ) ) . all ( ) master_session = None for index , session in enumerate ( sessions ) : if SessionActivity . is_current ( session . sid_s ) : master_session = session del sessions [ index ] return render_template ( current_app . config [ 'ACCOUNTS_SETTINGS_SECURITY_TEMPLATE' ] , formclass = RevokeForm , sessions = [ master_session ] + sessions , is_current = SessionActivity . is_current ) | View for security page . |
40,879 | def revoke_session ( ) : form = RevokeForm ( request . form ) if not form . validate_on_submit ( ) : abort ( 403 ) sid_s = form . data [ 'sid_s' ] if SessionActivity . query . filter_by ( user_id = current_user . get_id ( ) , sid_s = sid_s ) . count ( ) == 1 : delete_session ( sid_s = sid_s ) db . session . commit ( ) if not SessionActivity . is_current ( sid_s = sid_s ) : flash ( 'Session {0} successfully removed.' . format ( sid_s ) , 'success' ) else : flash ( 'Unable to remove the session {0}.' . format ( sid_s ) , 'error' ) return redirect ( url_for ( 'invenio_accounts.security' ) ) | Revoke a session . |
40,880 | def query_by_expired ( cls ) : lifetime = current_app . permanent_session_lifetime expired_moment = datetime . utcnow ( ) - lifetime return cls . query . filter ( cls . created < expired_moment ) | Query to select all expired sessions . |
40,881 | def monkey_patch_flask_security ( ) : if utils . get_hmac != get_hmac : utils . get_hmac = get_hmac if utils . hash_password != hash_password : utils . hash_password = hash_password changeable . hash_password = hash_password recoverable . hash_password = hash_password registerable . hash_password = hash_password def patch_do_nothing ( * args , ** kwargs ) : pass LoginManager . _set_cookie = patch_do_nothing def patch_reload_anonym ( self , * args , ** kwargs ) : self . reload_user ( ) LoginManager . _load_from_header = patch_reload_anonym LoginManager . _load_from_request = patch_reload_anonym | Monkey - patch Flask - Security . |
40,882 | def _enable_session_activity ( self , app ) : user_logged_in . connect ( login_listener , app ) user_logged_out . connect ( logout_listener , app ) from . views . settings import blueprint from . views . security import security , revoke_session blueprint . route ( '/security/' , methods = [ 'GET' ] ) ( security ) blueprint . route ( '/sessions/revoke/' , methods = [ 'POST' ] ) ( revoke_session ) | Enable session activity . |
40,883 | def _initialize_attributes ( model_class , name , bases , attrs ) : model_class . _attributes = { } for k , v in attrs . iteritems ( ) : if isinstance ( v , Attribute ) : model_class . _attributes [ k ] = v v . name = v . name or k | Initialize the attributes of the model . |
40,884 | def _initialize_referenced ( model_class , attribute ) : def _related_objects ( self ) : return ( model_class . objects . filter ( ** { attribute . attname : self . id } ) ) klass = attribute . _target_type if isinstance ( klass , basestring ) : return ( klass , model_class , attribute ) else : related_name = ( attribute . related_name or model_class . __name__ . lower ( ) + '_set' ) setattr ( klass , related_name , property ( _related_objects ) ) | Adds a property to the target of a reference field that returns the list of associated objects . |
40,885 | def _initialize_lists ( model_class , name , bases , attrs ) : model_class . _lists = { } for k , v in attrs . iteritems ( ) : if isinstance ( v , ListField ) : model_class . _lists [ k ] = v v . name = v . name or k | Stores the list fields descriptors of a model . |
40,886 | def _initialize_references ( model_class , name , bases , attrs ) : model_class . _references = { } h = { } deferred = [ ] for k , v in attrs . iteritems ( ) : if isinstance ( v , ReferenceField ) : model_class . _references [ k ] = v v . name = v . name or k att = Attribute ( name = v . attname ) h [ v . attname ] = att setattr ( model_class , v . attname , att ) refd = _initialize_referenced ( model_class , v ) if refd : deferred . append ( refd ) attrs . update ( h ) return deferred | Stores the list of reference field descriptors of a model . |
40,887 | def _initialize_indices ( model_class , name , bases , attrs ) : model_class . _indices = [ ] for k , v in attrs . iteritems ( ) : if isinstance ( v , ( Attribute , ListField ) ) and v . indexed : model_class . _indices . append ( k ) if model_class . _meta [ 'indices' ] : model_class . _indices . extend ( model_class . _meta [ 'indices' ] ) | Stores the list of indexed attributes . |
40,888 | def _initialize_counters ( model_class , name , bases , attrs ) : model_class . _counters = [ ] for k , v in attrs . iteritems ( ) : if isinstance ( v , Counter ) : model_class . _counters . append ( k ) | Stores the list of counter fields . |
40,889 | def get_model_from_key ( key ) : _known_models = { } model_name = key . split ( ':' , 2 ) [ 0 ] for klass in Model . __subclasses__ ( ) : _known_models [ klass . __name__ ] = klass return _known_models . get ( model_name , None ) | Gets the model from a given key . |
40,890 | def from_key ( key ) : model = get_model_from_key ( key ) if model is None : raise BadKeyError try : _ , id = key . split ( ':' , 2 ) id = int ( id ) except ValueError , TypeError : raise BadKeyError return model . objects . get_by_id ( id ) | Returns the model instance based on the key . |
40,891 | def is_valid ( self ) : self . _errors = [ ] for field in self . fields : try : field . validate ( self ) except FieldValidationError , e : self . _errors . extend ( e . errors ) self . validate ( ) return not bool ( self . _errors ) | Returns True if all the fields are valid . |
40,892 | def update_attributes ( self , ** kwargs ) : attrs = self . attributes . values ( ) + self . lists . values ( ) + self . references . values ( ) for att in attrs : if att . name in kwargs : att . __set__ ( self , kwargs [ att . name ] ) | Updates the attributes of the model . |
40,893 | def save ( self ) : if not self . is_valid ( ) : return self . _errors _new = self . is_new ( ) if _new : self . _initialize_id ( ) with Mutex ( self ) : self . _write ( _new ) return True | Saves the instance to the datastore . |
40,894 | def key ( self , att = None ) : if att is not None : return self . _key [ self . id ] [ att ] else : return self . _key [ self . id ] | Returns the Redis key where the values are stored . |
40,895 | def delete ( self ) : pipeline = self . db . pipeline ( ) self . _delete_from_indices ( pipeline ) self . _delete_membership ( pipeline ) pipeline . delete ( self . key ( ) ) pipeline . execute ( ) | Deletes the object from the datastore . |
40,896 | def incr ( self , att , val = 1 ) : if att not in self . counters : raise ValueError ( "%s is not a counter." ) self . db . hincrby ( self . key ( ) , att , val ) | Increments a counter . |
40,897 | def attributes_dict ( self ) : h = { } for k in self . attributes . keys ( ) : h [ k ] = getattr ( self , k ) for k in self . lists . keys ( ) : h [ k ] = getattr ( self , k ) for k in self . references . keys ( ) : h [ k ] = getattr ( self , k ) return h | Returns the mapping of the model attributes and their values . |
40,898 | def fields ( self ) : return ( self . attributes . values ( ) + self . lists . values ( ) + self . references . values ( ) ) | Returns the list of field names of the model . |
40,899 | def exists ( cls , id ) : return bool ( redisco . get_client ( ) . exists ( cls . _key [ str ( id ) ] ) or redisco . get_client ( ) . sismember ( cls . _key [ 'all' ] , str ( id ) ) ) | Checks if the model with id exists . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.