idx
int64
0
63k
question
stringlengths
53
5.28k
target
stringlengths
5
805
26,300
def configure_alias ( graph , ns , mappings ) : convention = AliasConvention ( graph ) convention . configure ( ns , mappings )
Register Alias endpoints for a resource object .
26,301
def configure_alias ( self , ns , definition ) : @ self . add_route ( ns . alias_path , Operation . Alias , ns ) @ qs ( definition . request_schema ) @ wraps ( definition . func ) def retrieve ( ** path_data ) : request_data = ( load_query_string_data ( definition . request_schema ) if definition . request_schema else ...
Register an alias endpoint which will redirect to a resource s retrieve endpoint .
26,302
def encode_id_header ( resource ) : if not hasattr ( resource , "id" ) : return { } return { "X-{}-Id" . format ( camelize ( name_for ( resource ) ) ) : str ( resource . id ) , }
Generate a header for a newly created resource .
26,303
def load_request_data ( request_schema , partial = False ) : try : json_data = request . get_json ( force = True ) or { } except Exception : json_data = { } request_data = request_schema . load ( json_data , partial = partial ) if request_data . errors : raise with_context ( UnprocessableEntity ( "Validation error" ) ,...
Load request data as JSON using the given schema .
26,304
def load_query_string_data ( request_schema , query_string_data = None ) : if query_string_data is None : query_string_data = request . args request_data = request_schema . load ( query_string_data ) if request_data . errors : raise with_context ( UnprocessableEntity ( "Validation error" ) , dict ( errors = request_dat...
Load query string data using the given schema .
26,305
def dump_response_data ( response_schema , response_data , status_code = 200 , headers = None , response_format = None ) : if response_schema : response_data = response_schema . dump ( response_data ) . data return make_response ( response_data , response_schema , response_format , status_code , headers )
Dumps response data as JSON using the given schema .
26,306
def merge_data ( path_data , request_data ) : merged = request_data . copy ( ) if request_data else { } merged . update ( path_data or { } ) return merged
Merge data from the URI path and the request .
26,307
def find_response_format ( allowed_response_formats ) : if not allowed_response_formats : allowed_response_formats = [ ResponseFormats . JSON ] content_type = request . headers . get ( "Accept" ) if content_type is None : if allowed_response_formats : return allowed_response_formats [ 0 ] return ResponseFormats . JSON ...
Basic content negotiation logic .
26,308
def build_swagger ( graph , ns , operations ) : base_path = graph . build_route_path ( ns . path , ns . prefix ) schema = swagger . Swagger ( swagger = "2.0" , info = swagger . Info ( title = graph . metadata . name , version = ns . version , ) , consumes = swagger . MediaTypeList ( [ swagger . MimeType ( "application/...
Build out the top - level swagger definition .
26,309
def add_paths ( paths , base_path , operations ) : for operation , ns , rule , func in operations : path = build_path ( operation , ns ) if not path . startswith ( base_path ) : continue method = operation . value . method . lower ( ) suffix_start = 0 if len ( base_path ) == 1 else len ( base_path ) paths . setdefault ...
Add paths to swagger .
26,310
def add_definitions ( definitions , operations ) : for definition_schema in iter_definitions ( definitions , operations ) : if definition_schema is None : continue if isinstance ( definition_schema , str ) : continue for name , schema in iter_schemas ( definition_schema ) : definitions . setdefault ( name , swagger . S...
Add definitions to swagger .
26,311
def iter_definitions ( definitions , operations ) : for error_schema_class in [ ErrorSchema , ErrorContextSchema , SubErrorSchema ] : yield error_schema_class ( ) for operation , obj , rule , func in operations : yield get_request_schema ( func ) yield get_response_schema ( func )
Generate definitions to be converted to swagger schema .
26,312
def build_path ( operation , ns ) : try : return ns . url_for ( operation , _external = False ) except BuildError as error : uri_templates = { argument : "{{{}}}" . format ( argument ) for argument in error . suggested . arguments } return unquote ( ns . url_for ( operation , _external = False , ** uri_templates ) )
Build a path URI for an operation .
26,313
def header_param ( name , required = False , param_type = "string" ) : return swagger . HeaderParameterSubSchema ( ** { "name" : name , "in" : "header" , "required" : required , "type" : param_type , } )
Build a header parameter definition .
26,314
def query_param ( name , field , required = False ) : parameter = build_parameter ( field ) parameter [ "name" ] = name parameter [ "in" ] = "query" parameter [ "required" ] = False return swagger . QueryParameterSubSchema ( ** parameter )
Build a query parameter definition .
26,315
def path_param ( name , ns ) : if ns . identifier_type == "uuid" : param_type = "string" param_format = "uuid" else : param_type = "string" param_format = None kwargs = { "name" : name , "in" : "path" , "required" : True , "type" : param_type , } if param_format : kwargs [ "format" ] = param_format return swagger . Pat...
Build a path parameter definition .
26,316
def build_operation ( operation , ns , rule , func ) : swagger_operation = swagger . Operation ( operationId = operation_name ( operation , ns ) , parameters = swagger . ParametersList ( [ ] ) , responses = swagger . Responses ( ) , tags = [ ns . subject_name ] , ) swagger_operation . parameters . append ( header_param...
Build an operation definition .
26,317
def add_responses ( swagger_operation , operation , ns , func ) : swagger_operation . responses [ "default" ] = build_response ( description = "An error occurred" , resource = type_name ( name_for ( ErrorSchema ( ) ) ) , ) if getattr ( func , "__doc__" , None ) : description = func . __doc__ . strip ( ) . splitlines ( ...
Add responses to an operation .
26,318
def build_response ( description , resource = None ) : response = swagger . Response ( description = description , ) if resource is not None : response . schema = swagger . JsonReference ( { "$ref" : "#/definitions/{}" . format ( type_name ( name_for ( resource ) ) ) , } ) return response
Build a response definition .
26,319
def iter_endpoints ( graph , match_func ) : for rule in graph . flask . url_map . iter_rules ( ) : try : operation , ns = Namespace . parse_endpoint ( rule . endpoint , get_converter ( rule ) ) except ( IndexError , ValueError , InternalServerError ) : continue else : if match_func ( operation , ns , rule ) : func = gr...
Iterate through matching endpoints .
26,320
def get_converter ( rule ) : for converter , _ , _ in parse_rule ( str ( rule ) ) : if converter is not None : return converter return None
Parse rule will extract the converter from the rule as a generator
26,321
def request ( schema ) : def wrapper ( func ) : setattr ( func , REQUEST , schema ) return func return wrapper
Decorate a function with a request schema .
26,322
def response ( schema ) : def wrapper ( func ) : setattr ( func , RESPONSE , schema ) return func return wrapper
Decorate a function with a response schema .
26,323
def qs ( schema ) : def wrapper ( func ) : setattr ( func , QS , schema ) return func return wrapper
Decorate a function with a query string schema .
26,324
def should_skip_logging ( func ) : disabled = strtobool ( request . headers . get ( "x-request-nolog" , "false" ) ) return disabled or getattr ( func , SKIP_LOGGING , False )
Should we skip logging for this handler?
26,325
def logging_levels ( ) : enabled = strtobool ( request . headers . get ( "x-request-debug" , "false" ) ) level = None try : if enabled : level = getLogger ( ) . getEffectiveLevel ( ) getLogger ( ) . setLevel ( DEBUG ) yield finally : if enabled : getLogger ( ) . setLevel ( level )
Context manager to conditionally set logging levels .
26,326
def audit ( func ) : @ wraps ( func ) def wrapper ( * args , ** kwargs ) : options = AuditOptions ( include_request_body = DEFAULT_INCLUDE_REQUEST_BODY , include_response_body = DEFAULT_INCLUDE_RESPONSE_BODY , include_path = True , include_query_string = True , ) with logging_levels ( ) : return _audit_request ( option...
Record a Flask route function in the audit log .
26,327
def _audit_request ( options , func , request_context , * args , ** kwargs ) : logger = getLogger ( "audit" ) request_info = RequestInfo ( options , func , request_context ) response = None request_info . capture_request ( ) try : with elapsed_time ( request_info . timing ) : response = func ( * args , ** kwargs ) exce...
Run a request function under audit .
26,328
def parse_response ( response ) : if isinstance ( response , tuple ) : if len ( response ) > 2 : return response [ 0 ] , response [ 1 ] , response [ 2 ] elif len ( response ) > 1 : return response [ 0 ] , response [ 1 ] , { } try : return response . data , response . status_code , response . headers except AttributeErr...
Parse a Flask response into a body a status code and headers
26,329
def configure_audit_decorator ( graph ) : include_request_body = int ( graph . config . audit . include_request_body ) include_response_body = int ( graph . config . audit . include_response_body ) include_path = strtobool ( graph . config . audit . include_path ) include_query_string = strtobool ( graph . config . aud...
Configure the audit decorator .
26,330
def configure_route_decorator ( graph ) : enable_audit = graph . config . route . enable_audit enable_basic_auth = graph . config . route . enable_basic_auth enable_context_logger = graph . config . route . enable_context_logger enable_cors = graph . config . route . enable_cors graph . use ( * graph . config . route ....
Configure a flask route decorator that operates on Operation and Namespace objects .
26,331
def extract_status_code ( error ) : try : return int ( error . code ) except ( AttributeError , TypeError , ValueError ) : try : return int ( error . status_code ) except ( AttributeError , TypeError , ValueError ) : try : return int ( error . errno ) except ( AttributeError , TypeError , ValueError ) : return 500
Extract an error code from a message .
26,332
def extract_error_message ( error ) : try : return error . description or error . __class__ . __name__ except AttributeError : try : return str ( error . message ) or error . __class__ . __name__ except AttributeError : return str ( error ) or error . __class__ . __name__
Extract a useful message from an error .
26,333
def make_json_error ( error ) : message = extract_error_message ( error ) status_code = extract_status_code ( error ) context = extract_context ( error ) retryable = extract_retryable ( error ) headers = extract_headers ( error ) error_logger . debug ( "Handling {} error: {}" . format ( status_code , message , ) ) resp...
Handle errors by logging and
26,334
def configure_error_handlers ( graph ) : for code in default_exceptions . keys ( ) : graph . flask . register_error_handler ( code , make_json_error ) graph . flask . register_error_handler ( Exception , make_json_error )
Register error handlers .
26,335
def to_json_type ( self ) : document_dict = self . _json_safe ( self . _document ) self . _remove_keys ( document_dict , self . _private_fields ) return document_dict
Return a dictionary for the document with values converted to JSON safe types .
26,336
def _json_safe ( cls , value ) : if type ( value ) == date : return str ( value ) elif type ( value ) == datetime : return value . strftime ( '%Y-%m-%d %H:%M:%S' ) elif isinstance ( value , ObjectId ) : return str ( value ) elif isinstance ( value , _BaseFrame ) : return value . to_json_type ( ) elif isinstance ( value...
Return a JSON safe value
26,337
def _path_to_keys ( cls , path ) : keys = _BaseFrame . _path_to_keys_cache . get ( path ) if keys is None : keys = _BaseFrame . _path_to_keys_cache [ path ] = path . split ( '.' ) return keys
Return a list of keys for a given path
26,338
def _path_to_value ( cls , path , parent_dict ) : keys = cls . _path_to_keys ( path ) child_dict = parent_dict for key in keys [ : - 1 ] : child_dict = child_dict . get ( key ) if child_dict is None : return return child_dict . get ( keys [ - 1 ] )
Return a value from a dictionary at the given path
26,339
def _remove_keys ( cls , parent_dict , paths ) : for path in paths : keys = cls . _path_to_keys ( path ) child_dict = parent_dict for key in keys [ : - 1 ] : child_dict = child_dict . get ( key ) if child_dict is None : break if child_dict is None : continue if keys [ - 1 ] in child_dict : child_dict . pop ( keys [ - 1...
Remove a list of keys from a dictionary .
26,340
def insert ( self ) : from mongoframes . queries import to_refs signal ( 'insert' ) . send ( self . __class__ , frames = [ self ] ) document = to_refs ( self . _document ) self . _id = self . get_collection ( ) . insert_one ( document ) . inserted_id signal ( 'inserted' ) . send ( self . __class__ , frames = [ self ] )
Insert this document
26,341
def update ( self , * fields ) : from mongoframes . queries import to_refs assert '_id' in self . _document , "Can't update documents without `_id`" signal ( 'update' ) . send ( self . __class__ , frames = [ self ] ) if len ( fields ) > 0 : document = { } for field in fields : document [ field ] = self . _path_to_value...
Update this document . Optionally a specific list of fields to update can be specified .
26,342
def upsert ( self , * fields ) : if not self . _id : return self . insert ( ) if self . count ( { '_id' : self . _id } ) == 0 : self . insert ( ) else : self . update ( * fields )
Update or Insert this document depending on whether it exists or not . The presense of an _id value in the document is used to determine if the document exists .
26,343
def delete ( self ) : assert '_id' in self . _document , "Can't delete documents without `_id`" signal ( 'delete' ) . send ( self . __class__ , frames = [ self ] ) self . get_collection ( ) . delete_one ( { '_id' : self . _id } ) signal ( 'deleted' ) . send ( self . __class__ , frames = [ self ] )
Delete this document
26,344
def insert_many ( cls , documents ) : from mongoframes . queries import to_refs frames = cls . _ensure_frames ( documents ) signal ( 'insert' ) . send ( cls , frames = frames ) documents = [ to_refs ( f . _document ) for f in frames ] ids = cls . get_collection ( ) . insert_many ( documents ) . inserted_ids for i , id ...
Insert a list of documents
26,345
def update_many ( cls , documents , * fields ) : from mongoframes . queries import to_refs frames = cls . _ensure_frames ( documents ) all_count = len ( documents ) assert len ( [ f for f in frames if '_id' in f . _document ] ) == all_count , "Can't update documents without `_id`s" signal ( 'update' ) . send ( cls , fr...
Update multiple documents . Optionally a specific list of fields to update can be specified .
26,346
def delete_many ( cls , documents ) : frames = cls . _ensure_frames ( documents ) all_count = len ( documents ) assert len ( [ f for f in frames if '_id' in f . _document ] ) == all_count , "Can't delete documents without `_id`s" signal ( 'delete' ) . send ( cls , frames = frames ) ids = [ f . _id for f in frames ] cls...
Delete multiple documents
26,347
def _ensure_frames ( cls , documents ) : frames = [ ] for document in documents : if not isinstance ( document , Frame ) : frames . append ( cls ( document ) ) else : frames . append ( document ) return frames
Ensure all items in a list are frames by converting those that aren t .
26,348
def reload ( self , ** kwargs ) : frame = self . one ( { '_id' : self . _id } , ** kwargs ) self . _document = frame . _document
Reload the document
26,349
def count ( cls , filter = None , ** kwargs ) : from mongoframes . queries import Condition , Group , to_refs if isinstance ( filter , ( Condition , Group ) ) : filter = filter . to_dict ( ) return cls . get_collection ( ) . count ( to_refs ( filter ) , ** kwargs )
Return a count of documents matching the filter
26,350
def ids ( cls , filter = None , ** kwargs ) : from mongoframes . queries import Condition , Group , to_refs if isinstance ( filter , ( Condition , Group ) ) : filter = filter . to_dict ( ) documents = cls . get_collection ( ) . find ( to_refs ( filter ) , projection = { '_id' : True } , ** kwargs ) return [ d [ '_id' ]...
Return a list of Ids for documents matching the filter
26,351
def one ( cls , filter = None , ** kwargs ) : from mongoframes . queries import Condition , Group , to_refs kwargs [ 'projection' ] , references , subs = cls . _flatten_projection ( kwargs . get ( 'projection' , cls . _default_projection ) ) if isinstance ( filter , ( Condition , Group ) ) : filter = filter . to_dict (...
Return the first document matching the filter
26,352
def many ( cls , filter = None , ** kwargs ) : from mongoframes . queries import Condition , Group , to_refs kwargs [ 'projection' ] , references , subs = cls . _flatten_projection ( kwargs . get ( 'projection' , cls . _default_projection ) ) if isinstance ( filter , ( Condition , Group ) ) : filter = filter . to_dict ...
Return a list of documents matching the filter
26,353
def _apply_sub_frames ( cls , documents , subs ) : for path , projection in subs . items ( ) : sub = None expect_map = False if '$sub' in projection : sub = projection . pop ( '$sub' ) elif '$sub.' in projection : sub = projection . pop ( '$sub.' ) expect_map = True else : continue raw_subs = [ ] for document in docume...
Convert embedded documents to sub - frames for one or more documents
26,354
def _dereference ( cls , documents , references ) : for path , projection in references . items ( ) : if '$ref' not in projection : continue ids = set ( ) for document in documents : value = cls . _path_to_value ( path , document ) if not value : continue if isinstance ( value , list ) : ids . update ( value ) elif isi...
Dereference one or more documents
26,355
def listen ( cls , event , func ) : signal ( event ) . connect ( func , sender = cls )
Add a callback for a signal against the class
26,356
def stop_listening ( cls , event , func ) : signal ( event ) . disconnect ( func , sender = cls )
Remove a callback for a signal against the class
26,357
def get_db ( cls ) : if cls . _db : return getattr ( cls . _client , cls . _db ) return cls . _client . get_default_database ( )
Return the database for the collection
26,358
def _default_service_formatter ( service_url , width , height , background , foreground , options ) : image_tmp = '{service_url}/{width}x{height}/{background}/{foreground}/' image_url = image_tmp . format ( service_url = service_url , width = width , height = height , background = background , foreground = foreground )...
Generate an image URL for a service
26,359
def _body ( self , paragraphs ) : body = [ ] for i in range ( paragraphs ) : paragraph = self . _paragraph ( random . randint ( 1 , 10 ) ) body . append ( paragraph ) return '\n' . join ( body )
Generate a body of text
26,360
def _paragraph ( self , sentences ) : paragraph = [ ] for i in range ( sentences ) : sentence = self . _sentence ( random . randint ( 5 , 16 ) ) paragraph . append ( sentence ) return ' ' . join ( paragraph )
Generate a paragraph
26,361
def _sentence ( self , words ) : db = self . database seed = random . randint ( 0 , db [ 'word_count' ] - 3 ) seed_word , next_word = db [ 'words' ] [ seed ] , db [ 'words' ] [ seed + 1 ] w1 , w2 = seed_word , next_word sentence = [ ] for i in range ( 0 , words - 1 ) : sentence . append ( w1 ) w1 , w2 = w2 , random . c...
Generate a sentence
26,362
def init_word_db ( cls , name , text ) : text = text . replace ( '\n' , ' ' ) . replace ( '\r' , ' ' ) words = [ w . strip ( ) for w in text . split ( ' ' ) if w . strip ( ) ] assert len ( words ) > 2 , 'Database text sources must contain 3 or more words.' freqs = { } for i in range ( len ( words ) - 2 ) : w1 = words [...
Initialize a database of words for the maker with the given name
26,363
def p ( i , sample_size , weights ) : weight_i = weights [ i ] weights_sum = sum ( weights ) other_weights = list ( weights ) del other_weights [ i ] probability_of_i = 0 for picks in range ( 0 , sample_size ) : permutations = list ( itertools . permutations ( other_weights , picks ) ) permutation_probabilities = [ ] f...
Given a weighted set and sample size return the probabilty that the weight i will be present in the sample .
26,364
def get_fake ( locale = None ) : if locale is None : locale = Faker . default_locale if not hasattr ( Maker , '_fake_' + locale ) : Faker . _fake = faker . Factory . create ( locale ) return Faker . _fake
Return a shared faker factory used to generate fake data
26,365
def _get_unique ( self , * args ) : value = '' attempts = 0 while True : attempts += 1 value = self . _maker ( * args ) if value not in self . _used_values : break assert attempts < self . _max_attempts , 'Too many attempts to generate a unique value' self . _used_values . add ( value ) return value
Generate a unique value using the assigned maker
26,366
def assemble ( cls ) : document = { } for field_name , maker in cls . _instructions . items ( ) : with maker . target ( document ) : document [ field_name ] = maker ( ) return document
Assemble a single document using the blueprint
26,367
def finish ( cls , document ) : target_document = { } document_copy = { } for field_name , value in document . items ( ) : maker = cls . _instructions [ field_name ] target_document = document . copy ( ) with maker . target ( target_document ) : document_copy [ field_name ] = maker ( value ) target_document [ field_nam...
Take a assembled document and convert all assembled values to finished values .
26,368
def reassemble ( cls , fields , document ) : for field_name in cls . _instructions : if field_name in fields : maker = cls . _instructions [ field_name ] with maker . target ( document ) : document [ field_name ] = maker ( )
Take a previously assembled document and reassemble the given set of fields for it in place .
26,369
def is_diff ( self ) : if not isinstance ( self . details , dict ) : return False for key in [ 'additions' , 'updates' , 'deletions' ] : if self . details . get ( key , None ) : return True return False
Return True if there are any differences logged
26,370
def diff_to_html ( cls , details ) : changes = [ ] if not details : return '' def _frame ( value ) : if isinstance ( value , dict ) and '_str' in value : return value [ '_str' ] elif isinstance ( value , list ) : return ', ' . join ( [ _frame ( v ) for v in value ] ) return str ( value ) fields = sorted ( details . get...
Return an entry s details in HTML format
26,371
def diff_safe ( cls , value ) : if isinstance ( value , Frame ) : return { '_str' : str ( value ) , '_id' : value . _id } elif isinstance ( value , ( list , tuple ) ) : return [ cls . diff_safe ( v ) for v in value ] return value
Return a value that can be safely stored as a diff
26,372
def comparable ( self ) : document_dict = self . compare_safe ( self . _document ) self . _remove_keys ( document_dict , self . _uncompared_fields ) clean_document_dict = { } for k , v in document_dict . items ( ) : if not v and not isinstance ( v , ( int , float ) ) : continue clean_document_dict [ k ] = v for ref_fie...
Return a dictionary that can be compared
26,373
def logged_delete ( self , user ) : self . delete ( ) entry = ChangeLogEntry ( { 'type' : 'DELETED' , 'documents' : [ self ] , 'user' : user } ) entry . insert ( ) return entry
Delete the document and log the event in the change log
26,374
def logged_insert ( self , user ) : self . insert ( ) entry = ChangeLogEntry ( { 'type' : 'ADDED' , 'documents' : [ self ] , 'user' : user } ) entry . insert ( ) return entry
Create and insert the document and log the event in the change log
26,375
def logged_update ( self , user , data , * fields ) : original = self . comparable _fields = fields if len ( fields ) == 0 : _fields = data . keys ( ) for field in _fields : if field in data : setattr ( self , field , data [ field ] ) self . update ( * fields ) entry = ChangeLogEntry ( { 'type' : 'UPDATED' , 'documents...
Update the document with the dictionary of data provided and log the event in the change log .
26,376
def compare_safe ( cls , value ) : if type ( value ) == date : return str ( value ) elif isinstance ( value , ( list , tuple ) ) : return [ cls . compare_safe ( v ) for v in value ] elif isinstance ( value , dict ) : return { k : cls . compare_safe ( v ) for k , v in value . items ( ) } return value
Return a value that can be safely compared
26,377
def ElemMatch ( q , * conditions ) : new_condition = { } for condition in conditions : deep_merge ( condition . to_dict ( ) , new_condition ) return Condition ( q . _path , new_condition , '$elemMatch' )
The ElemMatch operator matches documents that contain an array field with at least one element that matches all the specified query criteria .
26,378
def SortBy ( * qs ) : sort = [ ] for q in qs : if q . _path . endswith ( '.desc' ) : sort . append ( ( q . _path [ : - 5 ] , DESCENDING ) ) else : sort . append ( ( q . _path , ASCENDING ) ) return sort
Convert a list of Q objects into list of sort instructions
26,379
def deep_merge ( source , dest ) : for key , value in source . items ( ) : if key in dest : if isinstance ( value , dict ) and isinstance ( dest [ key ] , dict ) : deep_merge ( value , dest [ key ] ) continue elif isinstance ( value , list ) and isinstance ( dest [ key ] , list ) : for item in value : if item not in de...
Deep merges source dict into dest dict .
26,380
def to_refs ( value ) : from mongoframes . frames import Frame , SubFrame if isinstance ( value , Frame ) : return value . _id elif isinstance ( value , SubFrame ) : return to_refs ( value . _document ) elif isinstance ( value , ( list , tuple ) ) : return [ to_refs ( v ) for v in value ] elif isinstance ( value , dict...
Convert all Frame instances within the given value to Ids
26,381
def assemble ( self , blueprint , quota ) : blueprint . reset ( ) documents = [ ] for i in range ( 0 , int ( quota ) ) : documents . append ( blueprint . assemble ( ) ) return documents
Assemble a quota of documents
26,382
def finish ( self , blueprint , documents ) : blueprint . reset ( ) finished = [ ] for document in documents : finished . append ( blueprint . finish ( document ) ) return finished
Finish a list of pre - assembled documents
26,383
def populate ( self , blueprint , documents ) : documents = self . finish ( blueprint , documents ) frames = [ ] for document in documents : meta_document = { } for field_name in blueprint . _meta_fields : meta_document [ field_name ] = document [ field_name ] document . pop ( field_name ) frame = blueprint . get_frame...
Populate the database with documents
26,384
def reassemble ( self , blueprint , fields , documents ) : blueprint . reset ( ) for document in documents : blueprint . reassemble ( fields , document )
Reassemble the given set of fields for a list of pre - assembed documents .
26,385
def can_publish ( self ) : with self . published_context ( ) : published = self . one ( Q . _uid == self . _uid , projection = { 'revision' : True } ) if not published : return True with self . draft_context ( ) : draft = self . one ( Q . _uid == self . _uid , projection = { 'revision' : True } ) return draft . revisio...
Return True if there is a draft version of the document that s ready to be published .
26,386
def can_revert ( self ) : if self . can_publish : with self . published_context ( ) : return self . count ( Q . _uid == self . _uid ) > 0 return False
Return True if we can revert the draft version of the document to the currently published version .
26,387
def get_publisher_doc ( self ) : with self . draft_context ( ) : draft = self . one ( Q . _uid == self . _uid ) publisher_doc = draft . _document self . _remove_keys ( publisher_doc , self . _unpublished_fields ) return publisher_doc
Return a publish safe version of the frame s document
26,388
def publish ( self ) : publisher_doc = self . get_publisher_doc ( ) with self . published_context ( ) : published = self . one ( Q . _uid == self . _uid ) if not published : published = self . __class__ ( ) for field , value in publisher_doc . items ( ) : setattr ( published , field , value ) published . upsert ( ) now...
Publish the current document .
26,389
def new_revision ( self , * fields ) : if not self . _id : assert g . get ( 'draft' ) , 'Only draft documents can be assigned new revisions' else : with self . draft_context ( ) : assert self . count ( Q . _id == self . _id ) == 1 , 'Only draft documents can be assigned new revisions' if len ( fields ) > 0 : fields . a...
Save a new revision of the document
26,390
def delete ( self ) : with self . draft_context ( ) : draft = self . one ( Q . _uid == self . _uid ) if draft : super ( PublisherFrame , draft ) . delete ( ) with self . published_context ( ) : published = self . one ( Q . _uid == self . _uid ) if published : super ( PublisherFrame , published ) . delete ( )
Delete this document and any counterpart document
26,391
def revert ( self ) : with self . draft_context ( ) : draft = self . one ( Q . _uid == self . _uid ) with self . published_context ( ) : published = self . one ( Q . _uid == self . _uid ) for field , value in draft . _document . items ( ) : if field in self . _unpublished_fields : continue setattr ( draft , field , get...
Revert the document to currently published version
26,392
def get_collection ( cls ) : if g . get ( 'draft' ) : return getattr ( cls . get_db ( ) , '{collection}_draft' . format ( collection = cls . _collection ) ) return getattr ( cls . get_db ( ) , cls . _collection )
Return a reference to the database collection for the class
26,393
def draft_context ( cls ) : previous_state = g . get ( 'draft' ) try : g . draft = True yield finally : g . draft = previous_state
Set the context to draft
26,394
def published_context ( cls ) : previous_state = g . get ( 'draft' ) try : g . draft = False yield finally : g . draft = previous_state
Set the context to published
26,395
def initialize_registry ( args : argparse . Namespace , backend : StorageBackend , log : logging . Logger ) : try : backend . reset ( args . force ) except ExistingBackendError : return 1 log . info ( "Resetting the index ..." ) backend . index . reset ( ) try : backend . index . upload ( "reset" , { } ) except ValueEr...
Initialize the registry and the index .
26,396
def publish_model ( args : argparse . Namespace , backend : StorageBackend , log : logging . Logger ) : path = os . path . abspath ( args . model ) try : model = GenericModel ( source = path , dummy = True ) except ValueError as e : log . critical ( '"model" must be a path: %s' , e ) return 1 except Exception as e : lo...
Push the model to Google Cloud Storage and updates the index file .
26,397
def list_models ( args : argparse . Namespace ) : try : git_index = GitIndex ( remote = args . index_repo , username = args . username , password = args . password , cache = args . cache , log_level = args . log_level ) except ValueError : return 1 for model_type , models in git_index . models . items ( ) : print ( mod...
Output the list of known models in the registry .
26,398
def install_environment ( args : argparse . Namespace , backend : StorageBackend , log : logging . Logger ) : model = _load_generic_model ( args . input , backend , log ) if model is None : return 1 packages = [ "%s==%s" % ( pkg , ver ) for pkg , ver in model . environment [ "packages" ] ] cmdline = [ sys . executable ...
Install the packages mentioned in the model s metadata .
26,399
def dump_model ( args : argparse . Namespace , backend : StorageBackend , log : logging . Logger ) : model = _load_generic_model ( args . input , backend , log ) if model is None : return 1 print ( model )
Print the information about the model .