idx
int64 0
63k
| question
stringlengths 61
4.03k
| target
stringlengths 6
1.23k
|
|---|---|---|
5,600
|
def get_ancestors ( self ) : ancestors = list ( self . get_parents ( ) ) ancestor_unique_attributes = set ( [ ( a . __class__ , a . id ) for a in ancestors ] ) ancestors_with_parents = [ a for a in ancestors if isinstance ( a , DescendantMixin ) ] for ancestor in ancestors_with_parents : for parent in ancestor . get_ancestors ( ) : if ( parent . __class__ , parent . id ) not in ancestor_unique_attributes : ancestors . append ( parent ) return ancestors
|
Get all unique instance ancestors
|
5,601
|
def has_succeed ( self ) : status_code = self . _response . status_code if status_code in [ HTTP_CODE_ZERO , HTTP_CODE_SUCCESS , HTTP_CODE_CREATED , HTTP_CODE_EMPTY , HTTP_CODE_MULTIPLE_CHOICES ] : return True if status_code in [ HTTP_CODE_BAD_REQUEST , HTTP_CODE_UNAUTHORIZED , HTTP_CODE_PERMISSION_DENIED , HTTP_CODE_NOT_FOUND , HTTP_CODE_METHOD_NOT_ALLOWED , HTTP_CODE_CONNECTION_TIMEOUT , HTTP_CODE_CONFLICT , HTTP_CODE_PRECONDITION_FAILED , HTTP_CODE_INTERNAL_SERVER_ERROR , HTTP_CODE_SERVICE_UNAVAILABLE ] : return False raise Exception ( 'Unknown status code %s.' , status_code )
|
Check if the connection has succeed
|
5,602
|
def handle_response_for_connection ( self , should_post = False ) : status_code = self . _response . status_code data = self . _response . data if data and 'errors' in data : self . _response . errors = data [ 'errors' ] if status_code in [ HTTP_CODE_SUCCESS , HTTP_CODE_CREATED , HTTP_CODE_EMPTY ] : return True if status_code == HTTP_CODE_MULTIPLE_CHOICES : return False if status_code in [ HTTP_CODE_PERMISSION_DENIED , HTTP_CODE_UNAUTHORIZED ] : if not should_post : return True return False if status_code in [ HTTP_CODE_CONFLICT , HTTP_CODE_NOT_FOUND , HTTP_CODE_BAD_REQUEST , HTTP_CODE_METHOD_NOT_ALLOWED , HTTP_CODE_PRECONDITION_FAILED , HTTP_CODE_SERVICE_UNAVAILABLE ] : if not should_post : return True return False if status_code == HTTP_CODE_INTERNAL_SERVER_ERROR : return False if status_code == HTTP_CODE_ZERO : bambou_logger . error ( "NURESTConnection: Connection error with code 0. Sending NUNURESTConnectionFailureNotification notification and exiting." ) return False bambou_logger . error ( "NURESTConnection: Report this error, because this should not happen: %s" % self . _response ) return False
|
Check if the response succeed or not .
|
5,603
|
def _did_receive_response ( self , response ) : try : data = response . json ( ) except : data = None self . _response = NURESTResponse ( status_code = response . status_code , headers = response . headers , data = data , reason = response . reason ) level = logging . WARNING if self . _response . status_code >= 300 else logging . DEBUG bambou_logger . info ( '< %s %s %s [%s] ' % ( self . _request . method , self . _request . url , self . _request . params if self . _request . params else "" , self . _response . status_code ) ) bambou_logger . log ( level , '< headers: %s' % self . _response . headers ) bambou_logger . log ( level , '< data:\n%s' % json . dumps ( self . _response . data , indent = 4 ) ) self . _callback ( self ) return self
|
Called when a response is received
|
5,604
|
def _did_timeout ( self ) : bambou_logger . debug ( 'Bambou %s on %s has timeout (timeout=%ss)..' % ( self . _request . method , self . _request . url , self . timeout ) ) self . _has_timeouted = True if self . async : self . _callback ( self ) else : return self
|
Called when a resquest has timeout
|
5,605
|
def _make_request ( self , session = None ) : if session is None : session = NURESTSession . get_current_session ( ) self . _has_timeouted = False controller = session . login_controller enterprise = controller . enterprise user_name = controller . user api_key = controller . api_key certificate = controller . certificate if self . _root_object : enterprise = self . _root_object . enterprise_name user_name = self . _root_object . user_name api_key = self . _root_object . api_key if self . _uses_authentication : self . _request . set_header ( 'X-Nuage-Organization' , enterprise ) self . _request . set_header ( 'Authorization' , controller . get_authentication_header ( user_name , api_key ) ) if controller . is_impersonating : self . _request . set_header ( 'X-Nuage-ProxyUser' , controller . impersonation ) headers = self . _request . headers data = json . dumps ( self . _request . data ) bambou_logger . info ( '> %s %s %s' % ( self . _request . method , self . _request . url , self . _request . params if self . _request . params else "" ) ) bambou_logger . debug ( '> headers: %s' % headers ) bambou_logger . debug ( '> data:\n %s' % json . dumps ( self . _request . data , indent = 4 ) ) response = self . __make_request ( requests_session = session . requests_session , method = self . _request . method , url = self . _request . url , params = self . _request . params , data = data , headers = headers , certificate = certificate ) retry_request = False if response . status_code == HTTP_CODE_MULTIPLE_CHOICES : self . _request . url += '?responseChoice=1' bambou_logger . debug ( 'Bambou got [%s] response. Trying to force response choice' % HTTP_CODE_MULTIPLE_CHOICES ) retry_request = True elif response . status_code == HTTP_CODE_AUTHENTICATION_EXPIRED and session : bambou_logger . debug ( 'Bambou got [%s] response . Trying to reconnect your session that has expired' % HTTP_CODE_AUTHENTICATION_EXPIRED ) session . reset ( ) session . start ( ) retry_request = True if retry_request : response = self . __make_request ( requests_session = session . requests_session , method = self . _request . method , url = self . _request . url , params = self . _request . params , data = data , headers = headers , certificate = certificate ) return self . _did_receive_response ( response )
|
Make a synchronous request
|
5,606
|
def __make_request ( self , requests_session , method , url , params , data , headers , certificate ) : verify = False timeout = self . timeout try : response = requests_session . request ( method = method , url = url , data = data , headers = headers , verify = verify , timeout = timeout , params = params , cert = certificate ) except requests . exceptions . SSLError : try : response = requests_session . request ( method = method , url = url , data = data , headers = headers , verify = verify , timeout = timeout , params = params , cert = certificate ) except requests . exceptions . Timeout : return self . _did_timeout ( ) except requests . exceptions . Timeout : return self . _did_timeout ( ) return response
|
Encapsulate requests call
|
5,607
|
def start ( self ) : from . nurest_session import NURESTSession session = NURESTSession . get_current_session ( ) if self . async : thread = threading . Thread ( target = self . _make_request , kwargs = { 'session' : session } ) thread . is_daemon = False thread . start ( ) return self . transaction_id return self . _make_request ( session = session )
|
Make an HTTP request with a specific method
|
5,608
|
def reset ( self ) : self . _request = None self . _response = None self . _transaction_id = uuid . uuid4 ( ) . hex
|
Reset the connection
|
5,609
|
def create ( self , price_estimate ) : kwargs = { } try : previous_price_estimate = price_estimate . get_previous ( ) except ObjectDoesNotExist : pass else : configuration = previous_price_estimate . consumption_details . configuration kwargs [ 'configuration' ] = configuration month_start = core_utils . month_start ( datetime . date ( price_estimate . year , price_estimate . month , 1 ) ) kwargs [ 'last_update_time' ] = month_start return super ( ConsumptionDetailsQuerySet , self ) . create ( price_estimate = price_estimate , ** kwargs )
|
Take configuration from previous month it it exists . Set last_update_time equals to the beginning of the month .
|
5,610
|
def get_fields ( self ) : fields = super ( BaseHookSerializer , self ) . get_fields ( ) fields [ 'event_types' ] = serializers . MultipleChoiceField ( choices = loggers . get_valid_events ( ) , required = False ) fields [ 'event_groups' ] = serializers . MultipleChoiceField ( choices = loggers . get_event_groups_keys ( ) , required = False ) return fields
|
When static declaration is used event type choices are fetched too early - even before all apps are initialized . As a result some event types are missing . When dynamic declaration is used all valid event types are available as choices .
|
5,611
|
def build_nested_field ( self , field_name , relation_info , nested_depth ) : if field_name != 'children' : return super ( PriceEstimateSerializer , self ) . build_nested_field ( field_name , relation_info , nested_depth ) field_class = self . __class__ field_kwargs = { 'read_only' : True , 'many' : True , 'context' : { 'depth' : nested_depth - 1 } } return field_class , field_kwargs
|
Use PriceEstimateSerializer to serialize estimate children
|
5,612
|
def prepare_for_reraise ( error , exc_info = None ) : if not hasattr ( error , "_type_" ) : if exc_info is None : exc_info = sys . exc_info ( ) error . _type_ = exc_info [ 0 ] error . _traceback = exc_info [ 2 ] return error
|
Prepares the exception for re - raising with reraise method .
|
5,613
|
def reraise ( error ) : if hasattr ( error , "_type_" ) : six . reraise ( type ( error ) , error , error . _traceback ) raise error
|
Re - raises the error that was processed by prepare_for_reraise earlier .
|
5,614
|
def rest_name ( cls ) : if cls . __name__ == "NURESTRootObject" or cls . __name__ == "NURESTObject" : return "Not Implemented" if cls . __rest_name__ is None : raise NotImplementedError ( '%s has no defined name. Implement rest_name property first.' % cls ) return cls . __rest_name__
|
Represents a singular REST name
|
5,615
|
def resource_name ( cls ) : if cls . __name__ == "NURESTRootObject" or cls . __name__ == "NURESTObject" : return "Not Implemented" if cls . __resource_name__ is None : raise NotImplementedError ( '%s has no defined resource name. Implement resource_name property first.' % cls ) return cls . __resource_name__
|
Represents the resource name
|
5,616
|
def _compute_args ( self , data = dict ( ) , ** kwargs ) : for name , remote_attribute in self . _attributes . items ( ) : default_value = BambouConfig . get_default_attribute_value ( self . __class__ , name , remote_attribute . attribute_type ) setattr ( self , name , default_value ) if len ( data ) > 0 : self . from_dict ( data ) for key , value in kwargs . items ( ) : if hasattr ( self , key ) : setattr ( self , key , value )
|
Compute the arguments
|
5,617
|
def children_rest_names ( self ) : names = [ ] for fetcher in self . fetchers : names . append ( fetcher . __class__ . managed_object_rest_name ( ) ) return names
|
Gets the list of all possible children ReST names .
|
5,618
|
def validate ( self ) : self . _attribute_errors = dict ( ) for local_name , attribute in self . _attributes . items ( ) : value = getattr ( self , local_name , None ) if attribute . is_required and ( value is None or value == "" ) : self . _attribute_errors [ local_name ] = { 'title' : 'Invalid input' , 'description' : 'This value is mandatory.' , 'remote_name' : attribute . remote_name } continue if value is None : continue if not self . _validate_type ( local_name , attribute . remote_name , value , attribute . attribute_type ) : continue if attribute . min_length is not None and len ( value ) < attribute . min_length : self . _attribute_errors [ local_name ] = { 'title' : 'Invalid length' , 'description' : 'Attribute %s minimum length should be %s but is %s' % ( attribute . remote_name , attribute . min_length , len ( value ) ) , 'remote_name' : attribute . remote_name } continue if attribute . max_length is not None and len ( value ) > attribute . max_length : self . _attribute_errors [ local_name ] = { 'title' : 'Invalid length' , 'description' : 'Attribute %s maximum length should be %s but is %s' % ( attribute . remote_name , attribute . max_length , len ( value ) ) , 'remote_name' : attribute . remote_name } continue if attribute . attribute_type == list : valid = True for item in value : if valid is True : valid = self . _validate_value ( local_name , attribute , item ) else : self . _validate_value ( local_name , attribute , value ) return self . is_valid ( )
|
Validate the current object attributes .
|
5,619
|
def expose_attribute ( self , local_name , attribute_type , remote_name = None , display_name = None , is_required = False , is_readonly = False , max_length = None , min_length = None , is_identifier = False , choices = None , is_unique = False , is_email = False , is_login = False , is_editable = True , is_password = False , can_order = False , can_search = False , subtype = None , min_value = None , max_value = None ) : if remote_name is None : remote_name = local_name if display_name is None : display_name = local_name attribute = NURemoteAttribute ( local_name = local_name , remote_name = remote_name , attribute_type = attribute_type ) attribute . display_name = display_name attribute . is_required = is_required attribute . is_readonly = is_readonly attribute . min_length = min_length attribute . max_length = max_length attribute . is_editable = is_editable attribute . is_identifier = is_identifier attribute . choices = choices attribute . is_unique = is_unique attribute . is_email = is_email attribute . is_login = is_login attribute . is_password = is_password attribute . can_order = can_order attribute . can_search = can_search attribute . subtype = subtype attribute . min_value = min_value attribute . max_value = max_value self . _attributes [ local_name ] = attribute
|
Expose local_name as remote_name
|
5,620
|
def is_owned_by_current_user ( self ) : from bambou . nurest_root_object import NURESTRootObject root_object = NURESTRootObject . get_default_root_object ( ) return self . _owner == root_object . id
|
Check if the current user owns the object
|
5,621
|
def parent_for_matching_rest_name ( self , rest_names ) : parent = self while parent : if parent . rest_name in rest_names : return parent parent = parent . parent_object return None
|
Return parent that matches a rest name
|
5,622
|
def genealogic_types ( self ) : types = [ ] parent = self while parent : types . append ( parent . rest_name ) parent = parent . parent_object return types
|
Get genealogic types
|
5,623
|
def genealogic_ids ( self ) : ids = [ ] parent = self while parent : ids . append ( parent . id ) parent = parent . parent_object return ids
|
Get all genealogic ids
|
5,624
|
def add_child ( self , child ) : rest_name = child . rest_name children = self . fetcher_for_rest_name ( rest_name ) if children is None : raise InternalConsitencyError ( 'Could not find fetcher with name %s while adding %s in parent %s' % ( rest_name , child , self ) ) if child not in children : child . parent_object = self children . append ( child )
|
Add a child
|
5,625
|
def remove_child ( self , child ) : rest_name = child . rest_name children = self . fetcher_for_rest_name ( rest_name ) target_child = None for local_child in children : if local_child . id == child . id : target_child = local_child break if target_child : target_child . parent_object = None children . remove ( target_child )
|
Remove a child
|
5,626
|
def to_dict ( self ) : dictionary = dict ( ) for local_name , attribute in self . _attributes . items ( ) : remote_name = attribute . remote_name if hasattr ( self , local_name ) : value = getattr ( self , local_name ) if isinstance ( value , NURESTObject ) : value = value . to_dict ( ) if isinstance ( value , list ) and len ( value ) > 0 and isinstance ( value [ 0 ] , NURESTObject ) : tmp = list ( ) for obj in value : tmp . append ( obj . to_dict ( ) ) value = tmp dictionary [ remote_name ] = value else : pass return dictionary
|
Converts the current object into a Dictionary using all exposed ReST attributes .
|
5,627
|
def from_dict ( self , dictionary ) : for remote_name , remote_value in dictionary . items ( ) : local_name = next ( ( name for name , attribute in self . _attributes . items ( ) if attribute . remote_name == remote_name ) , None ) if local_name : setattr ( self , local_name , remote_value ) else : pass
|
Sets all the exposed ReST attribues from the given dictionary
|
5,628
|
def delete ( self , response_choice = 1 , async = False , callback = None ) : return self . _manage_child_object ( nurest_object = self , method = HTTP_METHOD_DELETE , async = async , callback = callback , response_choice = response_choice )
|
Delete object and call given callback in case of call .
|
5,629
|
def save ( self , response_choice = None , async = False , callback = None ) : return self . _manage_child_object ( nurest_object = self , method = HTTP_METHOD_PUT , async = async , callback = callback , response_choice = response_choice )
|
Update object and call given callback in case of async call
|
5,630
|
def send_request ( self , request , async = False , local_callback = None , remote_callback = None , user_info = None ) : callbacks = dict ( ) if local_callback : callbacks [ 'local' ] = local_callback if remote_callback : callbacks [ 'remote' ] = remote_callback connection = NURESTConnection ( request = request , async = async , callback = self . _did_receive_response , callbacks = callbacks ) connection . user_info = user_info return connection . start ( )
|
Sends a request calls the local callback then the remote callback in case of async call
|
5,631
|
def _manage_child_object ( self , nurest_object , method = HTTP_METHOD_GET , async = False , callback = None , handler = None , response_choice = None , commit = False ) : url = None if method == HTTP_METHOD_POST : url = self . get_resource_url_for_child_type ( nurest_object . __class__ ) else : url = self . get_resource_url ( ) if response_choice is not None : url += '?responseChoice=%s' % response_choice request = NURESTRequest ( method = method , url = url , data = nurest_object . to_dict ( ) ) user_info = { 'nurest_object' : nurest_object , 'commit' : commit } if not handler : handler = self . _did_perform_standard_operation if async : return self . send_request ( request = request , async = async , local_callback = handler , remote_callback = callback , user_info = user_info ) else : connection = self . send_request ( request = request , user_info = user_info ) return handler ( connection )
|
Low level child management . Send given HTTP method with given nurest_object to given ressource of current object
|
5,632
|
def _did_receive_response ( self , connection ) : if connection . has_timeouted : bambou_logger . info ( "NURESTConnection has timeout." ) return has_callbacks = connection . has_callbacks ( ) should_post = not has_callbacks if connection . handle_response_for_connection ( should_post = should_post ) and has_callbacks : callback = connection . callbacks [ 'local' ] callback ( connection )
|
Receive a response from the connection
|
5,633
|
def _did_retrieve ( self , connection ) : response = connection . response try : self . from_dict ( response . data [ 0 ] ) except : pass return self . _did_perform_standard_operation ( connection )
|
Callback called after fetching the object
|
5,634
|
def _did_perform_standard_operation ( self , connection ) : if connection . async : callback = connection . callbacks [ 'remote' ] if connection . user_info and 'nurest_object' in connection . user_info : callback ( connection . user_info [ 'nurest_object' ] , connection ) else : callback ( self , connection ) else : if connection . response . status_code >= 400 and BambouConfig . _should_raise_bambou_http_error : raise BambouHTTPError ( connection = connection ) if connection . user_info and 'nurest_objects' in connection . user_info : if connection . user_info [ 'commit' ] : for nurest_object in connection . user_info [ 'nurest_objects' ] : self . add_child ( nurest_object ) return ( connection . user_info [ 'nurest_objects' ] , connection ) if connection . user_info and 'nurest_object' in connection . user_info : if connection . user_info [ 'commit' ] : self . add_child ( connection . user_info [ 'nurest_object' ] ) return ( connection . user_info [ 'nurest_object' ] , connection ) return ( self , connection )
|
Performs standard opertions
|
5,635
|
def create_child ( self , nurest_object , response_choice = None , async = False , callback = None , commit = True ) : return self . _manage_child_object ( nurest_object = nurest_object , async = async , method = HTTP_METHOD_POST , callback = callback , handler = self . _did_create_child , response_choice = response_choice , commit = commit )
|
Add given nurest_object to the current object
|
5,636
|
def instantiate_child ( self , nurest_object , from_template , response_choice = None , async = False , callback = None , commit = True ) : if not from_template . id : raise InternalConsitencyError ( "Cannot instantiate a child from a template with no ID: %s." % from_template ) nurest_object . template_id = from_template . id return self . _manage_child_object ( nurest_object = nurest_object , async = async , method = HTTP_METHOD_POST , callback = callback , handler = self . _did_create_child , response_choice = response_choice , commit = commit )
|
Instantiate an nurest_object from a template object
|
5,637
|
def _did_create_child ( self , connection ) : response = connection . response try : connection . user_info [ 'nurest_object' ] . from_dict ( response . data [ 0 ] ) except Exception : pass return self . _did_perform_standard_operation ( connection )
|
Callback called after adding a new child nurest_object
|
5,638
|
def assign ( self , objects , nurest_object_type , async = False , callback = None , commit = True ) : ids = list ( ) for nurest_object in objects : ids . append ( nurest_object . id ) url = self . get_resource_url_for_child_type ( nurest_object_type ) request = NURESTRequest ( method = HTTP_METHOD_PUT , url = url , data = ids ) user_info = { 'nurest_objects' : objects , 'commit' : commit } if async : return self . send_request ( request = request , async = async , local_callback = self . _did_perform_standard_operation , remote_callback = callback , user_info = user_info ) else : connection = self . send_request ( request = request , user_info = user_info ) return self . _did_perform_standard_operation ( connection )
|
Reference a list of objects into the current resource
|
5,639
|
def rest_equals ( self , rest_object ) : if not self . equals ( rest_object ) : return False return self . to_dict ( ) == rest_object . to_dict ( )
|
Compare objects REST attributes
|
5,640
|
def equals ( self , rest_object ) : if self . _is_dirty : return False if rest_object is None : return False if not isinstance ( rest_object , NURESTObject ) : raise TypeError ( 'The object is not a NURESTObject %s' % rest_object ) if self . rest_name != rest_object . rest_name : return False if self . id and rest_object . id : return self . id == rest_object . id if self . local_id and rest_object . local_id : return self . local_id == rest_object . local_id return False
|
Compare with another object
|
5,641
|
def get_ip_address ( request ) : if 'HTTP_X_FORWARDED_FOR' in request . META : return request . META [ 'HTTP_X_FORWARDED_FOR' ] . split ( ',' ) [ 0 ] . strip ( ) else : return request . META [ 'REMOTE_ADDR' ]
|
Correct IP address is expected as first element of HTTP_X_FORWARDED_FOR or REMOTE_ADDR
|
5,642
|
def get_estimates_without_scope_in_month ( self , customer ) : estimates = self . get_price_estimates_for_customer ( customer ) if not estimates : return [ ] tables = { model : collections . defaultdict ( list ) for model in self . get_estimated_models ( ) } dates = set ( ) for estimate in estimates : date = ( estimate . year , estimate . month ) dates . add ( date ) cls = estimate . content_type . model_class ( ) for model , table in tables . items ( ) : if issubclass ( cls , model ) : table [ date ] . append ( estimate ) break invalid_estimates = [ ] for date in dates : if any ( map ( lambda table : len ( table [ date ] ) == 0 , tables . values ( ) ) ) : for table in tables . values ( ) : invalid_estimates . extend ( table [ date ] ) print ( invalid_estimates ) return invalid_estimates
|
It is expected that valid row for each month contains at least one price estimate for customer service setting service service project link project and resource . Otherwise all price estimates in the row should be deleted .
|
5,643
|
def get_default_value ( self ) : if self . choices : return self . choices [ 0 ] value = self . attribute_type ( ) if self . attribute_type is time : value = int ( value ) elif self . attribute_type is str : value = "A" if self . min_length : if self . attribute_type is str : value = value . ljust ( self . min_length , 'a' ) elif self . attribute_type is int : value = self . min_length elif self . max_length : if self . attribute_type is str : value = value . ljust ( self . max_length , 'a' ) elif self . attribute_type is int : value = self . max_length return value
|
Get a default value of the attribute_type
|
5,644
|
def get_min_value ( self ) : value = self . get_default_value ( ) if self . attribute_type is str : min_value = value [ : self . min_length - 1 ] elif self . attribute_type is int : min_value = self . min_length - 1 else : raise TypeError ( 'Attribute %s can not have a minimum value' % self . local_name ) return min_value
|
Get the minimum value
|
5,645
|
def get_max_value ( self ) : value = self . get_default_value ( ) if self . attribute_type is str : max_value = value . ljust ( self . max_length + 1 , 'a' ) elif self . attribute_type is int : max_value = self . max_length + 1 else : raise TypeError ( 'Attribute %s can not have a maximum value' % self . local_name ) return max_value
|
Get the maximum value
|
5,646
|
def get_api_root_view ( self , api_urls = None ) : api_root_dict = OrderedDict ( ) list_name = self . routes [ 0 ] . name for prefix , viewset , basename in self . registry : api_root_dict [ prefix ] = list_name . format ( basename = basename ) class APIRootView ( views . APIView ) : _ignore_model_permissions = True exclude_from_schema = True def get ( self , request , * args , ** kwargs ) : ret = OrderedDict ( ) namespace = request . resolver_match . namespace for key , url_name in sorted ( api_root_dict . items ( ) , key = itemgetter ( 0 ) ) : if namespace : url_name = namespace + ':' + url_name try : ret [ key ] = reverse ( url_name , args = args , kwargs = kwargs , request = request , format = kwargs . get ( 'format' , None ) ) except NoReverseMatch : continue return Response ( ret ) return APIRootView . as_view ( )
|
Return a basic root view .
|
5,647
|
def get_default_base_name ( self , viewset ) : queryset = getattr ( viewset , 'queryset' , None ) if queryset is not None : get_url_name = getattr ( queryset . model , 'get_url_name' , None ) if get_url_name is not None : return get_url_name ( ) return super ( SortedDefaultRouter , self ) . get_default_base_name ( viewset )
|
Attempt to automatically determine base name using get_url_name .
|
5,648
|
def change_customer_nc_users_quota ( sender , structure , user , role , signal , ** kwargs ) : assert signal in ( signals . structure_role_granted , signals . structure_role_revoked ) , 'Handler "change_customer_nc_users_quota" has to be used only with structure_role signals' assert sender in ( Customer , Project ) , 'Handler "change_customer_nc_users_quota" works only with Project and Customer models' if sender == Customer : customer = structure elif sender == Project : customer = structure . customer customer_users = customer . get_users ( ) customer . set_quota_usage ( Customer . Quotas . nc_user_count , customer_users . count ( ) )
|
Modify nc_user_count quota usage on structure role grant or revoke
|
5,649
|
def delete_service_settings_on_service_delete ( sender , instance , ** kwargs ) : service = instance try : service_settings = service . settings except ServiceSettings . DoesNotExist : return if not service_settings . shared : service . settings . delete ( )
|
Delete not shared service settings without services
|
5,650
|
def delete_service_settings_on_scope_delete ( sender , instance , ** kwargs ) : for service_settings in ServiceSettings . objects . filter ( scope = instance ) : service_settings . unlink_descendants ( ) service_settings . delete ( )
|
If VM that contains service settings were deleted - all settings resources could be safely deleted from NC .
|
5,651
|
def url ( self , url ) : if url and url . endswith ( '/' ) : url = url [ : - 1 ] self . _url = url
|
Set API URL endpoint
|
5,652
|
def get_authentication_header ( self , user = None , api_key = None , password = None , certificate = None ) : if not user : user = self . user if not api_key : api_key = self . api_key if not password : password = self . password if not password : password = self . password if not certificate : certificate = self . _certificate if certificate : return "XREST %s" % urlsafe_b64encode ( "{}:" . format ( user ) . encode ( 'utf-8' ) ) . decode ( 'utf-8' ) if api_key : return "XREST %s" % urlsafe_b64encode ( "{}:{}" . format ( user , api_key ) . encode ( 'utf-8' ) ) . decode ( 'utf-8' ) return "XREST %s" % urlsafe_b64encode ( "{}:{}" . format ( user , password ) . encode ( 'utf-8' ) ) . decode ( 'utf-8' )
|
Return authenication string to place in Authorization Header
|
5,653
|
def impersonate ( self , user , enterprise ) : if not user or not enterprise : raise ValueError ( 'You must set a user name and an enterprise name to begin impersonification' ) self . _is_impersonating = True self . _impersonation = "%s@%s" % ( user , enterprise )
|
Impersonate a user in a enterprise
|
5,654
|
def equals ( self , controller ) : if controller is None : return False return self . user == controller . user and self . enterprise == controller . enterprise and self . url == controller . url
|
Verify if the controller corresponds to the current one .
|
5,655
|
def release ( self , conn ) : if conn . in_transaction : raise InvalidRequestError ( "Cannot release a connection with " "not finished transaction" ) raw = conn . connection res = yield from self . _pool . release ( raw ) return res
|
Revert back connection to pool .
|
5,656
|
def get_configuration ( cls , resource ) : strategy = cls . _get_strategy ( resource . __class__ ) return strategy . get_configuration ( resource )
|
Return how much consumables are used by resource with current configuration .
|
5,657
|
def get_version ( ) : import imp import os mod = imp . load_source ( 'version' , os . path . join ( 'skdata' , '__init__.py' ) ) return mod . __version__
|
Obtain the version number
|
5,658
|
def accept ( self , request , uuid = None ) : invitation = self . get_object ( ) if invitation . state != models . Invitation . State . PENDING : raise ValidationError ( _ ( 'Only pending invitation can be accepted.' ) ) elif invitation . civil_number and invitation . civil_number != request . user . civil_number : raise ValidationError ( _ ( 'User has an invalid civil number.' ) ) if invitation . project : if invitation . project . has_user ( request . user ) : raise ValidationError ( _ ( 'User already has role within this project.' ) ) elif invitation . customer . has_user ( request . user ) : raise ValidationError ( _ ( 'User already has role within this customer.' ) ) if settings . WALDUR_CORE [ 'VALIDATE_INVITATION_EMAIL' ] and invitation . email != request . user . email : raise ValidationError ( _ ( 'Invitation and user emails mismatch.' ) ) replace_email = bool ( request . data . get ( 'replace_email' ) ) invitation . accept ( request . user , replace_email = replace_email ) return Response ( { 'detail' : _ ( 'Invitation has been successfully accepted.' ) } , status = status . HTTP_200_OK )
|
Accept invitation for current user .
|
5,659
|
def scope_deletion ( sender , instance , ** kwargs ) : is_resource = isinstance ( instance , structure_models . ResourceMixin ) if is_resource and getattr ( instance , 'PERFORM_UNLINK' , False ) : _resource_unlink ( resource = instance ) elif is_resource and not getattr ( instance , 'PERFORM_UNLINK' , False ) : _resource_deletion ( resource = instance ) elif isinstance ( instance , structure_models . Customer ) : _customer_deletion ( customer = instance ) else : for price_estimate in models . PriceEstimate . objects . filter ( scope = instance ) : price_estimate . init_details ( )
|
Run different actions on price estimate scope deletion .
|
5,660
|
def _resource_deletion ( resource ) : if resource . __class__ not in CostTrackingRegister . registered_resources : return new_configuration = { } price_estimate = models . PriceEstimate . update_resource_estimate ( resource , new_configuration ) price_estimate . init_details ( )
|
Recalculate consumption details and save resource details
|
5,661
|
def resource_update ( sender , instance , created = False , ** kwargs ) : resource = instance try : new_configuration = CostTrackingRegister . get_configuration ( resource ) except ResourceNotRegisteredError : return models . PriceEstimate . update_resource_estimate ( resource , new_configuration , raise_exception = not _is_in_celery_task ( ) ) if created : _create_historical_estimates ( resource , new_configuration )
|
Update resource consumption details and price estimate if its configuration has changed . Create estimates for previous months if resource was created not in current month .
|
5,662
|
def resource_quota_update ( sender , instance , ** kwargs ) : quota = instance resource = quota . scope try : new_configuration = CostTrackingRegister . get_configuration ( resource ) except ResourceNotRegisteredError : return models . PriceEstimate . update_resource_estimate ( resource , new_configuration , raise_exception = not _is_in_celery_task ( ) )
|
Update resource consumption details and price estimate if its configuration has changed
|
5,663
|
def _create_historical_estimates ( resource , configuration ) : today = timezone . now ( ) month_start = core_utils . month_start ( today ) while month_start > resource . created : month_start -= relativedelta ( months = 1 ) models . PriceEstimate . create_historical ( resource , configuration , max ( month_start , resource . created ) )
|
Create consumption details and price estimates for past months .
|
5,664
|
def IPYTHON_MAIN ( ) : import pkg_resources runner_frame = inspect . getouterframes ( inspect . currentframe ( ) ) [ - 2 ] return ( getattr ( runner_frame , "function" , None ) == pkg_resources . load_entry_point ( "ipython" , "console_scripts" , "ipython" ) . __name__ )
|
Decide if the Ipython command line is running code .
|
5,665
|
def register_model ( cls , model ) : rest_name = model . rest_name resource_name = model . resource_name if rest_name not in cls . _model_rest_name_registry : cls . _model_rest_name_registry [ rest_name ] = [ model ] cls . _model_resource_name_registry [ resource_name ] = [ model ] elif model not in cls . _model_rest_name_registry [ rest_name ] : cls . _model_rest_name_registry [ rest_name ] . append ( model ) cls . _model_resource_name_registry [ resource_name ] . append ( model )
|
Register a model class according to its remote name
|
5,666
|
def get_first_model_with_rest_name ( cls , rest_name ) : models = cls . get_models_with_rest_name ( rest_name ) if len ( models ) > 0 : return models [ 0 ] return None
|
Get the first model corresponding to a rest_name
|
5,667
|
def get_first_model_with_resource_name ( cls , resource_name ) : models = cls . get_models_with_resource_name ( resource_name ) if len ( models ) > 0 : return models [ 0 ] return None
|
Get the first model corresponding to a resource_name
|
5,668
|
def find_spec ( self , fullname , target = None ) : spec = super ( ) . find_spec ( fullname , target = target ) if spec is None : original = fullname if "." in fullname : original , fullname = fullname . rsplit ( "." , 1 ) else : original , fullname = "" , original if "_" in fullname : files = fuzzy_file_search ( self . path , fullname ) if files : file = Path ( sorted ( files ) [ 0 ] ) spec = super ( ) . find_spec ( ( original + "." + file . stem . split ( "." , 1 ) [ 0 ] ) . lstrip ( "." ) , target = target ) fullname = ( original + "." + fullname ) . lstrip ( "." ) if spec and fullname != spec . name : spec = FuzzySpec ( spec . name , spec . loader , origin = spec . origin , loader_state = spec . loader_state , alias = fullname , is_package = bool ( spec . submodule_search_locations ) , ) return spec
|
Try to finder the spec and if it cannot be found use the underscore starring syntax to identify potential matches .
|
5,669
|
def save ( self , async = False , callback = None , encrypted = True ) : if self . _new_password and encrypted : self . password = Sha1 . encrypt ( self . _new_password ) controller = NURESTSession . get_current_session ( ) . login_controller controller . password = self . _new_password controller . api_key = None data = json . dumps ( self . to_dict ( ) ) request = NURESTRequest ( method = HTTP_METHOD_PUT , url = self . get_resource_url ( ) , data = data ) if async : return self . send_request ( request = request , async = async , local_callback = self . _did_save , remote_callback = callback ) else : connection = self . send_request ( request = request ) return self . _did_save ( connection )
|
Updates the user and perform the callback method
|
5,670
|
def _did_save ( self , connection ) : self . _new_password = None controller = NURESTSession . get_current_session ( ) . login_controller controller . password = None controller . api_key = self . api_key if connection . async : callback = connection . callbacks [ 'remote' ] if connection . user_info : callback ( connection . user_info , connection ) else : callback ( self , connection ) else : return ( self , connection )
|
Launched when save has been successfully executed
|
5,671
|
def fetch ( self , async = False , callback = None ) : request = NURESTRequest ( method = HTTP_METHOD_GET , url = self . get_resource_url ( ) ) if async : return self . send_request ( request = request , async = async , local_callback = self . _did_fetch , remote_callback = callback ) else : connection = self . send_request ( request = request ) return self . _did_retrieve ( connection )
|
Fetch all information about the current object
|
5,672
|
def _fabtabular ( ) : import csv import sys from pkg_resources import resource_filename data = resource_filename ( __package__ , 'iso-639-3.tab' ) inverted = resource_filename ( __package__ , 'iso-639-3_Name_Index.tab' ) macro = resource_filename ( __package__ , 'iso-639-3-macrolanguages.tab' ) part5 = resource_filename ( __package__ , 'iso639-5.tsv' ) part2 = resource_filename ( __package__ , 'iso639-2.tsv' ) part1 = resource_filename ( __package__ , 'iso639-1.tsv' ) if sys . version_info [ 0 ] == 3 : from functools import partial global open open = partial ( open , encoding = 'utf-8' ) data_fo = open ( data ) inverted_fo = open ( inverted ) macro_fo = open ( macro ) part5_fo = open ( part5 ) part2_fo = open ( part2 ) part1_fo = open ( part1 ) with data_fo as u : with inverted_fo as i : with macro_fo as m : with part5_fo as p5 : with part2_fo as p2 : with part1_fo as p1 : return ( list ( csv . reader ( u , delimiter = '\t' ) ) [ 1 : ] , list ( csv . reader ( i , delimiter = '\t' ) ) [ 1 : ] , list ( csv . reader ( m , delimiter = '\t' ) ) [ 1 : ] , list ( csv . reader ( p5 , delimiter = '\t' ) ) [ 1 : ] , list ( csv . reader ( p2 , delimiter = '\t' ) ) [ 1 : ] , list ( csv . reader ( p1 , delimiter = '\t' ) ) [ 1 : ] )
|
This function retrieves the ISO 639 and inverted names datasets as tsv files and returns them as lists .
|
5,673
|
def users ( self , request , uuid = None ) : project = self . get_object ( ) queryset = project . get_users ( ) filter_backend = filters . UserConcatenatedNameOrderingBackend ( ) queryset = filter_backend . filter_queryset ( request , queryset , self ) queryset = self . paginate_queryset ( queryset ) serializer = self . get_serializer ( queryset , many = True ) return self . get_paginated_response ( serializer . data )
|
A list of users connected to the project
|
5,674
|
def can_user_update_settings ( request , view , obj = None ) : if obj is None : return if obj . customer and not obj . shared : return permissions . is_owner ( request , view , obj ) else : return permissions . is_staff ( request , view , obj )
|
Only staff can update shared settings otherwise user has to be an owner of the settings .
|
5,675
|
def list ( self , request , * args , ** kwargs ) : return super ( ServicesViewSet , self ) . list ( request , * args , ** kwargs )
|
Filter services by type ^^^^^^^^^^^^^^^^^^^^^^^
|
5,676
|
def _require_staff_for_shared_settings ( request , view , obj = None ) : if obj is None : return if obj . settings . shared and not request . user . is_staff : raise PermissionDenied ( _ ( 'Only staff users are allowed to import resources from shared services.' ) )
|
Allow to execute action only if service settings are not shared or user is staff
|
5,677
|
def unlink ( self , request , uuid = None ) : service = self . get_object ( ) service . unlink_descendants ( ) self . perform_destroy ( service ) return Response ( status = status . HTTP_204_NO_CONTENT )
|
Unlink all related resources service project link and service itself .
|
5,678
|
def get_aggregator_quotas ( self , quota ) : ancestors = quota . scope . get_quota_ancestors ( ) aggregator_quotas = [ ] for ancestor in ancestors : for ancestor_quota_field in ancestor . get_quotas_fields ( field_class = AggregatorQuotaField ) : if ancestor_quota_field . get_child_quota_name ( ) == quota . name : aggregator_quotas . append ( ancestor . quotas . get ( name = ancestor_quota_field ) ) return aggregator_quotas
|
Fetch ancestors quotas that have the same name and are registered as aggregator quotas .
|
5,679
|
def subscribe ( self , handler ) : assert callable ( handler ) , "Invalid handler %s" % handler self . handlers . append ( handler )
|
Adds a new event handler .
|
5,680
|
def on ( self , event , handler ) : event_hook = self . get_or_create ( event ) event_hook . subscribe ( handler ) return self
|
Attaches the handler to the specified event .
|
5,681
|
def off ( self , event , handler ) : event_hook = self . get_or_create ( event ) event_hook . unsubscribe ( handler ) return self
|
Detaches the handler from the specified event .
|
5,682
|
def trigger ( self , event , * args ) : event_hook = self . get_or_create ( event ) event_hook . trigger ( * args ) return self
|
Triggers the specified event by invoking EventHook . trigger under the hood .
|
5,683
|
def safe_trigger ( self , event , * args ) : event_hook = self . get_or_create ( event ) event_hook . safe_trigger ( * args ) return self
|
Safely triggers the specified event by invoking EventHook . safe_trigger under the hood .
|
5,684
|
def cancel_expired_invitations ( invitations = None ) : expiration_date = timezone . now ( ) - settings . WALDUR_CORE [ 'INVITATION_LIFETIME' ] if not invitations : invitations = models . Invitation . objects . filter ( state = models . Invitation . State . PENDING ) invitations = invitations . filter ( created__lte = expiration_date ) invitations . update ( state = models . Invitation . State . EXPIRED )
|
Invitation lifetime must be specified in Waldur Core settings with parameter INVITATION_LIFETIME . If invitation creation time is less than expiration time the invitation will set as expired .
|
5,685
|
def _prepare_abi ( self , jsonabi ) : self . signatures = { } for element_description in jsonabi : abi_e = AbiMethod ( element_description ) if abi_e [ "type" ] == "constructor" : self . signatures [ b"__constructor__" ] = abi_e elif abi_e [ "type" ] == "fallback" : abi_e . setdefault ( "inputs" , [ ] ) self . signatures [ b"__fallback__" ] = abi_e elif abi_e [ "type" ] == "function" : if abi_e . get ( "signature" ) : self . signatures [ Utils . str_to_bytes ( abi_e [ "signature" ] ) ] = abi_e elif abi_e [ "type" ] == "event" : self . signatures [ b"__event__" ] = abi_e else : raise Exception ( "Invalid abi type: %s - %s - %s" % ( abi_e . get ( "type" ) , element_description , abi_e ) )
|
Prepare the contract json abi for sighash lookups and fast access
|
5,686
|
def describe_input ( self , s ) : signatures = self . signatures . items ( ) for sighash , method in signatures : if sighash is None or sighash . startswith ( b"__" ) : continue if s . startswith ( sighash ) : s = s [ len ( sighash ) : ] types_def = self . signatures . get ( sighash ) [ "inputs" ] types = [ t [ "type" ] for t in types_def ] names = [ t [ "name" ] for t in types_def ] if not len ( s ) : values = len ( types ) * [ "<nA>" ] else : values = decode_abi ( types , s ) method . inputs = [ { "type" : t , "name" : n , "data" : v } for t , n , v in list ( zip ( types , names , values ) ) ] return method else : method = AbiMethod ( { "type" : "fallback" , "name" : "__fallback__" , "inputs" : [ ] , "outputs" : [ ] } ) types_def = self . signatures . get ( b"__fallback__" , { "inputs" : [ ] } ) [ "inputs" ] types = [ t [ "type" ] for t in types_def ] names = [ t [ "name" ] for t in types_def ] values = decode_abi ( types , s ) method . inputs = [ { "type" : t , "name" : n , "data" : v } for t , n , v in list ( zip ( types , names , values ) ) ] return method
|
Describe the input bytesequence s based on the loaded contract abi definition
|
5,687
|
def assert_is ( expected , actual , message = None , extra = None ) : assert expected is actual , _assert_fail_message ( message , expected , actual , "is not" , extra )
|
Raises an AssertionError if expected is not actual .
|
5,688
|
def assert_is_not ( expected , actual , message = None , extra = None ) : assert expected is not actual , _assert_fail_message ( message , expected , actual , "is" , extra )
|
Raises an AssertionError if expected is actual .
|
5,689
|
def assert_eq ( expected , actual , message = None , tolerance = None , extra = None ) : if tolerance is None : assert expected == actual , _assert_fail_message ( message , expected , actual , "!=" , extra ) else : assert isinstance ( tolerance , _number_types ) , ( "tolerance parameter to assert_eq must be a number: %r" % tolerance ) assert isinstance ( expected , _number_types ) and isinstance ( actual , _number_types ) , ( "parameters must be numbers when tolerance is specified: %r, %r" % ( expected , actual ) ) diff = abs ( expected - actual ) assert diff <= tolerance , _assert_fail_message ( message , expected , actual , "is more than %r away from" % tolerance , extra )
|
Raises an AssertionError if expected ! = actual .
|
5,690
|
def assert_dict_eq ( expected , actual , number_tolerance = None , dict_path = [ ] ) : assert_is_instance ( expected , dict ) assert_is_instance ( actual , dict ) expected_keys = set ( expected . keys ( ) ) actual_keys = set ( actual . keys ( ) ) assert expected_keys <= actual_keys , "Actual dict at %s is missing keys: %r" % ( _dict_path_string ( dict_path ) , expected_keys - actual_keys , ) assert actual_keys <= expected_keys , "Actual dict at %s has extra keys: %r" % ( _dict_path_string ( dict_path ) , actual_keys - expected_keys , ) for k in expected_keys : key_path = dict_path + [ k ] assert_is_instance ( actual [ k ] , type ( expected [ k ] ) , extra = "Types don't match for %s" % _dict_path_string ( key_path ) , ) assert_is_instance ( expected [ k ] , type ( actual [ k ] ) , extra = "Types don't match for %s" % _dict_path_string ( key_path ) , ) if isinstance ( actual [ k ] , dict ) : assert_dict_eq ( expected [ k ] , actual [ k ] , number_tolerance = number_tolerance , dict_path = key_path , ) elif isinstance ( actual [ k ] , _number_types ) : assert_eq ( expected [ k ] , actual [ k ] , extra = "Value doesn't match for %s" % _dict_path_string ( key_path ) , tolerance = number_tolerance , ) else : assert_eq ( expected [ k ] , actual [ k ] , extra = "Value doesn't match for %s" % _dict_path_string ( key_path ) , )
|
Asserts that two dictionaries are equal producing a custom message if they are not .
|
5,691
|
def assert_gt ( left , right , message = None , extra = None ) : assert left > right , _assert_fail_message ( message , left , right , "<=" , extra )
|
Raises an AssertionError if left_hand < = right_hand .
|
5,692
|
def assert_ge ( left , right , message = None , extra = None ) : assert left >= right , _assert_fail_message ( message , left , right , "<" , extra )
|
Raises an AssertionError if left_hand < right_hand .
|
5,693
|
def assert_lt ( left , right , message = None , extra = None ) : assert left < right , _assert_fail_message ( message , left , right , ">=" , extra )
|
Raises an AssertionError if left_hand > = right_hand .
|
5,694
|
def assert_le ( left , right , message = None , extra = None ) : assert left <= right , _assert_fail_message ( message , left , right , ">" , extra )
|
Raises an AssertionError if left_hand > right_hand .
|
5,695
|
def assert_in ( obj , seq , message = None , extra = None ) : assert obj in seq , _assert_fail_message ( message , obj , seq , "is not in" , extra )
|
Raises an AssertionError if obj is not in seq .
|
5,696
|
def assert_not_in ( obj , seq , message = None , extra = None ) : if isinstance ( seq , six . string_types ) and obj in seq and len ( seq ) > 200 : index = seq . find ( obj ) start_index = index - 50 if start_index > 0 : truncated = "(truncated) ..." else : truncated = "" start_index = 0 end_index = index + len ( obj ) + 50 truncated += seq [ start_index : end_index ] if end_index < len ( seq ) : truncated += "... (truncated)" assert False , _assert_fail_message ( message , obj , truncated , "is in" , extra ) assert obj not in seq , _assert_fail_message ( message , obj , seq , "is in" , extra )
|
Raises an AssertionError if obj is in iter .
|
5,697
|
def assert_in_with_tolerance ( obj , seq , tolerance , message = None , extra = None ) : for i in seq : try : assert_eq ( obj , i , tolerance = tolerance , message = message , extra = extra ) return except AssertionError : pass assert False , _assert_fail_message ( message , obj , seq , "is not in" , extra )
|
Raises an AssertionError if obj is not in seq using assert_eq cmp .
|
5,698
|
def assert_is_substring ( substring , subject , message = None , extra = None ) : assert ( ( subject is not None ) and ( substring is not None ) and ( subject . find ( substring ) != - 1 ) ) , _assert_fail_message ( message , substring , subject , "is not in" , extra )
|
Raises an AssertionError if substring is not a substring of subject .
|
5,699
|
def assert_is_not_substring ( substring , subject , message = None , extra = None ) : assert ( ( subject is not None ) and ( substring is not None ) and ( subject . find ( substring ) == - 1 ) ) , _assert_fail_message ( message , substring , subject , "is in" , extra )
|
Raises an AssertionError if substring is a substring of subject .
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.