idx
int64
0
63k
question
stringlengths
53
5.28k
target
stringlengths
5
805
34,700
def save_output_in_cache ( name , filename , output ) : cache_filename = _get_cache_filename ( name , filename ) with _open_for_write ( cache_filename ) as f : f . write ( output )
Saves output in the cache location .
34,701
def md5 ( text ) : h = hashlib . md5 ( ) h . update ( _unicode ( text ) . encode ( "utf-8" ) ) return h . hexdigest ( )
Returns the md5 hash of a string .
34,702
def cleanup_nodes ( doc ) : for node in doc . documentElement . childNodes : if node . nodeType == Node . TEXT_NODE and node . nodeValue . isspace ( ) : doc . documentElement . removeChild ( node ) return doc
Remove text nodes containing only whitespace
34,703
def _collect_nodes ( limit , sender , method_name , cacheable , params = None ) : if not params : params = sender . _get_params ( ) nodes = [ ] page = 1 end_of_pages = False while not end_of_pages and ( not limit or ( limit and len ( nodes ) < limit ) ) : params [ "page" ] = str ( page ) tries = 1 while True : try : do...
Returns a sequence of dom . Node objects about as close to limit as possible
34,704
def _extract ( node , name , index = 0 ) : nodes = node . getElementsByTagName ( name ) if len ( nodes ) : if nodes [ index ] . firstChild : return _unescape_htmlentity ( nodes [ index ] . firstChild . data . strip ( ) ) else : return None
Extracts a value from the xml string
34,705
def _extract_all ( node , name , limit_count = None ) : seq = [ ] for i in range ( 0 , len ( node . getElementsByTagName ( name ) ) ) : if len ( seq ) == limit_count : break seq . append ( _extract ( node , name , i ) ) return seq
Extracts all the values from the xml string . returning a list .
34,706
def _delay_call ( self ) : now = time . time ( ) time_since_last = now - self . last_call_time if time_since_last < DELAY_TIME : time . sleep ( DELAY_TIME - time_since_last ) self . last_call_time = now
Makes sure that web service calls are at least 0 . 2 seconds apart .
34,707
def get_top_artists ( self , limit = None , cacheable = True ) : params = { } if limit : params [ "limit" ] = limit doc = _Request ( self , "chart.getTopArtists" , params ) . execute ( cacheable ) return _extract_top_artists ( doc , self )
Returns the most played artists as a sequence of TopItem objects .
34,708
def get_top_tracks ( self , limit = None , cacheable = True ) : params = { } if limit : params [ "limit" ] = limit doc = _Request ( self , "chart.getTopTracks" , params ) . execute ( cacheable ) seq = [ ] for node in doc . getElementsByTagName ( "track" ) : title = _extract ( node , "name" ) artist = _extract ( node , ...
Returns the most played tracks as a sequence of TopItem objects .
34,709
def get_top_tags ( self , limit = None , cacheable = True ) : doc = _Request ( self , "tag.getTopTags" ) . execute ( cacheable ) seq = [ ] for node in doc . getElementsByTagName ( "tag" ) : if limit and len ( seq ) >= limit : break tag = Tag ( _extract ( node , "name" ) , self ) weight = _number ( _extract ( node , "co...
Returns the most used tags as a sequence of TopItem objects .
34,710
def enable_proxy ( self , host , port ) : self . proxy = [ host , _number ( port ) ] self . proxy_enabled = True
Enable a default web proxy
34,711
def enable_caching ( self , file_path = None ) : if not file_path : file_path = tempfile . mktemp ( prefix = "pylast_tmp_" ) self . cache_backend = _ShelfCacheBackend ( file_path )
Enables caching request - wide for all cacheable calls .
34,712
def get_track_by_mbid ( self , mbid ) : params = { "mbid" : mbid } doc = _Request ( self , "track.getInfo" , params ) . execute ( True ) return Track ( _extract ( doc , "name" , 1 ) , _extract ( doc , "name" ) , self )
Looks up a track by its MusicBrainz ID
34,713
def get_artist_by_mbid ( self , mbid ) : params = { "mbid" : mbid } doc = _Request ( self , "artist.getInfo" , params ) . execute ( True ) return Artist ( _extract ( doc , "name" ) , self )
Looks up an artist by its MusicBrainz ID
34,714
def get_album_by_mbid ( self , mbid ) : params = { "mbid" : mbid } doc = _Request ( self , "album.getInfo" , params ) . execute ( True ) return Album ( _extract ( doc , "artist" ) , _extract ( doc , "name" ) , self )
Looks up an album by its MusicBrainz ID
34,715
def update_now_playing ( self , artist , title , album = None , album_artist = None , duration = None , track_number = None , mbid = None , context = None , ) : params = { "track" : title , "artist" : artist } if album : params [ "album" ] = album if album_artist : params [ "albumArtist" ] = album_artist if context : p...
Used to notify Last . fm that a user has started listening to a track .
34,716
def scrobble ( self , artist , title , timestamp , album = None , album_artist = None , track_number = None , duration = None , stream_id = None , context = None , mbid = None , ) : return self . scrobble_many ( ( { "artist" : artist , "title" : title , "timestamp" : timestamp , "album" : album , "album_artist" : album...
Used to add a track - play to a user s profile .
34,717
def _get_signature ( self ) : keys = list ( self . params . keys ( ) ) keys . sort ( ) string = "" for name in keys : string += name string += self . params [ name ] string += self . api_secret return md5 ( string )
Returns a 32 - character hexadecimal md5 hash of the signature string .
34,718
def _get_cache_key ( self ) : keys = list ( self . params . keys ( ) ) keys . sort ( ) cache_key = str ( ) for key in keys : if key != "api_sig" and key != "api_key" and key != "sk" : cache_key += key + self . params [ key ] return hashlib . sha1 ( cache_key . encode ( "utf-8" ) ) . hexdigest ( )
The cache key is a string of concatenated sorted names and values .
34,719
def _get_cached_response ( self ) : if not self . _is_cached ( ) : response = self . _download_response ( ) self . cache . set_xml ( self . _get_cache_key ( ) , response ) return self . cache . get_xml ( self . _get_cache_key ( ) )
Returns a file object of the cached response .
34,720
def _download_response ( self ) : if self . network . limit_rate : self . network . _delay_call ( ) data = [ ] for name in self . params . keys ( ) : data . append ( "=" . join ( ( name , url_quote_plus ( _string ( self . params [ name ] ) ) ) ) ) data = "&" . join ( data ) headers = { "Content-type" : "application/x-w...
Returns a response body string from the server .
34,721
def execute ( self , cacheable = False ) : if self . network . is_caching_enabled ( ) and cacheable : response = self . _get_cached_response ( ) else : response = self . _download_response ( ) return minidom . parseString ( _string ( response ) . replace ( "opensearch:" , "" ) )
Returns the XML DOM response of the POST Request from the server
34,722
def _check_response_for_errors ( self , response ) : try : doc = minidom . parseString ( _string ( response ) . replace ( "opensearch:" , "" ) ) except Exception as e : raise MalformedResponseError ( self . network , e ) e = doc . getElementsByTagName ( "lfm" ) [ 0 ] if e . getAttribute ( "status" ) != "ok" : e = doc ....
Checks the response for errors and raises one if any exists .
34,723
def _get_web_auth_token ( self ) : request = _Request ( self . network , "auth.getToken" ) request . sign_it ( ) doc = request . execute ( ) e = doc . getElementsByTagName ( "token" ) [ 0 ] return e . firstChild . data
Retrieves a token from the network for web authentication . The token then has to be authorized from getAuthURL before creating session .
34,724
def get_web_auth_session_key ( self , url , token = "" ) : session_key , _username = self . get_web_auth_session_key_username ( url , token ) return session_key
Retrieves the session key of a web authorization process by its URL .
34,725
def get_session_key ( self , username , password_hash ) : params = { "username" : username , "authToken" : md5 ( username + password_hash ) } request = _Request ( self . network , "auth.getMobileSession" , params ) request . sign_it ( ) doc = request . execute ( ) return _extract ( doc , "key" )
Retrieve a session key with a username and a md5 hash of the user s password .
34,726
def _get_things ( self , method , thing , thing_type , params = None , cacheable = True ) : limit = params . get ( "limit" , 1 ) seq = [ ] for node in _collect_nodes ( limit , self , self . ws_prefix + "." + method , cacheable , params ) : title = _extract ( node , "name" ) artist = _extract ( node , "name" , 1 ) playc...
Returns a list of the most played thing_types by this thing .
34,727
def get_weekly_chart_dates ( self ) : doc = self . _request ( self . ws_prefix + ".getWeeklyChartList" , True ) seq = [ ] for node in doc . getElementsByTagName ( "chart" ) : seq . append ( ( node . getAttribute ( "from" ) , node . getAttribute ( "to" ) ) ) return seq
Returns a list of From and To tuples for the available charts .
34,728
def get_weekly_charts ( self , chart_kind , from_date = None , to_date = None ) : method = ".getWeekly" + chart_kind . title ( ) + "Chart" chart_type = eval ( chart_kind . title ( ) ) params = self . _get_params ( ) if from_date and to_date : params [ "from" ] = from_date params [ "to" ] = to_date doc = self . _request...
Returns the weekly charts for the week starting from the from_date value to the to_date value . chart_kind should be one of album artist or track
34,729
def remove_tag ( self , tag ) : if isinstance ( tag , Tag ) : tag = tag . get_name ( ) params = self . _get_params ( ) params [ "tag" ] = tag self . _request ( self . ws_prefix + ".removeTag" , False , params )
Remove a user s tag from this object .
34,730
def get_tags ( self ) : params = self . _get_params ( ) doc = self . _request ( self . ws_prefix + ".getTags" , False , params ) tag_names = _extract_all ( doc , "name" ) tags = [ ] for tag in tag_names : tags . append ( Tag ( tag , self . network ) ) return tags
Returns a list of the tags set by the user to this object .
34,731
def get_top_tags ( self , limit = None ) : doc = self . _request ( self . ws_prefix + ".getTopTags" , True ) elements = doc . getElementsByTagName ( "tag" ) seq = [ ] for element in elements : tag_name = _extract ( element , "name" ) tagcount = _extract ( element , "count" ) seq . append ( TopItem ( Tag ( tag_name , se...
Returns a list of the most frequently used Tags on this object .
34,732
def get_title ( self , properly_capitalized = False ) : if properly_capitalized : self . title = _extract ( self . _request ( self . ws_prefix + ".getInfo" , True ) , "name" ) return self . title
Returns the artist or track title .
34,733
def get_playcount ( self ) : return _number ( _extract ( self . _request ( self . ws_prefix + ".getInfo" , cacheable = True ) , "playcount" ) )
Returns the number of plays on the network
34,734
def get_userplaycount ( self ) : if not self . username : return params = self . _get_params ( ) params [ "username" ] = self . username doc = self . _request ( self . ws_prefix + ".getInfo" , True , params ) return _number ( _extract ( doc , "userplaycount" ) )
Returns the number of plays by a given username
34,735
def get_listener_count ( self ) : return _number ( _extract ( self . _request ( self . ws_prefix + ".getInfo" , cacheable = True ) , "listeners" ) )
Returns the number of listeners on the network
34,736
def get_mbid ( self ) : doc = self . _request ( self . ws_prefix + ".getInfo" , cacheable = True ) try : lfm = doc . getElementsByTagName ( "lfm" ) [ 0 ] opus = next ( self . _get_children_by_tag_name ( lfm , self . ws_prefix ) ) mbid = next ( self . _get_children_by_tag_name ( opus , "mbid" ) ) return mbid . firstChil...
Returns the MusicBrainz ID of the album or track .
34,737
def get_tracks ( self ) : return _extract_tracks ( self . _request ( self . ws_prefix + ".getInfo" , cacheable = True ) , self . network )
Returns the list of Tracks on this album .
34,738
def get_name ( self , properly_capitalized = False ) : if properly_capitalized : self . name = _extract ( self . _request ( self . ws_prefix + ".getInfo" , True ) , "name" ) return self . name
Returns the name of the artist . If properly_capitalized was asserted then the name would be downloaded overwriting the given one .
34,739
def get_mbid ( self ) : doc = self . _request ( self . ws_prefix + ".getInfo" , True ) return _extract ( doc , "mbid" )
Returns the MusicBrainz ID of this artist .
34,740
def get_listener_count ( self ) : if hasattr ( self , "listener_count" ) : return self . listener_count else : self . listener_count = _number ( _extract ( self . _request ( self . ws_prefix + ".getInfo" , True ) , "listeners" ) ) return self . listener_count
Returns the number of listeners on the network .
34,741
def is_streamable ( self ) : return bool ( _number ( _extract ( self . _request ( self . ws_prefix + ".getInfo" , True ) , "streamable" ) ) )
Returns True if the artist is streamable .
34,742
def get_similar ( self , limit = None ) : params = self . _get_params ( ) if limit : params [ "limit" ] = limit doc = self . _request ( self . ws_prefix + ".getSimilar" , True , params ) names = _extract_all ( doc , "name" ) matches = _extract_all ( doc , "match" ) artists = [ ] for i in range ( 0 , len ( names ) ) : a...
Returns the similar artists on the network .
34,743
def get_top_albums ( self , limit = None , cacheable = True ) : params = self . _get_params ( ) if limit : params [ "limit" ] = limit return self . _get_things ( "getTopAlbums" , "album" , Album , params , cacheable )
Returns a list of the top albums .
34,744
def get_top_tracks ( self , limit = None , cacheable = True ) : params = self . _get_params ( ) if limit : params [ "limit" ] = limit return self . _get_things ( "getTopTracks" , "track" , Track , params , cacheable )
Returns a list of the most played Tracks by this artist .
34,745
def get_top_artists ( self , limit = None , cacheable = True ) : params = self . _get_params ( ) if limit : params [ "limit" ] = limit doc = self . _request ( "geo.getTopArtists" , cacheable , params ) return _extract_top_artists ( doc , self )
Returns a sequence of the most played artists .
34,746
def get_duration ( self ) : doc = self . _request ( self . ws_prefix + ".getInfo" , True ) return _number ( _extract ( doc , "duration" ) )
Returns the track duration .
34,747
def get_userloved ( self ) : if not self . username : return params = self . _get_params ( ) params [ "username" ] = self . username doc = self . _request ( self . ws_prefix + ".getInfo" , True , params ) loved = _number ( _extract ( doc , "userloved" ) ) return bool ( loved )
Whether the user loved this track
34,748
def is_streamable ( self ) : doc = self . _request ( self . ws_prefix + ".getInfo" , True ) return _extract ( doc , "streamable" ) == "1"
Returns True if the track is available at Last . fm .
34,749
def is_fulltrack_available ( self ) : doc = self . _request ( self . ws_prefix + ".getInfo" , True ) return ( doc . getElementsByTagName ( "streamable" ) [ 0 ] . getAttribute ( "fulltrack" ) == "1" )
Returns True if the full track is available for streaming .
34,750
def get_album ( self ) : doc = self . _request ( self . ws_prefix + ".getInfo" , True ) albums = doc . getElementsByTagName ( "album" ) if len ( albums ) == 0 : return node = doc . getElementsByTagName ( "album" ) [ 0 ] return Album ( _extract ( node , "artist" ) , _extract ( node , "title" ) , self . network )
Returns the album object of this track .
34,751
def get_similar ( self , limit = None ) : params = self . _get_params ( ) if limit : params [ "limit" ] = limit doc = self . _request ( self . ws_prefix + ".getSimilar" , True , params ) seq = [ ] for node in doc . getElementsByTagName ( self . ws_prefix ) : title = _extract ( node , "name" ) artist = _extract ( node ,...
Returns similar tracks for this track on the network based on listening data .
34,752
def get_artist_tracks ( self , artist , cacheable = False ) : warnings . warn ( "User.get_artist_tracks is deprecated and will be removed in a future " "version. User.get_track_scrobbles is a partial replacement. " "See https://github.com/pylast/pylast/issues/298" , DeprecationWarning , stacklevel = 2 , ) params = self...
Get a list of tracks by a given artist scrobbled by this user including scrobble time .
34,753
def get_friends ( self , limit = 50 , cacheable = False ) : seq = [ ] for node in _collect_nodes ( limit , self , self . ws_prefix + ".getFriends" , cacheable ) : seq . append ( User ( _extract ( node , "name" ) , self . network ) ) return seq
Returns a list of the user s friends .
34,754
def get_loved_tracks ( self , limit = 50 , cacheable = True ) : params = self . _get_params ( ) if limit : params [ "limit" ] = limit seq = [ ] for track in _collect_nodes ( limit , self , self . ws_prefix + ".getLovedTracks" , cacheable , params ) : try : artist = _extract ( track , "name" , 1 ) except IndexError : co...
Returns this user s loved track as a sequence of LovedTrack objects in reverse order of their timestamp all the way back to the first track .
34,755
def get_now_playing ( self ) : params = self . _get_params ( ) params [ "limit" ] = "1" doc = self . _request ( self . ws_prefix + ".getRecentTracks" , False , params ) tracks = doc . getElementsByTagName ( "track" ) if len ( tracks ) == 0 : return None e = tracks [ 0 ] if not e . hasAttribute ( "nowplaying" ) : return...
Returns the currently playing track or None if nothing is playing .
34,756
def get_recent_tracks ( self , limit = 10 , cacheable = True , time_from = None , time_to = None ) : params = self . _get_params ( ) if limit : params [ "limit" ] = limit if time_from : params [ "from" ] = time_from if time_to : params [ "to" ] = time_to seq = [ ] for track in _collect_nodes ( limit , self , self . ws_...
Returns this user s played track as a sequence of PlayedTrack objects in reverse order of playtime all the way back to the first track .
34,757
def get_country ( self ) : doc = self . _request ( self . ws_prefix + ".getInfo" , True ) country = _extract ( doc , "country" ) if country is None or country == "None" : return None else : return Country ( country , self . network )
Returns the name of the country of the user .
34,758
def is_subscriber ( self ) : doc = self . _request ( self . ws_prefix + ".getInfo" , True ) return _extract ( doc , "subscriber" ) == "1"
Returns whether the user is a subscriber or not . True or False .
34,759
def get_playcount ( self ) : doc = self . _request ( self . ws_prefix + ".getInfo" , True ) return _number ( _extract ( doc , "playcount" ) )
Returns the user s playcount so far .
34,760
def get_registered ( self ) : doc = self . _request ( self . ws_prefix + ".getInfo" , True ) return _extract ( doc , "registered" )
Returns the user s registration date .
34,761
def get_unixtime_registered ( self ) : doc = self . _request ( self . ws_prefix + ".getInfo" , True ) return int ( doc . getElementsByTagName ( "registered" ) [ 0 ] . getAttribute ( "unixtime" ) )
Returns the user s registration date as a UNIX timestamp .
34,762
def get_tagged_albums ( self , tag , limit = None , cacheable = True ) : params = self . _get_params ( ) params [ "tag" ] = tag params [ "taggingtype" ] = "album" if limit : params [ "limit" ] = limit doc = self . _request ( self . ws_prefix + ".getpersonaltags" , cacheable , params ) return _extract_albums ( doc , sel...
Returns the albums tagged by a user .
34,763
def get_tagged_artists ( self , tag , limit = None ) : params = self . _get_params ( ) params [ "tag" ] = tag params [ "taggingtype" ] = "artist" if limit : params [ "limit" ] = limit doc = self . _request ( self . ws_prefix + ".getpersonaltags" , True , params ) return _extract_artists ( doc , self . network )
Returns the artists tagged by a user .
34,764
def get_tagged_tracks ( self , tag , limit = None , cacheable = True ) : params = self . _get_params ( ) params [ "tag" ] = tag params [ "taggingtype" ] = "track" if limit : params [ "limit" ] = limit doc = self . _request ( self . ws_prefix + ".getpersonaltags" , cacheable , params ) return _extract_tracks ( doc , sel...
Returns the tracks tagged by a user .
34,765
def get_track_scrobbles ( self , artist , track , cacheable = False ) : params = self . _get_params ( ) params [ "artist" ] = artist params [ "track" ] = track seq = [ ] for track in _collect_nodes ( None , self , self . ws_prefix + ".getTrackScrobbles" , cacheable , params ) : title = _extract ( track , "name" ) artis...
Get a list of this user s scrobbles of this artist s track including scrobble time .
34,766
def get_total_result_count ( self ) : doc = self . _request ( self . _ws_prefix + ".search" , True ) return _extract ( doc , "totalResults" )
Returns the total count of all the results .
34,767
def _retrieve_page ( self , page_index ) : params = self . _get_params ( ) params [ "page" ] = str ( page_index ) doc = self . _request ( self . _ws_prefix + ".search" , True , params ) return doc . getElementsByTagName ( self . _ws_prefix + "matches" ) [ 0 ]
Returns the node of matches to be processed
34,768
def get_next_page ( self ) : master_node = self . _retrieve_next_page ( ) seq = [ ] for node in master_node . getElementsByTagName ( "album" ) : seq . append ( Album ( _extract ( node , "artist" ) , _extract ( node , "name" ) , self . network , info = { "image" : _extract_all ( node , "image" ) } , ) ) return seq
Returns the next page of results as a sequence of Album objects .
34,769
def get_next_page ( self ) : master_node = self . _retrieve_next_page ( ) seq = [ ] for node in master_node . getElementsByTagName ( "artist" ) : artist = Artist ( _extract ( node , "name" ) , self . network , info = { "image" : _extract_all ( node , "image" ) } , ) artist . listener_count = _number ( _extract ( node ,...
Returns the next page of results as a sequence of Artist objects .
34,770
def get_next_page ( self ) : master_node = self . _retrieve_next_page ( ) seq = [ ] for node in master_node . getElementsByTagName ( "track" ) : track = Track ( _extract ( node , "artist" ) , _extract ( node , "name" ) , self . network , info = { "image" : _extract_all ( node , "image" ) } , ) track . listener_count = ...
Returns the next page of results as a sequence of Track objects .
34,771
def write_file ( self , fp , data ) : with open ( fp , 'w' ) as f : f . write ( data )
Write output to a file .
34,772
def detect_function_style ( self , test_record ) : index = 0 for regex in FUNCTION_STYLE_REGEX : if re . search ( regex , test_record ) : return index index += 1 return None
Returns the index for the function declaration style detected in the given string or None if no function declarations are detected .
34,773
def change_function_style ( self , stripped_record , func_decl_style ) : if func_decl_style is None : return stripped_record if self . apply_function_style is None : return stripped_record regex = FUNCTION_STYLE_REGEX [ func_decl_style ] replacement = FUNCTION_STYLE_REPLACEMENT [ self . apply_function_style ] changed_r...
Converts a function definition syntax from the func_decl_style to the one that has been set in self . apply_function_style and returns the string with the converted syntax .
34,774
def beautify_file ( self , path ) : error = False if ( path == '-' ) : data = sys . stdin . read ( ) result , error = self . beautify_string ( data , '(stdin)' ) sys . stdout . write ( result ) else : data = self . read_file ( path ) result , error = self . beautify_string ( data , path ) if ( data != result ) : if ( s...
Beautify bash script file .
34,775
def main ( self ) : error = False parser = argparse . ArgumentParser ( description = "A Bash beautifier for the masses, version {}" . format ( self . get_version ( ) ) , add_help = False ) parser . add_argument ( '--indent-size' , '-i' , nargs = 1 , type = int , default = 4 , help = "Sets the number of spaces to be use...
Main beautifying function .
34,776
def init_default ( required , default , optional_default ) : if not required and default == NOTHING : default = optional_default return default
Returns optional default if field is not required and default was not provided .
34,777
def to_child_field ( cls ) : class ChildConverter ( object ) : def __init__ ( self , cls ) : self . _cls = cls @ property def cls ( self ) : return resolve_class ( self . _cls ) def __call__ ( self , value ) : try : if value == self . _cls and callable ( value ) : value = value ( ) return to_model ( self . cls , value ...
Returns an callable instance that will convert a value to a Child object .
34,778
def to_mapping_field ( cls , key ) : class MappingConverter ( object ) : def __init__ ( self , cls , key ) : self . _cls = cls self . key = key @ property def cls ( self ) : return resolve_class ( self . _cls ) def __call__ ( self , values ) : kwargs = OrderedDict ( ) if isinstance ( values , TypedMapping ) : return va...
Returns a callable instance that will convert a value to a Mapping .
34,779
def to_date_field ( formatter ) : class DateConverter ( object ) : def __init__ ( self , formatter ) : self . formatter = formatter def __call__ ( self , value ) : if isinstance ( value , string_types ) : value = datetime . strptime ( value , self . formatter ) . date ( ) if isinstance ( value , datetime ) : value = va...
Returns a callable instance that will convert a string to a Date .
34,780
def to_datetime_field ( formatter ) : class DateTimeConverter ( object ) : def __init__ ( self , formatter ) : self . formatter = formatter def __call__ ( self , value ) : if isinstance ( value , string_types ) : value = parser . parse ( value ) return value return DateTimeConverter ( formatter )
Returns a callable instance that will convert a string to a DateTime .
34,781
def to_time_field ( formatter ) : class TimeConverter ( object ) : def __init__ ( self , formatter ) : self . formatter = formatter def __call__ ( self , value ) : if isinstance ( value , string_types ) : value = datetime . strptime ( value , self . formatter ) . time ( ) return value return TimeConverter ( formatter )
Returns a callable instance that will convert a string to a Time .
34,782
def to_dict ( obj , ** kwargs ) : if is_model ( obj . __class__ ) : return related_obj_to_dict ( obj , ** kwargs ) else : return obj
Convert an object into dictionary . Uses singledispatch to allow for clean extensions for custom class types .
34,783
def related_obj_to_dict ( obj , ** kwargs ) : kwargs . pop ( 'formatter' , None ) suppress_private_attr = kwargs . get ( "suppress_private_attr" , False ) suppress_empty_values = kwargs . get ( "suppress_empty_values" , False ) attrs = fields ( obj . __class__ ) return_dict = kwargs . get ( "dict_factory" , OrderedDict...
Covert a known related object to a dictionary .
34,784
def convert_key_to_attr_names ( cls , original ) : attrs = fields ( cls ) updated = { } keys_pulled = set ( ) for a in attrs : key_name = a . metadata . get ( 'key' ) or a . name if key_name in original : updated [ a . name ] = original . get ( key_name ) keys_pulled . add ( key_name ) if getattr ( cls , '__related_str...
convert key names to their corresponding attribute names
34,785
def to_yaml ( obj , stream = None , dumper_cls = yaml . Dumper , default_flow_style = False , ** kwargs ) : class OrderedDumper ( dumper_cls ) : pass def dict_representer ( dumper , data ) : return dumper . represent_mapping ( yaml . resolver . BaseResolver . DEFAULT_MAPPING_TAG , data . items ( ) ) OrderedDumper . add...
Serialize a Python object into a YAML stream with OrderedDict and default_flow_style defaulted to False .
34,786
def from_yaml ( stream , cls = None , loader_cls = yaml . Loader , object_pairs_hook = OrderedDict , ** extras ) : class OrderedLoader ( loader_cls ) : pass def construct_mapping ( loader , node ) : loader . flatten_mapping ( node ) return object_pairs_hook ( loader . construct_pairs ( node ) ) OrderedLoader . add_cons...
Convert a YAML stream into a class via the OrderedLoader class .
34,787
def from_json ( stream , cls = None , object_pairs_hook = OrderedDict , ** extras ) : stream = stream . read ( ) if hasattr ( stream , 'read' ) else stream json_dict = json . loads ( stream , object_pairs_hook = object_pairs_hook ) if extras : json_dict . update ( extras ) return to_model ( cls , json_dict ) if cls els...
Convert a JSON string or stream into specified class .
34,788
def BooleanField ( default = NOTHING , required = True , repr = True , cmp = True , key = None ) : default = _init_fields . init_default ( required , default , None ) validator = _init_fields . init_validator ( required , bool ) return attrib ( default = default , validator = validator , repr = repr , cmp = cmp , metad...
Create new bool field on a model .
34,789
def ChildField ( cls , default = NOTHING , required = True , repr = True , cmp = True , key = None ) : default = _init_fields . init_default ( required , default , None ) converter = converters . to_child_field ( cls ) validator = _init_fields . init_validator ( required , object if isinstance ( cls , str ) else cls ) ...
Create new child field on a model .
34,790
def DateField ( formatter = types . DEFAULT_DATE_FORMAT , default = NOTHING , required = True , repr = True , cmp = True , key = None ) : default = _init_fields . init_default ( required , default , None ) validator = _init_fields . init_validator ( required , date ) converter = converters . to_date_field ( formatter )...
Create new date field on a model .
34,791
def DateTimeField ( formatter = types . DEFAULT_DATETIME_FORMAT , default = NOTHING , required = True , repr = True , cmp = True , key = None ) : default = _init_fields . init_default ( required , default , None ) validator = _init_fields . init_validator ( required , datetime ) converter = converters . to_datetime_fie...
Create new datetime field on a model .
34,792
def TimeField ( formatter = types . DEFAULT_TIME_FORMAT , default = NOTHING , required = True , repr = True , cmp = True , key = None ) : default = _init_fields . init_default ( required , default , None ) validator = _init_fields . init_validator ( required , time ) converter = converters . to_time_field ( formatter )...
Create new time field on a model .
34,793
def FloatField ( default = NOTHING , required = True , repr = True , cmp = True , key = None ) : default = _init_fields . init_default ( required , default , None ) validator = _init_fields . init_validator ( required , float ) return attrib ( default = default , converter = converters . float_if_not_none , validator =...
Create new float field on a model .
34,794
def IntegerField ( default = NOTHING , required = True , repr = True , cmp = True , key = None ) : default = _init_fields . init_default ( required , default , None ) validator = _init_fields . init_validator ( required , int ) return attrib ( default = default , converter = converters . int_if_not_none , validator = v...
Create new int field on a model .
34,795
def MappingField ( cls , child_key , default = NOTHING , required = True , repr = False , key = None ) : default = _init_fields . init_default ( required , default , OrderedDict ( ) ) converter = converters . to_mapping_field ( cls , child_key ) validator = _init_fields . init_validator ( required , types . TypedMappin...
Create new mapping field on a model .
34,796
def RegexField ( regex , default = NOTHING , required = True , repr = True , cmp = True , key = None ) : default = _init_fields . init_default ( required , default , None ) validator = _init_fields . init_validator ( required , string_types , validators . regex ( regex ) ) return attrib ( default = default , converter ...
Create new str field on a model .
34,797
def SequenceField ( cls , default = NOTHING , required = True , repr = False , key = None ) : default = _init_fields . init_default ( required , default , [ ] ) converter = converters . to_sequence_field ( cls ) validator = _init_fields . init_validator ( required , types . TypedSequence ) return attrib ( default = def...
Create new sequence field on a model .
34,798
def SetField ( cls , default = NOTHING , required = True , repr = False , key = None ) : default = _init_fields . init_default ( required , default , set ( ) ) converter = converters . to_set_field ( cls ) validator = _init_fields . init_validator ( required , types . TypedSet ) return attrib ( default = default , conv...
Create new set field on a model .
34,799
def DecimalField ( default = NOTHING , required = True , repr = True , cmp = True , key = None ) : default = _init_fields . init_default ( required , default , None ) validator = _init_fields . init_validator ( required , Decimal ) return attrib ( default = default , converter = lambda x : Decimal ( x ) , validator = v...
Create new decimal field on a model .