idx
int64
0
251k
question
stringlengths
53
3.53k
target
stringlengths
5
1.23k
len_question
int64
20
893
len_target
int64
3
238
8,600
async def request ( self , method , url , params = None , headers = None , data = None , json = None , token_refresh_attempts = 2 , * * kwargs ) : if all ( [ data , json ] ) : msg = ( '"data" and "json" request parameters can not be used ' 'at the same time' ) logging . warn ( msg ) raise exceptions . GCPHTTPError ( msg ) req_headers = headers or { } req_headers . update ( _utils . DEFAULT_REQUEST_HEADERS ) req_kwargs = { 'params' : params , 'headers' : req_headers , } if data : req_kwargs [ 'data' ] = data if json : req_kwargs [ 'json' ] = json if token_refresh_attempts : if not await self . valid_token_set ( ) : await self . _auth_client . refresh_token ( ) token_refresh_attempts -= 1 req_headers . update ( { 'Authorization' : f'Bearer {self._auth_client.token}' } ) request_id = kwargs . get ( 'request_id' , uuid . uuid4 ( ) ) logging . debug ( _utils . REQ_LOG_FMT . format ( request_id = request_id , method = method . upper ( ) , url = url , kwargs = req_kwargs ) ) try : async with self . _session . request ( method , url , * * req_kwargs ) as resp : log_kw = { 'request_id' : request_id , 'method' : method . upper ( ) , 'url' : resp . url , 'status' : resp . status , 'reason' : resp . reason } logging . debug ( _utils . RESP_LOG_FMT . format ( * * log_kw ) ) if resp . status in REFRESH_STATUS_CODES : logging . warning ( f'[{request_id}] HTTP Status Code {resp.status}' f' returned requesting {resp.url}: {resp.reason}' ) if token_refresh_attempts : logging . info ( f'[{request_id}] Attempting request to {resp.url} ' 'again.' ) return await self . request ( method , url , token_refresh_attempts = token_refresh_attempts , request_id = request_id , * * req_kwargs ) logging . warning ( f'[{request_id}] Max attempts refreshing auth token ' f'exhausted while requesting {resp.url}' ) resp . raise_for_status ( ) return await resp . text ( ) except aiohttp . ClientResponseError as e : # bad HTTP status; avoid leaky abstractions and wrap HTTP errors # with our own msg = f'[{request_id}] HTTP error response from {resp.url}: {e}' logging . error ( msg , exc_info = e ) raise exceptions . GCPHTTPResponseError ( msg , resp . status ) except exceptions . GCPHTTPResponseError as e : # from recursive call raise e except Exception as e : msg = f'[{request_id}] Request call failed: {e}' logging . error ( msg , exc_info = e ) raise exceptions . GCPHTTPError ( msg )
Make an asynchronous HTTP request .
746
6
8,601
async def get_json ( self , url , json_callback = None , * * kwargs ) : if not json_callback : json_callback = json . loads response = await self . request ( method = 'get' , url = url , * * kwargs ) return json_callback ( response )
Get a URL and return its JSON response .
67
9
8,602
async def get_all ( self , url , params = None ) : if not params : params = { } items = [ ] next_page_token = None while True : if next_page_token : params [ 'pageToken' ] = next_page_token response = await self . get_json ( url , params = params ) items . append ( response ) next_page_token = response . get ( 'nextPageToken' ) if not next_page_token : break return items
Aggregate data from all pages of an API query .
106
11
8,603
def check_config ( ) : configfile = ConfigFile ( ) global data if data . keys ( ) > 0 : # FIXME: run a better check of this file print ( "gitberg config file exists" ) print ( "\twould you like to edit your gitberg config file?" ) else : print ( "No config found" ) print ( "\twould you like to create a gitberg config file?" ) answer = input ( "--> [Y/n]" ) # By default, the answer is yes, as denoted by the capital Y if not answer : answer = 'Y' # If yes, generate a new configuration # to be written out as yaml if answer in 'Yy' : print ( "Running gitberg config generator ..." ) # config.exists_or_make() config_gen = ConfigGenerator ( current = data ) config_gen . ask ( ) # print(config_gen.answers) data = config_gen . answers configfile . write ( ) print ( "Config written to {}" . format ( configfile . file_path ) )
Report if there is an existing config file
231
8
8,604
async def main ( ) : async with aiohttp . ClientSession ( ) as session : data = Luftdaten ( SENSOR_ID , loop , session ) await data . get_data ( ) if not await data . validate_sensor ( ) : print ( "Station is not available:" , data . sensor_id ) return if data . values and data . meta : # Print the sensor values print ( "Sensor values:" , data . values ) # Print the coordinates fo the sensor print ( "Location:" , data . meta [ 'latitude' ] , data . meta [ 'longitude' ] )
Sample code to retrieve the data .
131
7
8,605
async def list_instances ( self , project , page_size = 100 , instance_filter = None ) : url = ( f'{self.BASE_URL}{self.api_version}/projects/{project}' '/aggregated/instances' ) params = { 'maxResults' : page_size } if instance_filter : params [ 'filter' ] = instance_filter responses = await self . list_all ( url , params ) instances = self . _parse_rsps_for_instances ( responses ) return instances
Fetch all instances in a GCE project .
119
10
8,606
def infer_alpha_chain ( beta ) : if beta . gene . startswith ( "DRB" ) : return AlleleName ( species = "HLA" , gene = "DRA1" , allele_family = "01" , allele_code = "01" ) elif beta . gene . startswith ( "DPB" ) : # Most common alpha chain for DP is DPA*01:03 but we really # need to change this logic to use a lookup table of pairwise # frequencies for inferring the alpha-beta pairing return AlleleName ( species = "HLA" , gene = "DPA1" , allele_family = "01" , allele_code = "03" ) elif beta . gene . startswith ( "DQB" ) : # Most common DQ alpha (according to wikipedia) # DQA1*01:02 return AlleleName ( species = "HLA" , gene = "DQA1" , allele_family = "01" , allele_code = "02" ) return None
Given a parsed beta chain of a class II MHC infer the most frequent corresponding alpha chain .
233
19
8,607
def create_ticket ( subject , tags , ticket_body , requester_email = None , custom_fields = [ ] ) : payload = { 'ticket' : { 'subject' : subject , 'comment' : { 'body' : ticket_body } , 'group_id' : settings . ZENDESK_GROUP_ID , 'tags' : tags , 'custom_fields' : custom_fields } } if requester_email : payload [ 'ticket' ] [ 'requester' ] = { 'name' : 'Sender: %s' % requester_email . split ( '@' ) [ 0 ] , 'email' : requester_email , } else : payload [ 'ticket' ] [ 'requester_id' ] = settings . ZENDESK_REQUESTER_ID requests . post ( get_ticket_endpoint ( ) , data = json . dumps ( payload ) , auth = zendesk_auth ( ) , headers = { 'content-type' : 'application/json' } ) . raise_for_status ( )
Create a new Zendesk ticket
234
8
8,608
def message ( message , title = '' ) : return backend_api . opendialog ( "message" , dict ( message = message , title = title ) )
Display a message
35
3
8,609
def ask_file ( message = 'Select file for open.' , default = '' , title = '' , save = False ) : return backend_api . opendialog ( "ask_file" , dict ( message = message , default = default , title = title , save = save ) )
A dialog to get a file name . The default argument specifies a file path .
62
16
8,610
def ask_folder ( message = 'Select folder.' , default = '' , title = '' ) : return backend_api . opendialog ( "ask_folder" , dict ( message = message , default = default , title = title ) )
A dialog to get a directory name . Returns the name of a directory or None if user chose to cancel . If the default argument specifies a directory name and that directory exists then the dialog box will start with that directory .
52
44
8,611
def ask_ok_cancel ( message = '' , default = 0 , title = '' ) : return backend_api . opendialog ( "ask_ok_cancel" , dict ( message = message , default = default , title = title ) )
Display a message with choices of OK and Cancel .
55
10
8,612
def ask_yes_no ( message = '' , default = 0 , title = '' ) : return backend_api . opendialog ( "ask_yes_no" , dict ( message = message , default = default , title = title ) )
Display a message with choices of Yes and No .
53
10
8,613
def register ( self , receiver_id , receiver ) : assert receiver_id not in self . receivers self . receivers [ receiver_id ] = receiver ( receiver_id )
Register a receiver .
36
4
8,614
def get ( self , sched_rule_id ) : path = '/' . join ( [ 'schedulerule' , sched_rule_id ] ) return self . rachio . get ( path )
Retrieve the information for a scheduleRule entity .
45
10
8,615
def parse ( self , message , schema ) : func = { 'audit-log' : self . _parse_audit_log_msg , 'event' : self . _parse_event_msg , } [ schema ] return func ( message )
Parse message according to schema .
54
7
8,616
def start ( self , zone_id , duration ) : path = 'zone/start' payload = { 'id' : zone_id , 'duration' : duration } return self . rachio . put ( path , payload )
Start a zone .
49
4
8,617
def startMultiple ( self , zones ) : path = 'zone/start_multiple' payload = { 'zones' : zones } return self . rachio . put ( path , payload )
Start multiple zones .
41
4
8,618
def get ( self , zone_id ) : path = '/' . join ( [ 'zone' , zone_id ] ) return self . rachio . get ( path )
Retrieve the information for a zone entity .
38
9
8,619
def start ( self ) : zones = [ { "id" : data [ 0 ] , "duration" : data [ 1 ] , "sortOrder" : count } for ( count , data ) in enumerate ( self . _zones , 1 ) ] self . _api . startMultiple ( zones )
Start the schedule .
64
4
8,620
def clean_translation ( self ) : translation = self . cleaned_data [ 'translation' ] if self . instance and self . instance . content_object : # do not allow string longer than translatable field obj = self . instance . content_object field = obj . _meta . get_field ( self . instance . field ) max_length = field . max_length if max_length and len ( translation ) > max_length : raise forms . ValidationError ( _ ( 'The entered translation is too long. You entered ' '%(entered)s chars, max length is %(maxlength)s' ) % { 'entered' : len ( translation ) , 'maxlength' : max_length , } ) else : raise forms . ValidationError ( _ ( 'Can not store translation. First create all translation' ' for this object' ) ) return translation
Do not allow translations longer than the max_lenght of the field to be translated .
186
19
8,621
def _get_merge_rules ( properties , path = None ) : if path is None : path = ( ) for key , value in properties . items ( ) : new_path = path + ( key , ) types = _get_types ( value ) # `omitWhenMerged` supersedes all other rules. # See http://standard.open-contracting.org/1.1-dev/en/schema/merging/#omit-when-merged if value . get ( 'omitWhenMerged' ) or value . get ( 'mergeStrategy' ) == 'ocdsOmit' : yield ( new_path , { 'omitWhenMerged' } ) # `wholeListMerge` supersedes any nested rules. # See http://standard.open-contracting.org/1.1-dev/en/schema/merging/#whole-list-merge elif 'array' in types and ( value . get ( 'wholeListMerge' ) or value . get ( 'mergeStrategy' ) == 'ocdsVersion' ) : yield ( new_path , { 'wholeListMerge' } ) elif 'object' in types and 'properties' in value : yield from _get_merge_rules ( value [ 'properties' ] , path = new_path ) elif 'array' in types and 'items' in value : item_types = _get_types ( value [ 'items' ] ) # See http://standard.open-contracting.org/1.1-dev/en/schema/merging/#objects if any ( item_type != 'object' for item_type in item_types ) : yield ( new_path , { 'wholeListMerge' } ) elif 'object' in item_types and 'properties' in value [ 'items' ] : # See http://standard.open-contracting.org/1.1-dev/en/schema/merging/#whole-list-merge if 'id' not in value [ 'items' ] [ 'properties' ] : yield ( new_path , { 'wholeListMerge' } ) else : yield from _get_merge_rules ( value [ 'items' ] [ 'properties' ] , path = new_path )
Yields merge rules as key - value pairs in which the first element is a JSON path as a tuple and the second element is a list of merge properties whose values are true .
509
37
8,622
def get_merge_rules ( schema = None ) : schema = schema or get_release_schema_url ( get_tags ( ) [ - 1 ] ) if isinstance ( schema , dict ) : deref_schema = jsonref . JsonRef . replace_refs ( schema ) else : deref_schema = _get_merge_rules_from_url_or_path ( schema ) return dict ( _get_merge_rules ( deref_schema [ 'properties' ] ) )
Returns merge rules as key - value pairs in which the key is a JSON path as a tuple and the value is a list of merge properties whose values are true .
114
33
8,623
def unflatten ( processed , merge_rules ) : unflattened = OrderedDict ( ) for key in processed : current_node = unflattened for end , part in enumerate ( key , 1 ) : # If this is a path to an item of an array. # See http://standard.open-contracting.org/1.1-dev/en/schema/merging/#identifier-merge if isinstance ( part , IdValue ) : # If the `id` of an object in the array matches, change into it. for node in current_node : if isinstance ( node , IdDict ) and node . identifier == part . identifier : current_node = node break # Otherwise, append a new object, and change into it. else : new_node = IdDict ( ) new_node . identifier = part . identifier # If the original object had an `id` value, set it. if part . original_value is not None : new_node [ 'id' ] = part . original_value current_node . append ( new_node ) current_node = new_node continue # Otherwise, this is a path to a property of an object. node = current_node . get ( part ) # If this is a path to a node we visited before, change into it. If it's an `id` field, it's already been # set to its original value. if node is not None : current_node = node continue # If this is a full path, copy the data. if len ( key ) == end : # Omit null'ed fields. if processed [ key ] is not None : current_node [ part ] = processed [ key ] continue # If the path is to a new array, start a new array, and change into it. if isinstance ( key [ end ] , IdValue ) : new_node = [ ] # If the path is to a new object, start a new object, and change into it. else : new_node = OrderedDict ( ) current_node [ part ] = new_node current_node = new_node return unflattened
Unflattens a processed object into a JSON object .
455
12
8,624
def merge ( releases , schema = None , merge_rules = None ) : if not merge_rules : merge_rules = get_merge_rules ( schema ) merged = OrderedDict ( { ( 'tag' , ) : [ 'compiled' ] } ) for release in sorted ( releases , key = lambda release : release [ 'date' ] ) : release = release . copy ( ) ocid = release [ 'ocid' ] date = release [ 'date' ] # Prior to OCDS 1.1.4, `tag` didn't set "omitWhenMerged": true. release . pop ( 'tag' , None ) # becomes ["compiled"] flat = flatten ( release , merge_rules ) processed = process_flattened ( flat ) # Add an `id` and `date`. merged [ ( 'id' , ) ] = '{}-{}' . format ( ocid , date ) merged [ ( 'date' , ) ] = date # In OCDS 1.0, `ocid` incorrectly sets "mergeStrategy": "ocdsOmit". merged [ ( 'ocid' , ) ] = ocid merged . update ( processed ) return unflatten ( merged , merge_rules )
Merges a list of releases into a compiledRelease .
270
11
8,625
def merge_versioned ( releases , schema = None , merge_rules = None ) : if not merge_rules : merge_rules = get_merge_rules ( schema ) merged = OrderedDict ( ) for release in sorted ( releases , key = lambda release : release [ 'date' ] ) : release = release . copy ( ) # Don't version the OCID. ocid = release . pop ( 'ocid' ) merged [ ( 'ocid' , ) ] = ocid releaseID = release [ 'id' ] date = release [ 'date' ] # Prior to OCDS 1.1.4, `tag` didn't set "omitWhenMerged": true. tag = release . pop ( 'tag' , None ) flat = flatten ( release , merge_rules ) processed = process_flattened ( flat ) for key , value in processed . items ( ) : # If value is unchanged, don't add to history. if key in merged and value == merged [ key ] [ - 1 ] [ 'value' ] : continue if key not in merged : merged [ key ] = [ ] merged [ key ] . append ( OrderedDict ( [ ( 'releaseID' , releaseID ) , ( 'releaseDate' , date ) , ( 'releaseTag' , tag ) , ( 'value' , value ) , ] ) ) return unflatten ( merged , merge_rules )
Merges a list of releases into a versionedRelease .
304
12
8,626
def chunks ( items , size ) : return [ items [ i : i + size ] for i in range ( 0 , len ( items ) , size ) ]
Split list into chunks of the given size . Original order is preserved .
33
14
8,627
def login ( self ) : _LOGGER . debug ( "Attempting to login to ZoneMinder" ) login_post = { 'view' : 'console' , 'action' : 'login' } if self . _username : login_post [ 'username' ] = self . _username if self . _password : login_post [ 'password' ] = self . _password req = requests . post ( urljoin ( self . _server_url , 'index.php' ) , data = login_post , verify = self . _verify_ssl ) self . _cookies = req . cookies # Login calls returns a 200 response on both failure and success. # The only way to tell if you logged in correctly is to issue an api # call. req = requests . get ( urljoin ( self . _server_url , 'api/host/getVersion.json' ) , cookies = self . _cookies , timeout = ZoneMinder . DEFAULT_TIMEOUT , verify = self . _verify_ssl ) if not req . ok : _LOGGER . error ( "Connection error logging into ZoneMinder" ) return False return True
Login to the ZoneMinder API .
246
8
8,628
def _zm_request ( self , method , api_url , data = None , timeout = DEFAULT_TIMEOUT ) -> dict : try : # Since the API uses sessions that expire, sometimes we need to # re-auth if the call fails. for _ in range ( ZoneMinder . LOGIN_RETRIES ) : req = requests . request ( method , urljoin ( self . _server_url , api_url ) , data = data , cookies = self . _cookies , timeout = timeout , verify = self . _verify_ssl ) if not req . ok : self . login ( ) else : break else : _LOGGER . error ( 'Unable to get API response from ZoneMinder' ) try : return req . json ( ) except ValueError : _LOGGER . exception ( 'JSON decode exception caught while' 'attempting to decode "%s"' , req . text ) return { } except requests . exceptions . ConnectionError : _LOGGER . exception ( 'Unable to connect to ZoneMinder' ) return { }
Perform a request to the ZoneMinder API .
225
11
8,629
def get_monitors ( self ) -> List [ Monitor ] : raw_monitors = self . _zm_request ( 'get' , ZoneMinder . MONITOR_URL ) if not raw_monitors : _LOGGER . warning ( "Could not fetch monitors from ZoneMinder" ) return [ ] monitors = [ ] for raw_result in raw_monitors [ 'monitors' ] : _LOGGER . debug ( "Initializing camera %s" , raw_result [ 'Monitor' ] [ 'Id' ] ) monitors . append ( Monitor ( self , raw_result ) ) return monitors
Get a list of Monitors from the ZoneMinder API .
131
13
8,630
def get_run_states ( self ) -> List [ RunState ] : raw_states = self . get_state ( 'api/states.json' ) if not raw_states : _LOGGER . warning ( "Could not fetch runstates from ZoneMinder" ) return [ ] run_states = [ ] for i in raw_states [ 'states' ] : raw_state = i [ 'State' ] _LOGGER . info ( "Initializing runstate %s" , raw_state [ 'Id' ] ) run_states . append ( RunState ( self , raw_state ) ) return run_states
Get a list of RunStates from the ZoneMinder API .
133
13
8,631
def get_active_state ( self ) -> Optional [ str ] : for state in self . get_run_states ( ) : if state . active : return state . name return None
Get the name of the active run state from the ZoneMinder API .
39
15
8,632
def set_active_state ( self , state_name ) : _LOGGER . info ( 'Setting ZoneMinder run state to state %s' , state_name ) return self . _zm_request ( 'GET' , 'api/states/change/{}.json' . format ( state_name ) , timeout = 120 )
Set the ZoneMinder run state to the given state name via ZM API .
73
17
8,633
def is_available ( self ) -> bool : status_response = self . get_state ( 'api/host/daemonCheck.json' ) if not status_response : return False return status_response . get ( 'result' ) == 1
Indicate if this ZoneMinder service is currently available .
53
12
8,634
def _build_server_url ( server_host , server_path ) -> str : server_url = urljoin ( server_host , server_path ) if server_url [ - 1 ] == '/' : return server_url return '{}/' . format ( server_url )
Build the server url making sure it ends in a trailing slash .
63
13
8,635
def get ( self , flex_sched_rule_id ) : path = '/' . join ( [ 'flexschedulerule' , flex_sched_rule_id ] ) return self . rachio . get ( path )
Retrieve the information for a flexscheduleRule entity .
52
12
8,636
def upload_all_books ( book_id_start , book_id_end , rdf_library = None ) : # TODO refactor appname into variable logger . info ( "starting a gitberg mass upload: {0} -> {1}" . format ( book_id_start , book_id_end ) ) for book_id in range ( int ( book_id_start ) , int ( book_id_end ) + 1 ) : cache = { } errors = 0 try : if int ( book_id ) in missing_pgid : print ( u'missing\t{}' . format ( book_id ) ) continue upload_book ( book_id , rdf_library = rdf_library , cache = cache ) except Exception as e : print ( u'error\t{}' . format ( book_id ) ) logger . error ( u"Error processing: {}\r{}" . format ( book_id , e ) ) errors += 1 if errors > 10 : print ( 'error limit reached!' ) break
Uses the fetch make push subcommands to mirror Project Gutenberg to a github3 api
227
18
8,637
def upload_list ( book_id_list , rdf_library = None ) : with open ( book_id_list , 'r' ) as f : cache = { } for book_id in f : book_id = book_id . strip ( ) try : if int ( book_id ) in missing_pgid : print ( u'missing\t{}' . format ( book_id ) ) continue upload_book ( book_id , rdf_library = rdf_library , cache = cache ) except Exception as e : print ( u'error\t{}' . format ( book_id ) ) logger . error ( u"Error processing: {}\r{}" . format ( book_id , e ) )
Uses the fetch make push subcommands to add a list of pg books
161
16
8,638
def translate ( self ) : translations = [ ] for lang in settings . LANGUAGES : # do not create an translations for default language. # we will use the original model for this if lang [ 0 ] == self . _get_default_language ( ) : continue # create translations for all fields of each language if self . translatable_slug is not None : if self . translatable_slug not in self . translatable_fields : self . translatable_fields = self . translatable_fields + ( self . translatable_slug , ) for field in self . translatable_fields : trans , created = Translation . objects . get_or_create ( object_id = self . id , content_type = ContentType . objects . get_for_model ( self ) , field = field , lang = lang [ 0 ] , ) translations . append ( trans ) return translations
Create all translations objects for this Translatable instance .
189
10
8,639
def translations_objects ( self , lang ) : return Translation . objects . filter ( object_id = self . id , content_type = ContentType . objects . get_for_model ( self ) , lang = lang )
Return the complete list of translation objects of a Translatable instance
47
12
8,640
def translations ( self , lang ) : key = self . _get_translations_cache_key ( lang ) trans_dict = cache . get ( key , { } ) if self . translatable_slug is not None : if self . translatable_slug not in self . translatable_fields : self . translatable_fields = self . translatable_fields + ( self . translatable_slug , ) if not trans_dict : for field in self . translatable_fields : # we use get_translation method to be sure that it will # fall back and get the default value if needed trans_dict [ field ] = self . get_translation ( lang , field ) cache . set ( key , trans_dict ) return trans_dict
Return the list of translation strings of a Translatable instance in a dictionary form
160
15
8,641
def get_translation_obj ( self , lang , field , create = False ) : trans = None try : trans = Translation . objects . get ( object_id = self . id , content_type = ContentType . objects . get_for_model ( self ) , lang = lang , field = field , ) except Translation . DoesNotExist : if create : trans = Translation . objects . create ( object_id = self . id , content_type = ContentType . objects . get_for_model ( self ) , lang = lang , field = field , ) return trans
Return the translation object of an specific field in a Translatable istance
122
15
8,642
def get_translation ( self , lang , field ) : # Read from cache key = self . _get_translation_cache_key ( lang , field ) trans = cache . get ( key , '' ) if not trans : trans_obj = self . get_translation_obj ( lang , field ) trans = getattr ( trans_obj , 'translation' , '' ) # if there's no translation text fall back to the model field if not trans : trans = getattr ( self , field , '' ) # update cache cache . set ( key , trans ) return trans
Return the translation string of an specific field in a Translatable istance
119
15
8,643
def set_translation ( self , lang , field , text ) : # Do not allow user to set a translations in the default language auto_slug_obj = None if lang == self . _get_default_language ( ) : raise CanNotTranslate ( _ ( 'You are not supposed to translate the default language. ' 'Use the model fields for translations in default language' ) ) # Get translation, if it does not exits create one trans_obj = self . get_translation_obj ( lang , field , create = True ) trans_obj . translation = text trans_obj . save ( ) # check if the field has an autoslugfield and create the translation if INSTALLED_AUTOSLUG : if self . translatable_slug : try : auto_slug_obj = self . _meta . get_field ( self . translatable_slug ) . populate_from except AttributeError : pass if auto_slug_obj : tobj = self . get_translation_obj ( lang , self . translatable_slug , create = True ) translation = self . get_translation ( lang , auto_slug_obj ) tobj . translation = slugify ( translation ) tobj . save ( ) # Update cache for this specif translations key = self . _get_translation_cache_key ( lang , field ) cache . set ( key , text ) # remove cache for translations dict cache . delete ( self . _get_translations_cache_key ( lang ) ) return trans_obj
Store a translation string in the specified field for a Translatable istance
325
15
8,644
def translations_link ( self ) : translation_type = ContentType . objects . get_for_model ( Translation ) link = urlresolvers . reverse ( 'admin:%s_%s_changelist' % ( translation_type . app_label , translation_type . model ) , ) object_type = ContentType . objects . get_for_model ( self ) link += '?content_type__id__exact=%s&object_id=%s' % ( object_type . id , self . id ) return '<a href="%s">translate</a>' % link
Print on admin change list the link to see all translations for this object
134
14
8,645
def comparison_callback ( sender , instance , * * kwargs ) : if validate_instance ( instance ) and settings . AUTOMATED_LOGGING [ 'to_database' ] : try : old = sender . objects . get ( pk = instance . pk ) except Exception : return None try : mdl = ContentType . objects . get_for_model ( instance ) cur , ins = old . __dict__ , instance . __dict__ old , new = { } , { } for k in cur . keys ( ) : # _ fields are not real model fields, only state or cache fields # getting filtered if re . match ( '(_)(.*?)' , k ) : continue changed = False if k in ins . keys ( ) : if cur [ k ] != ins [ k ] : changed = True new [ k ] = ModelObject ( ) new [ k ] . value = str ( ins [ k ] ) new [ k ] . save ( ) try : new [ k ] . type = ContentType . objects . get_for_model ( ins [ k ] ) except Exception : logger = logging . getLogger ( __name__ ) logger . debug ( 'Could not dermin the content type of the field' ) new [ k ] . field = Field . objects . get_or_create ( name = k , model = mdl ) [ 0 ] new [ k ] . save ( ) else : changed = True if changed : old [ k ] = ModelObject ( ) old [ k ] . value = str ( cur [ k ] ) old [ k ] . save ( ) try : old [ k ] . type = ContentType . objects . get_for_model ( cur [ k ] ) except Exception : logger = logging . getLogger ( __name__ ) logger . debug ( 'Could not dermin the content type of the field' ) old [ k ] . field = Field . objects . get_or_create ( name = k , model = mdl ) [ 0 ] old [ k ] . save ( ) if old or new : changelog = ModelChangelog ( ) changelog . save ( ) changelog . modification = ModelModification ( ) changelog . modification . save ( ) changelog . modification . previously . add ( * old . values ( ) ) changelog . modification . currently . add ( * new . values ( ) ) changelog . information = ModelObject ( ) changelog . information . save ( ) changelog . information . value = repr ( instance ) changelog . information . type = ContentType . objects . get_for_model ( instance ) changelog . information . save ( ) changelog . save ( ) instance . al_chl = changelog return instance except Exception as e : print ( e ) logger = logging . getLogger ( __name__ ) logger . warning ( 'automated_logging recorded an exception that should not have happended' )
Comparing old and new object to determin which fields changed how
631
12
8,646
def save_callback ( sender , instance , created , update_fields , * * kwargs ) : if validate_instance ( instance ) : status = 'add' if created is True else 'change' change = '' if status == 'change' and 'al_chl' in instance . __dict__ . keys ( ) : changelog = instance . al_chl . modification change = ' to following changed: {}' . format ( changelog ) processor ( status , sender , instance , update_fields , addition = change )
Save object & link logging entry
114
6
8,647
def requires_refcount ( cls , func ) : @ functools . wraps ( func ) def requires_active_handle ( * args , * * kwargs ) : if cls . refcount ( ) == 0 : raise NoHandleException ( ) # You probably want to encase your code in a 'with LibZFSHandle():' block... return func ( * args , * * kwargs ) return requires_active_handle
The requires_refcount decorator adds a check prior to call func to verify that there is an active handle . if there is no such handle a NoHandleException exception is thrown .
96
37
8,648
def auto ( cls , func ) : @ functools . wraps ( func ) def auto_claim_handle ( * args , * * kwargs ) : with cls ( ) : return func ( * args , * * kwargs ) return auto_claim_handle
The auto decorator wraps func in a context manager so that a handle is obtained .
59
17
8,649
def get_gpubsub_publisher ( config , metrics , changes_channel , * * kw ) : builder = gpubsub_publisher . GPubsubPublisherBuilder ( config , metrics , changes_channel , * * kw ) return builder . build_publisher ( )
Get a GPubsubPublisher client .
61
8
8,650
def get_reconciler ( config , metrics , rrset_channel , changes_channel , * * kw ) : builder = reconciler . GDNSReconcilerBuilder ( config , metrics , rrset_channel , changes_channel , * * kw ) return builder . build_reconciler ( )
Get a GDNSReconciler client .
71
10
8,651
def get_authority ( config , metrics , rrset_channel , * * kwargs ) : builder = authority . GCEAuthorityBuilder ( config , metrics , rrset_channel , * * kwargs ) return builder . build_authority ( )
Get a GCEAuthority client .
58
8
8,652
async def refresh_token ( self ) : url , headers , body = self . _setup_token_request ( ) request_id = uuid . uuid4 ( ) logging . debug ( _utils . REQ_LOG_FMT . format ( request_id = request_id , method = 'POST' , url = url , kwargs = None ) ) async with self . _session . post ( url , headers = headers , data = body ) as resp : log_kw = { 'request_id' : request_id , 'method' : 'POST' , 'url' : resp . url , 'status' : resp . status , 'reason' : resp . reason , } logging . debug ( _utils . RESP_LOG_FMT . format ( * * log_kw ) ) # avoid leaky abstractions and wrap http errors with our own try : resp . raise_for_status ( ) except aiohttp . ClientResponseError as e : msg = f'[{request_id}] Issue connecting to {resp.url}: {e}' logging . error ( msg , exc_info = e ) raise exceptions . GCPHTTPResponseError ( msg , resp . status ) response = await resp . json ( ) try : self . token = response [ 'access_token' ] except KeyError : msg = '[{request_id}] No access token in response.' logging . error ( msg ) raise exceptions . GCPAuthError ( msg ) self . expiry = _client . _parse_expiry ( response )
Refresh oauth access token attached to this HTTP session .
335
12
8,653
def get ( self , dev_id ) : path = '/' . join ( [ 'device' , dev_id ] ) return self . rachio . get ( path )
Retrieve the information for a device entity .
38
9
8,654
def getEvent ( self , dev_id , starttime , endtime ) : path = 'device/%s/event?startTime=%s&endTime=%s' % ( dev_id , starttime , endtime ) return self . rachio . get ( path )
Retrieve events for a device entity .
62
8
8,655
def getForecast ( self , dev_id , units ) : assert units in [ 'US' , 'METRIC' ] , 'units must be either US or METRIC' path = 'device/%s/forecast?units=%s' % ( dev_id , units ) return self . rachio . get ( path )
Retrieve current and predicted forecast .
73
7
8,656
def stopWater ( self , dev_id ) : path = 'device/stop_water' payload = { 'id' : dev_id } return self . rachio . put ( path , payload )
Stop all watering on device .
44
6
8,657
def rainDelay ( self , dev_id , duration ) : path = 'device/rain_delay' payload = { 'id' : dev_id , 'duration' : duration } return self . rachio . put ( path , payload )
Rain delay device .
53
4
8,658
def on ( self , dev_id ) : path = 'device/on' payload = { 'id' : dev_id } return self . rachio . put ( path , payload )
Turn ON all features of the device .
41
8
8,659
def off ( self , dev_id ) : path = 'device/off' payload = { 'id' : dev_id } return self . rachio . put ( path , payload )
Turn OFF all features of the device .
41
8
8,660
def create_wallet ( self , master_secret = b"" ) : master_secret = deserialize . bytes_str ( master_secret ) bip32node = control . create_wallet ( self . testnet , master_secret = master_secret ) return bip32node . hwif ( as_private = True )
Create a BIP0032 - style hierarchical wallet .
69
11
8,661
def create_key ( self , master_secret = b"" ) : master_secret = deserialize . bytes_str ( master_secret ) bip32node = control . create_wallet ( self . testnet , master_secret = master_secret ) return bip32node . wif ( )
Create new private key and return in wif format .
63
11
8,662
def confirms ( self , txid ) : txid = deserialize . txid ( txid ) return self . service . confirms ( txid )
Returns number of confirms or None if unpublished .
32
9
8,663
def get_time_period ( value ) : for time_period in TimePeriod : if time_period . period == value : return time_period raise ValueError ( '{} is not a valid TimePeriod' . format ( value ) )
Get the corresponding TimePeriod from the value .
53
10
8,664
def update_monitor ( self ) : result = self . _client . get_state ( self . _monitor_url ) self . _raw_result = result [ 'monitor' ]
Update the monitor and monitor status from the ZM server .
39
12
8,665
def function ( self , new_function ) : self . _client . change_state ( self . _monitor_url , { 'Monitor[Function]' : new_function . value } )
Set the MonitorState of this Monitor .
40
8
8,666
def is_recording ( self ) -> Optional [ bool ] : status_response = self . _client . get_state ( 'api/monitors/alarm/id:{}/command:status.json' . format ( self . _monitor_id ) ) if not status_response : _LOGGER . warning ( 'Could not get status for monitor {}' . format ( self . _monitor_id ) ) return None status = status_response . get ( 'status' ) # ZoneMinder API returns an empty string to indicate that this monitor # cannot record right now if status == '' : return False return int ( status ) == STATE_ALARM
Indicate if this Monitor is currently recording .
139
9
8,667
def is_available ( self ) -> bool : status_response = self . _client . get_state ( 'api/monitors/daemonStatus/id:{}/daemon:zmc.json' . format ( self . _monitor_id ) ) if not status_response : _LOGGER . warning ( 'Could not get availability for monitor {}' . format ( self . _monitor_id ) ) return False # Monitor_Status was only added in ZM 1.32.3 monitor_status = self . _raw_result . get ( 'Monitor_Status' , None ) capture_fps = monitor_status and monitor_status [ 'CaptureFPS' ] return status_response . get ( 'status' , False ) and capture_fps != "0.00"
Indicate if this Monitor is currently available .
167
9
8,668
def get_events ( self , time_period , include_archived = False ) -> Optional [ int ] : date_filter = '1%20{}' . format ( time_period . period ) if time_period == TimePeriod . ALL : # The consoleEvents API uses DATE_SUB, so give it # something large date_filter = '100%20year' archived_filter = '/Archived=:0' if include_archived : archived_filter = '' event = self . _client . get_state ( 'api/events/consoleEvents/{}{}.json' . format ( date_filter , archived_filter ) ) try : events_by_monitor = event [ 'results' ] if isinstance ( events_by_monitor , list ) : return 0 return events_by_monitor . get ( str ( self . _monitor_id ) , 0 ) except ( TypeError , KeyError , AttributeError ) : return None
Get the number of events that have occurred on this Monitor .
206
12
8,669
def _build_image_url ( self , monitor , mode ) -> str : query = urlencode ( { 'mode' : mode , 'buffer' : monitor [ 'StreamReplayBuffer' ] , 'monitor' : monitor [ 'Id' ] , } ) url = '{zms_url}?{query}' . format ( zms_url = self . _client . get_zms_url ( ) , query = query ) _LOGGER . debug ( 'Monitor %s %s URL (without auth): %s' , monitor [ 'Id' ] , mode , url ) return self . _client . get_url_with_auth ( url )
Build and return a ZoneMinder camera image url .
145
11
8,670
def askopenfile ( mode = "r" , * * options ) : filename = askopenfilename ( * * options ) if filename : return open ( filename , mode ) return None
Ask for a filename to open and returned the opened file
38
11
8,671
def askopenfiles ( mode = "r" , * * options ) : files = askopenfilenames ( * * options ) if files : ofiles = [ ] for filename in files : ofiles . append ( open ( filename , mode ) ) files = ofiles return files
Ask for multiple filenames and return the open file objects
59
12
8,672
def asksaveasfile ( mode = "w" , * * options ) : filename = asksaveasfilename ( * * options ) if filename : return open ( filename , mode ) return None
Ask for a filename to save as and returned the opened file
40
12
8,673
def spaced_coordinate ( name , keys , ordered = True ) : def validate ( self ) : """Raise a ValueError if the instance's keys are incorrect""" if set ( keys ) != set ( self ) : raise ValueError ( '{} needs keys {} and got {}' . format ( type ( self ) . __name__ , keys , tuple ( self ) ) ) new_class = type ( name , ( Coordinate , ) , { 'default_order' : keys if ordered else None , '_validate' : validate } ) return new_class
Create a subclass of Coordinate instances of which must have exactly the given keys .
120
16
8,674
def norm ( self , order = 2 ) : return ( sum ( val ** order for val in abs ( self ) . values ( ) ) ) ** ( 1 / order )
Find the vector norm with the given order of the values
36
11
8,675
def jsonify ( o , max_depth = - 1 , parse_enums = PARSE_KEEP ) : if max_depth == 0 : return o max_depth -= 1 if isinstance ( o , dict ) : keyattrs = getattr ( o . __class__ , '_altnames' , { } ) def _getter ( key , value ) : key = keyattrs . get ( key , key ) other = getattr ( o , key , value ) if callable ( other ) : other = value if isinstance ( key , Enum ) : # Make sure we use a name as the key... if we don't it might mess some things up. key = key . name return key , jsonify ( other , max_depth = max_depth , parse_enums = parse_enums ) return dict ( _getter ( key , value ) for key , value in six . iteritems ( o ) ) elif isinstance ( o , list ) : return [ jsonify ( x , max_depth = max_depth , parse_enums = parse_enums ) for x in o ] elif isinstance ( o , tuple ) : return ( jsonify ( x , max_depth = max_depth , parse_enums = parse_enums ) for x in o ) elif isinstance ( o , Enum ) : o = _parse_enum ( o , parse_enums = parse_enums ) return o
Walks through object o and attempts to get the property instead of the key if available . This means that for our VDev objects we can easily get a dict of all the parsed values .
312
38
8,676
def copy_files ( self ) : files = [ u'LICENSE' , u'CONTRIBUTING.rst' ] this_dir = dirname ( abspath ( __file__ ) ) for _file in files : sh . cp ( '{0}/templates/{1}' . format ( this_dir , _file ) , '{0}/' . format ( self . book . local_path ) ) # copy metadata rdf file if self . book . meta . rdf_path : # if None, meta is from yaml file sh . cp ( self . book . meta . rdf_path , '{0}/' . format ( self . book . local_path ) ) if 'GITenberg' not in self . book . meta . subjects : if not self . book . meta . subjects : self . book . meta . metadata [ 'subjects' ] = [ ] self . book . meta . metadata [ 'subjects' ] . append ( 'GITenberg' ) self . save_meta ( )
Copy the LICENSE and CONTRIBUTING files to each folder repo Generate covers if needed . Dump the metadata .
228
25
8,677
def _collate_data ( collation , first_axis , second_axis ) : if first_axis not in collation : collation [ first_axis ] = { } collation [ first_axis ] [ "create" ] = 0 collation [ first_axis ] [ "modify" ] = 0 collation [ first_axis ] [ "delete" ] = 0 first = collation [ first_axis ] first [ second_axis ] = first [ second_axis ] + 1 collation [ first_axis ] = first
Collects information about the number of edit actions belonging to keys in a supplied dictionary of object or changeset ids .
114
24
8,678
def extract_changesets ( objects ) : def add_changeset_info ( collation , axis , item ) : """ """ if axis not in collation : collation [ axis ] = { } first = collation [ axis ] first [ "id" ] = axis first [ "username" ] = item [ "username" ] first [ "uid" ] = item [ "uid" ] first [ "timestamp" ] = item [ "timestamp" ] collation [ axis ] = first changeset_collation = { } for node in objects . nodes . values ( ) : _collate_data ( changeset_collation , node [ 'changeset' ] , node [ 'action' ] ) add_changeset_info ( changeset_collation , node [ 'changeset' ] , node ) for way in objects . ways . values ( ) : _collate_data ( changeset_collation , way [ 'changeset' ] , way [ 'action' ] ) add_changeset_info ( changeset_collation , way [ 'changeset' ] , way ) for relation in objects . relations . values ( ) : _collate_data ( changeset_collation , relation [ 'changeset' ] , relation [ 'action' ] ) add_changeset_info ( changeset_collation , relation [ 'changeset' ] , relation ) return changeset_collation
Provides information about each changeset present in an OpenStreetMap diff file .
302
16
8,679
def to_str ( obj ) : if isinstance ( obj , str ) : return obj if isinstance ( obj , unicode ) : return obj . encode ( 'utf-8' ) return str ( obj )
convert a object to string
45
6
8,680
def get_managed_zone ( self , zone ) : if zone . endswith ( '.in-addr.arpa.' ) : return self . reverse_prefix + '-' . join ( zone . split ( '.' ) [ - 5 : - 3 ] ) return self . forward_prefix + '-' . join ( zone . split ( '.' ) [ : - 1 ] )
Get the GDNS managed zone name for a DNS zone .
81
12
8,681
async def get_records_for_zone ( self , dns_zone , params = None ) : managed_zone = self . get_managed_zone ( dns_zone ) url = f'{self._base_url}/managedZones/{managed_zone}/rrsets' if not params : params = { } if 'fields' not in params : # Get only the fields we care about params [ 'fields' ] = ( 'rrsets/name,rrsets/kind,rrsets/rrdatas,' 'rrsets/type,rrsets/ttl,nextPageToken' ) next_page_token = None records = [ ] while True : if next_page_token : params [ 'pageToken' ] = next_page_token response = await self . get_json ( url , params = params ) records . extend ( response [ 'rrsets' ] ) next_page_token = response . get ( 'nextPageToken' ) if not next_page_token : break logging . info ( f'Found {len(records)} rrsets for zone "{dns_zone}".' ) return records
Get all resource record sets for a managed zone using the DNS zone .
256
14
8,682
async def is_change_done ( self , zone , change_id ) : zone_id = self . get_managed_zone ( zone ) url = f'{self._base_url}/managedZones/{zone_id}/changes/{change_id}' resp = await self . get_json ( url ) return resp [ 'status' ] == self . DNS_CHANGES_DONE
Check if a DNS change has completed .
91
8
8,683
async def publish_changes ( self , zone , changes ) : zone_id = self . get_managed_zone ( zone ) url = f'{self._base_url}/managedZones/{zone_id}/changes' resp = await self . request ( 'post' , url , json = changes ) return json . loads ( resp ) [ 'id' ]
Post changes to a zone .
81
6
8,684
def leave ( self , reason = None , message = None ) : # see https://github.com/crossbario/autobahn-python/issues/605 return self . _async_session . leave ( reason = reason , log_message = message )
Actively close this WAMP session .
56
8
8,685
def call ( self , procedure , * args , * * kwargs ) : return self . _async_session . call ( procedure , * args , * * kwargs )
Call a remote procedure .
39
5
8,686
def register ( self , endpoint , procedure = None , options = None ) : def proxy_endpoint ( * args , * * kwargs ) : return self . _callbacks_runner . put ( partial ( endpoint , * args , * * kwargs ) ) return self . _async_session . register ( proxy_endpoint , procedure = procedure , options = options )
Register a procedure for remote calling .
81
7
8,687
def publish ( self , topic , * args , * * kwargs ) : return self . _async_session . publish ( topic , * args , * * kwargs )
Publish an event to a topic .
39
8
8,688
def subscribe ( self , handler , topic = None , options = None ) : def proxy_handler ( * args , * * kwargs ) : return self . _callbacks_runner . put ( partial ( handler , * args , * * kwargs ) ) return self . _async_session . subscribe ( proxy_handler , topic = topic , options = options )
Subscribe to a topic for receiving events .
79
8
8,689
def b58encode ( val , charset = DEFAULT_CHARSET ) : def _b58encode_int ( int_ , default = bytes ( [ charset [ 0 ] ] ) ) : if not int_ and default : return default output = b'' while int_ : int_ , idx = divmod ( int_ , base ) output = charset [ idx : idx + 1 ] + output return output if not isinstance ( val , bytes ) : raise TypeError ( "a bytes-like object is required, not '%s', " "use .encode('ascii') to encode unicode strings" % type ( val ) . __name__ ) if isinstance ( charset , str ) : charset = charset . encode ( 'ascii' ) base = len ( charset ) if not base == 58 : raise ValueError ( 'charset base must be 58, not %s' % base ) pad_len = len ( val ) val = val . lstrip ( b'\0' ) pad_len -= len ( val ) p , acc = 1 , 0 for char in deque ( reversed ( val ) ) : acc += p * char p = p << 8 result = _b58encode_int ( acc , default = False ) prefix = bytes ( [ charset [ 0 ] ] ) * pad_len return prefix + result
Encode input to base58check encoding .
299
9
8,690
def b58decode ( val , charset = DEFAULT_CHARSET ) : def _b58decode_int ( val ) : output = 0 for char in val : output = output * base + charset . index ( char ) return output if isinstance ( val , str ) : val = val . encode ( ) if isinstance ( charset , str ) : charset = charset . encode ( ) base = len ( charset ) if not base == 58 : raise ValueError ( 'charset base must be 58, not %s' % base ) pad_len = len ( val ) val = val . lstrip ( bytes ( [ charset [ 0 ] ] ) ) pad_len -= len ( val ) acc = _b58decode_int ( val ) result = deque ( ) while acc > 0 : acc , mod = divmod ( acc , 256 ) result . appendleft ( mod ) prefix = b'\0' * pad_len return prefix + bytes ( result )
Decode base58check encoded input to original raw bytes .
215
12
8,691
def wait_for_edge ( self ) : GPIO . remove_event_detect ( self . _pin ) GPIO . wait_for_edge ( self . _pin , self . _edge )
This will remove remove any callbacks you might have specified
42
11
8,692
def request_finished_callback ( sender , * * kwargs ) : logger = logging . getLogger ( __name__ ) level = settings . AUTOMATED_LOGGING [ 'loglevel' ] [ 'request' ] user = get_current_user ( ) uri , application , method , status = get_current_environ ( ) excludes = settings . AUTOMATED_LOGGING [ 'exclude' ] [ 'request' ] if status and status in excludes : return if method and method . lower ( ) in excludes : return if not settings . AUTOMATED_LOGGING [ 'request' ] [ 'query' ] : uri = urllib . parse . urlparse ( uri ) . path logger . log ( level , ( '%s performed request at %s (%s %s)' % ( user , uri , method , status ) ) . replace ( " " , " " ) , extra = { 'action' : 'request' , 'data' : { 'user' : user , 'uri' : uri , 'method' : method , 'application' : application , 'status' : status } } )
This function logs if the user acceses the page
249
11
8,693
def request_exception ( sender , request , * * kwargs ) : if not isinstance ( request , WSGIRequest ) : logger = logging . getLogger ( __name__ ) level = CRITICAL if request . status_code <= 500 else WARNING logger . log ( level , '%s exception occured (%s)' , request . status_code , request . reason_phrase ) else : logger = logging . getLogger ( __name__ ) logger . log ( WARNING , 'WSGIResponse exception occured' )
Automated request exception logging .
115
6
8,694
def source_start ( base = '' , book_id = 'book' ) : repo_htm_path = "{book_id}-h/{book_id}-h.htm" . format ( book_id = book_id ) possible_paths = [ "book.asciidoc" , repo_htm_path , "{}-0.txt" . format ( book_id ) , "{}-8.txt" . format ( book_id ) , "{}.txt" . format ( book_id ) , "{}-pdf.pdf" . format ( book_id ) , ] # return the first match for path in possible_paths : fullpath = os . path . join ( base , path ) if os . path . exists ( fullpath ) : return path return None
chooses a starting source file in the base directory for id = book_id
173
16
8,695
def pretty_dump ( fn ) : @ wraps ( fn ) def pretty_dump_wrapper ( * args , * * kwargs ) : response . content_type = "application/json; charset=utf-8" return json . dumps ( fn ( * args , * * kwargs ) , # sort_keys=True, indent = 4 , separators = ( ',' , ': ' ) ) return pretty_dump_wrapper
Decorator used to output prettified JSON .
94
10
8,696
def decode_json_body ( ) : raw_data = request . body . read ( ) try : return json . loads ( raw_data ) except ValueError as e : raise HTTPError ( 400 , e . __str__ ( ) )
Decode bottle . request . body to JSON .
51
10
8,697
def handle_type_error ( fn ) : @ wraps ( fn ) def handle_type_error_wrapper ( * args , * * kwargs ) : def any_match ( string_list , obj ) : return filter ( lambda x : x in obj , string_list ) try : return fn ( * args , * * kwargs ) except TypeError as e : message = e . __str__ ( ) str_list = [ "takes exactly" , "got an unexpected" , "takes no argument" , ] if fn . __name__ in message and any_match ( str_list , message ) : raise HTTPError ( 400 , message ) raise # This will cause 500: Internal server error return handle_type_error_wrapper
Convert TypeError to bottle . HTTPError with 400 code and message about wrong parameters .
160
18
8,698
def json_to_params ( fn = None , return_json = True ) : def json_to_params_decorator ( fn ) : @ handle_type_error @ wraps ( fn ) def json_to_params_wrapper ( * args , * * kwargs ) : data = decode_json_body ( ) if type ( data ) in [ tuple , list ] : args = list ( args ) + data elif type ( data ) == dict : # transport only items that are not already in kwargs allowed_keys = set ( data . keys ( ) ) - set ( kwargs . keys ( ) ) for key in allowed_keys : kwargs [ key ] = data [ key ] elif type ( data ) in PRIMITIVE_TYPES : args = list ( args ) args . append ( data ) if not return_json : return fn ( * args , * * kwargs ) return encode_json_body ( fn ( * args , * * kwargs ) ) return json_to_params_wrapper if fn : # python decorator with optional parameters bukkake return json_to_params_decorator ( fn ) return json_to_params_decorator
Convert JSON in the body of the request to the parameters for the wrapped function .
262
17
8,699
def json_to_data ( fn = None , return_json = True ) : def json_to_data_decorator ( fn ) : @ handle_type_error @ wraps ( fn ) def get_data_wrapper ( * args , * * kwargs ) : kwargs [ "data" ] = decode_json_body ( ) if not return_json : return fn ( * args , * * kwargs ) return encode_json_body ( fn ( * args , * * kwargs ) ) return get_data_wrapper if fn : # python decorator with optional parameters bukkake return json_to_data_decorator ( fn ) return json_to_data_decorator
Decode JSON from the request and add it as data parameter for wrapped function .
155
16