idx
int64
0
63k
question
stringlengths
53
5.28k
target
stringlengths
5
805
59,000
def editproject ( self , project_id , ** kwargs ) : data = { "id" : project_id } if kwargs : data . update ( kwargs ) request = requests . put ( '{0}/{1}' . format ( self . projects_url , project_id ) , headers = self . headers , data = data , verify = self . verify_ssl , auth = self . auth , timeout = self . timeout ) if request . status_code == 200 : return True elif request . status_code == 400 : if "Your param's are invalid" in request . text : print ( request . text ) return False else : return False
Edit an existing project .
59,001
def shareproject ( self , project_id , group_id , group_access ) : data = { 'id' : project_id , 'group_id' : group_id , 'group_access' : group_access } request = requests . post ( '{0}/{1}/share' . format ( self . projects_url , project_id ) , headers = self . headers , data = data , verify = self . verify_ssl ) return request . status_code == 201
Allow to share project with group .
59,002
def delete_project ( self , id ) : url = '/projects/{id}' . format ( id = id ) response = self . delete ( url ) if response is True : return { } else : return response
Delete a project from the Gitlab server
59,003
def createprojectuser ( self , user_id , name , ** kwargs ) : data = { 'name' : name } if kwargs : data . update ( kwargs ) request = requests . post ( '{0}/user/{1}' . format ( self . projects_url , user_id ) , headers = self . headers , data = data , verify = self . verify_ssl , auth = self . auth , timeout = self . timeout ) if request . status_code == 201 : return True else : return False
Creates a new project owned by the specified user . Available only for admins .
59,004
def deleteprojectmember ( self , project_id , user_id ) : request = requests . delete ( '{0}/{1}/members/{2}' . format ( self . projects_url , project_id , user_id ) , headers = self . headers , verify = self . verify_ssl , auth = self . auth , timeout = self . timeout ) if request . status_code == 200 : return True
Delete a project member
59,005
def addprojecthook ( self , project_id , url , push = False , issues = False , merge_requests = False , tag_push = False ) : data = { 'id' : project_id , 'url' : url , 'push_events' : int ( bool ( push ) ) , 'issues_events' : int ( bool ( issues ) ) , 'merge_requests_events' : int ( bool ( merge_requests ) ) , 'tag_push_events' : int ( bool ( tag_push ) ) , } request = requests . post ( '{0}/{1}/hooks' . format ( self . projects_url , project_id ) , headers = self . headers , data = data , verify = self . verify_ssl , auth = self . auth , timeout = self . timeout ) if request . status_code == 201 : return request . json ( ) else : return False
add a hook to a project
59,006
def editprojecthook ( self , project_id , hook_id , url , push = False , issues = False , merge_requests = False , tag_push = False ) : data = { "id" : project_id , "hook_id" : hook_id , "url" : url , 'push_events' : int ( bool ( push ) ) , 'issues_events' : int ( bool ( issues ) ) , 'merge_requests_events' : int ( bool ( merge_requests ) ) , 'tag_push_events' : int ( bool ( tag_push ) ) , } request = requests . put ( '{0}/{1}/hooks/{2}' . format ( self . projects_url , project_id , hook_id ) , headers = self . headers , data = data , verify = self . verify_ssl , auth = self . auth , timeout = self . timeout ) if request . status_code == 200 : return True else : return False
edit an existing hook from a project
59,007
def getsystemhooks ( self , page = 1 , per_page = 20 ) : data = { 'page' : page , 'per_page' : per_page } request = requests . get ( self . hook_url , params = data , headers = self . headers , verify = self . verify_ssl , auth = self . auth , timeout = self . timeout ) if request . status_code == 200 : return request . json ( ) else : return False
Get all system hooks
59,008
def addsystemhook ( self , url ) : data = { "url" : url } request = requests . post ( self . hook_url , headers = self . headers , data = data , verify = self . verify_ssl , auth = self . auth , timeout = self . timeout ) if request . status_code == 201 : return True else : return False
Add a system hook
59,009
def deletesystemhook ( self , hook_id ) : data = { "id" : hook_id } request = requests . delete ( '{0}/{1}' . format ( self . hook_url , hook_id ) , data = data , headers = self . headers , verify = self . verify_ssl , auth = self . auth , timeout = self . timeout ) if request . status_code == 200 : return True else : return False
Delete a project hook
59,010
def createbranch ( self , project_id , branch , ref ) : data = { "id" : project_id , "branch_name" : branch , "ref" : ref } request = requests . post ( '{0}/{1}/repository/branches' . format ( self . projects_url , project_id ) , headers = self . headers , data = data , verify = self . verify_ssl , auth = self . auth , timeout = self . timeout ) if request . status_code == 201 : return request . json ( ) else : return False
Create branch from commit SHA or existing branch
59,011
def protectbranch ( self , project_id , branch ) : request = requests . put ( '{0}/{1}/repository/branches/{2}/protect' . format ( self . projects_url , project_id , branch ) , headers = self . headers , verify = self . verify_ssl , auth = self . auth , timeout = self . timeout ) if request . status_code == 200 : return True else : return False
Protect a branch from changes
59,012
def createforkrelation ( self , project_id , from_project_id ) : data = { 'id' : project_id , 'forked_from_id' : from_project_id } request = requests . post ( '{0}/{1}/fork/{2}' . format ( self . projects_url , project_id , from_project_id ) , headers = self . headers , data = data , verify = self . verify_ssl , auth = self . auth , timeout = self . timeout ) if request . status_code == 201 : return True else : return False
Create a fork relation .
59,013
def removeforkrelation ( self , project_id ) : request = requests . delete ( '{0}/{1}/fork' . format ( self . projects_url , project_id ) , headers = self . headers , verify = self . verify_ssl , auth = self . auth , timeout = self . timeout ) if request . status_code == 200 : return True else : return False
Remove an existing fork relation . this DO NOT remove the fork only the relation between them
59,014
def createfork ( self , project_id ) : request = requests . post ( '{0}/fork/{1}' . format ( self . projects_url , project_id ) , timeout = self . timeout , verify = self . verify_ssl ) if request . status_code == 200 : return True else : return False
Forks a project into the user namespace of the authenticated user .
59,015
def createissue ( self , project_id , title , ** kwargs ) : data = { 'id' : id , 'title' : title } if kwargs : data . update ( kwargs ) request = requests . post ( '{0}/{1}/issues' . format ( self . projects_url , project_id ) , headers = self . headers , data = data , verify = self . verify_ssl , auth = self . auth , timeout = self . timeout ) if request . status_code == 201 : return request . json ( ) else : return False
Create a new issue
59,016
def editissue ( self , project_id , issue_id , ** kwargs ) : data = { 'id' : project_id , 'issue_id' : issue_id } if kwargs : data . update ( kwargs ) request = requests . put ( '{0}/{1}/issues/{2}' . format ( self . projects_url , project_id , issue_id ) , headers = self . headers , data = data , verify = self . verify_ssl , auth = self . auth , timeout = self . timeout ) if request . status_code == 200 : return request . json ( ) else : return False
Edit an existing issue data
59,017
def enable_deploy_key ( self , project , key_id ) : url = '/projects/{project}/deploy_keys/{key_id}/enable' . format ( project = project , key_id = key_id ) return self . post ( url , default_response = { } )
Enables a deploy key for a project .
59,018
def adddeploykey ( self , project_id , title , key ) : data = { 'id' : project_id , 'title' : title , 'key' : key } request = requests . post ( '{0}/{1}/keys' . format ( self . projects_url , project_id ) , headers = self . headers , data = data , verify = self . verify_ssl , auth = self . auth , timeout = self . timeout ) if request . status_code == 201 : return request . json ( ) else : return False
Creates a new deploy key for a project .
59,019
def moveproject ( self , group_id , project_id ) : request = requests . post ( '{0}/{1}/projects/{2}' . format ( self . groups_url , group_id , project_id ) , headers = self . headers , verify = self . verify_ssl , auth = self . auth , timeout = self . timeout ) if request . status_code == 201 : return request . json ( ) else : return False
Move a given project into a given group
59,020
def getmergerequests ( self , project_id , page = 1 , per_page = 20 , state = None ) : data = { 'page' : page , 'per_page' : per_page , 'state' : state } request = requests . get ( '{0}/{1}/merge_requests' . format ( self . projects_url , project_id ) , params = data , headers = self . headers , verify = self . verify_ssl , auth = self . auth , timeout = self . timeout ) if request . status_code == 200 : return request . json ( ) else : return False
Get all the merge requests for a project .
59,021
def getmergerequest ( self , project_id , mergerequest_id ) : request = requests . get ( '{0}/{1}/merge_request/{2}' . format ( self . projects_url , project_id , mergerequest_id ) , headers = self . headers , verify = self . verify_ssl , auth = self . auth , timeout = self . timeout ) if request . status_code == 200 : return request . json ( ) else : return False
Get information about a specific merge request .
59,022
def createmergerequest ( self , project_id , sourcebranch , targetbranch , title , target_project_id = None , assignee_id = None ) : data = { 'source_branch' : sourcebranch , 'target_branch' : targetbranch , 'title' : title , 'assignee_id' : assignee_id , 'target_project_id' : target_project_id } request = requests . post ( '{0}/{1}/merge_requests' . format ( self . projects_url , project_id ) , data = data , headers = self . headers , verify = self . verify_ssl , auth = self . auth , timeout = self . timeout ) if request . status_code == 201 : return request . json ( ) else : return False
Create a new merge request .
59,023
def acceptmergerequest ( self , project_id , mergerequest_id , merge_commit_message = None ) : data = { 'merge_commit_message' : merge_commit_message } request = requests . put ( '{0}/{1}/merge_request/{2}/merge' . format ( self . projects_url , project_id , mergerequest_id ) , data = data , headers = self . headers , verify = self . verify_ssl , auth = self . auth , timeout = self . timeout ) if request . status_code == 200 : return request . json ( ) else : return False
Update an existing merge request .
59,024
def addcommenttomergerequest ( self , project_id , mergerequest_id , note ) : request = requests . post ( '{0}/{1}/merge_request/{2}/comments' . format ( self . projects_url , project_id , mergerequest_id ) , data = { 'note' : note } , headers = self . headers , verify = self . verify_ssl , auth = self . auth , timeout = self . timeout ) return request . status_code == 201
Add a comment to a merge request .
59,025
def createsnippet ( self , project_id , title , file_name , code , visibility_level = 0 ) : data = { 'id' : project_id , 'title' : title , 'file_name' : file_name , 'code' : code } if visibility_level in [ 0 , 10 , 20 ] : data [ 'visibility_level' ] = visibility_level request = requests . post ( '{0}/{1}/snippets' . format ( self . projects_url , project_id ) , data = data , verify = self . verify_ssl , auth = self . auth , headers = self . headers , timeout = self . timeout ) if request . status_code == 201 : return request . json ( ) else : return False
Creates an snippet
59,026
def deletesnippet ( self , project_id , snippet_id ) : request = requests . delete ( '{0}/{1}/snippets/{2}' . format ( self . projects_url , project_id , snippet_id ) , headers = self . headers , verify = self . verify_ssl , auth = self . auth , timeout = self . timeout ) return request . status_code == 200
Deletes a given snippet
59,027
def unprotectrepositorybranch ( self , project_id , branch ) : request = requests . put ( '{0}/{1}/repository/branches/{2}/unprotect' . format ( self . projects_url , project_id , branch ) , headers = self . headers , verify = self . verify_ssl , auth = self . auth , timeout = self . timeout ) if request . status_code == 200 : return request . json ( ) else : return
Unprotects a single project repository branch . This is an idempotent function unprotecting an already unprotected repository branch still returns a 200 OK status code .
59,028
def createrepositorytag ( self , project_id , tag_name , ref , message = None ) : data = { 'id' : project_id , 'tag_name' : tag_name , 'ref' : ref , 'message' : message } request = requests . post ( '{0}/{1}/repository/tags' . format ( self . projects_url , project_id ) , data = data , verify = self . verify_ssl , auth = self . auth , headers = self . headers , timeout = self . timeout ) if request . status_code == 201 : return request . json ( ) else : return False
Creates new tag in the repository that points to the supplied ref
59,029
def delete_repository_tag ( self , project_id , tag_name ) : return self . delete ( '/projects/{project_id}/repository/tags/{tag_name}' . format ( project_id = project_id , tag_name = tag_name ) )
Deletes a tag of a repository with given name .
59,030
def addcommenttocommit ( self , project_id , author , sha , path , line , note ) : data = { 'author' : author , 'note' : note , 'path' : path , 'line' : line , 'line_type' : 'new' } request = requests . post ( '{0}/{1}/repository/commits/{2}/comments' . format ( self . projects_url , project_id , sha ) , headers = self . headers , data = data , verify = self . verify_ssl ) if request . status_code == 201 : return True else : return False
Adds an inline comment to a specific commit
59,031
def getrepositorytree ( self , project_id , ** kwargs ) : data = { } if kwargs : data . update ( kwargs ) request = requests . get ( '{0}/{1}/repository/tree' . format ( self . projects_url , project_id ) , params = data , verify = self . verify_ssl , auth = self . auth , headers = self . headers , timeout = self . timeout ) if request . status_code == 200 : return request . json ( ) else : return False
Get a list of repository files and directories in a project .
59,032
def getrawfile ( self , project_id , sha1 , filepath ) : data = { 'filepath' : filepath } request = requests . get ( '{0}/{1}/repository/blobs/{2}' . format ( self . projects_url , project_id , sha1 ) , params = data , verify = self . verify_ssl , auth = self . auth , timeout = self . timeout , headers = self . headers ) if request . status_code == 200 : return request . content else : return False
Get the raw file contents for a file by commit SHA and path .
59,033
def getrawblob ( self , project_id , sha1 ) : request = requests . get ( '{0}/{1}/repository/raw_blobs/{2}' . format ( self . projects_url , project_id , sha1 ) , verify = self . verify_ssl , auth = self . auth , headers = self . headers , timeout = self . timeout ) if request . status_code == 200 : return request . content else : return False
Get the raw file contents for a blob by blob SHA .
59,034
def compare_branches_tags_commits ( self , project_id , from_id , to_id ) : data = { 'from' : from_id , 'to' : to_id } request = requests . get ( '{0}/{1}/repository/compare' . format ( self . projects_url , project_id ) , params = data , verify = self . verify_ssl , auth = self . auth , timeout = self . timeout , headers = self . headers ) if request . status_code == 200 : return request . json ( ) else : return False
Compare branches tags or commits
59,035
def searchproject ( self , search , page = 1 , per_page = 20 ) : data = { 'page' : page , 'per_page' : per_page } request = requests . get ( "{0}/{1}" . format ( self . search_url , search ) , params = data , verify = self . verify_ssl , auth = self . auth , headers = self . headers , timeout = self . timeout ) if request . status_code == 200 : return request . json ( ) else : return False
Search for projects by name which are accessible to the authenticated user
59,036
def getfilearchive ( self , project_id , filepath = None ) : if not filepath : filepath = '' request = requests . get ( '{0}/{1}/repository/archive' . format ( self . projects_url , project_id ) , verify = self . verify_ssl , auth = self . auth , headers = self . headers , timeout = self . timeout ) if request . status_code == 200 : if filepath == "" : filepath = request . headers [ 'content-disposition' ] . split ( ';' ) [ 1 ] . split ( '=' ) [ 1 ] . strip ( '"' ) with open ( filepath , 'wb' ) as filesave : filesave . write ( request . content ) return True else : msg = request . json ( ) [ 'message' ] raise exceptions . HttpError ( msg )
Get an archive of the repository
59,037
def deletegroup ( self , group_id ) : request = requests . delete ( '{0}/{1}' . format ( self . groups_url , group_id ) , headers = self . headers , verify = self . verify_ssl , auth = self . auth , timeout = self . timeout ) return request . status_code == 200
Deletes an group by ID
59,038
def getgroupmembers ( self , group_id , page = 1 , per_page = 20 ) : data = { 'page' : page , 'per_page' : per_page } request = requests . get ( '{0}/{1}/members' . format ( self . groups_url , group_id ) , params = data , headers = self . headers , verify = self . verify_ssl , auth = self . auth , timeout = self . timeout ) if request . status_code == 200 : return request . json ( ) else : return False
Lists the members of a given group id
59,039
def deletegroupmember ( self , group_id , user_id ) : request = requests . delete ( '{0}/{1}/members/{2}' . format ( self . groups_url , group_id , user_id ) , headers = self . headers , verify = self . verify_ssl , auth = self . auth , timeout = self . timeout ) if request . status_code == 200 : return True
Delete a group member
59,040
def addldapgrouplink ( self , group_id , cn , group_access , provider ) : data = { 'id' : group_id , 'cn' : cn , 'group_access' : group_access , 'provider' : provider } request = requests . post ( '{0}/{1}/ldap_group_links' . format ( self . groups_url , group_id ) , headers = self . headers , data = data , verify = self . verify_ssl ) return request . status_code == 201
Add LDAP group link
59,041
def createissuewallnote ( self , project_id , issue_id , content ) : data = { 'body' : content } request = requests . post ( '{0}/{1}/issues/{2}/notes' . format ( self . projects_url , project_id , issue_id ) , verify = self . verify_ssl , auth = self . auth , headers = self . headers , data = data , timeout = self . timeout ) if request . status_code == 201 : return request . json ( ) else : return False
Create a new note
59,042
def createfile ( self , project_id , file_path , branch_name , encoding , content , commit_message ) : data = { 'file_path' : file_path , 'branch_name' : branch_name , 'encoding' : encoding , 'content' : content , 'commit_message' : commit_message } request = requests . post ( '{0}/{1}/repository/files' . format ( self . projects_url , project_id ) , verify = self . verify_ssl , auth = self . auth , headers = self . headers , data = data , timeout = self . timeout ) return request . status_code == 201
Creates a new file in the repository
59,043
def updatefile ( self , project_id , file_path , branch_name , content , commit_message ) : data = { 'file_path' : file_path , 'branch_name' : branch_name , 'content' : content , 'commit_message' : commit_message } request = requests . put ( '{0}/{1}/repository/files' . format ( self . projects_url , project_id ) , headers = self . headers , data = data , verify = self . verify_ssl , auth = self . auth , timeout = self . timeout ) return request . status_code == 200
Updates an existing file in the repository
59,044
def getfile ( self , project_id , file_path , ref ) : data = { 'file_path' : file_path , 'ref' : ref } request = requests . get ( '{0}/{1}/repository/files' . format ( self . projects_url , project_id ) , headers = self . headers , data = data , verify = self . verify_ssl , auth = self . auth , timeout = self . timeout ) if request . status_code == 200 : return request . json ( ) else : return False
Allows you to receive information about file in repository like name size content . Note that file content is Base64 encoded .
59,045
def deletefile ( self , project_id , file_path , branch_name , commit_message ) : data = { 'file_path' : file_path , 'branch_name' : branch_name , 'commit_message' : commit_message } request = requests . delete ( '{0}/{1}/repository/files' . format ( self . projects_url , project_id ) , headers = self . headers , data = data , verify = self . verify_ssl , auth = self . auth , timeout = self . timeout ) return request . status_code == 200
Deletes existing file in the repository
59,046
def setgitlabciservice ( self , project_id , token , project_url ) : data = { 'token' : token , 'project_url' : project_url } request = requests . put ( '{0}/{1}/services/gitlab-ci' . format ( self . projects_url , project_id ) , verify = self . verify_ssl , auth = self . auth , headers = self . headers , data = data , timeout = self . timeout ) return request . status_code == 200
Set GitLab CI service for project
59,047
def deletegitlabciservice ( self , project_id , token , project_url ) : request = requests . delete ( '{0}/{1}/services/gitlab-ci' . format ( self . projects_url , project_id ) , headers = self . headers , verify = self . verify_ssl , auth = self . auth , timeout = self . timeout ) return request . status_code == 200
Delete GitLab CI service settings
59,048
def createlabel ( self , project_id , name , color ) : data = { 'name' : name , 'color' : color } request = requests . post ( '{0}/{1}/labels' . format ( self . projects_url , project_id ) , data = data , verify = self . verify_ssl , auth = self . auth , headers = self . headers , timeout = self . timeout ) if request . status_code == 201 : return request . json ( ) else : return False
Creates a new label for given repository with given name and color .
59,049
def deletelabel ( self , project_id , name ) : data = { 'name' : name } request = requests . delete ( '{0}/{1}/labels' . format ( self . projects_url , project_id ) , data = data , verify = self . verify_ssl , auth = self . auth , headers = self . headers , timeout = self . timeout ) return request . status_code == 200
Deletes a label given by its name .
59,050
def editlabel ( self , project_id , name , new_name = None , color = None ) : data = { 'name' : name , 'new_name' : new_name , 'color' : color } request = requests . put ( '{0}/{1}/labels' . format ( self . projects_url , project_id ) , data = data , verify = self . verify_ssl , auth = self . auth , headers = self . headers , timeout = self . timeout ) if request . status_code == 200 : return request . json ( ) else : return False
Updates an existing label with new name or now color . At least one parameter is required to update the label .
59,051
def getnamespaces ( self , search = None , page = 1 , per_page = 20 ) : data = { 'page' : page , 'per_page' : per_page } if search : data [ 'search' ] = search request = requests . get ( self . namespaces_url , params = data , headers = self . headers , verify = self . verify_ssl ) if request . status_code == 200 : return request . json ( ) else : return False
Return a namespace list
59,052
def get_field_mro ( cls , field_name ) : res = set ( ) if hasattr ( cls , '__mro__' ) : for _class in inspect . getmro ( cls ) : values_ = getattr ( _class , field_name , None ) if values_ is not None : res = res . union ( set ( make_list ( values_ ) ) ) return res
Goes up the mro and looks for the specified field .
59,053
def connect ( self ) : logging . info ( "Connecting to {} with user {}." . format ( self . host , self . username ) ) credentials = pika . PlainCredentials ( self . username , self . password ) connection_params = pika . ConnectionParameters ( host = self . host , credentials = credentials , heartbeat_interval = self . heartbeat_interval ) self . connection = pika . BlockingConnection ( connection_params )
Create internal connection to AMQP service .
59,054
def close ( self ) : if self . connection : logging . info ( "Closing connection to {}." . format ( self . host ) ) self . connection . close ( ) self . connection = None
Close internal connection to AMQP if connected .
59,055
def process_messages_loop ( self ) : self . receiving_messages = True try : self . process_messages_loop_internal ( ) except pika . exceptions . ConnectionClosed as ex : logging . error ( "Connection closed {}." . format ( ex ) ) raise
Processes incoming WorkRequest messages one at a time via functions specified by add_command .
59,056
def process_messages_loop_internal ( self ) : logging . info ( "Starting work queue loop." ) self . connection . receive_loop_with_callback ( self . queue_name , self . process_message )
Busy loop that processes incoming WorkRequest messages via functions specified by add_command . Terminates if a command runs shutdown method
59,057
def process_messages_loop_internal ( self ) : while self . receiving_messages : self . work_request = None self . connection . receive_loop_with_callback ( self . queue_name , self . save_work_request_and_close ) if self . work_request : self . process_work_request ( )
Busy loop that processes incoming WorkRequest messages via functions specified by add_command . Disconnects while servicing a message reconnects once finished processing a message Terminates if a command runs shutdown method
59,058
def save_work_request_and_close ( self , ch , method , properties , body ) : self . work_request = pickle . loads ( body ) ch . basic_ack ( delivery_tag = method . delivery_tag ) ch . stop_consuming ( ) self . connection . close ( )
Save message body and close connection
59,059
def get_related_galleries ( gallery , count = 5 ) : try : cat = gallery . sections . all ( ) [ 0 ] related = cat . gallery_categories . filter ( published = True ) . exclude ( id = gallery . id ) . order_by ( '-id' ) [ : count ] except : related = None return { 'related' : related , 'MEDIA_URL' : settings . MEDIA_URL }
Gets latest related galleries from same section as originating gallery .
59,060
def load_healthchecks ( self ) : self . load_default_healthchecks ( ) if getattr ( settings , 'AUTODISCOVER_HEALTHCHECKS' , True ) : self . autodiscover_healthchecks ( ) self . _registry_loaded = True
Loads healthchecks .
59,061
def load_default_healthchecks ( self ) : default_healthchecks = getattr ( settings , 'HEALTHCHECKS' , DEFAULT_HEALTHCHECKS ) for healthcheck in default_healthchecks : healthcheck = import_string ( healthcheck ) self . register_healthcheck ( healthcheck )
Loads healthchecks specified in settings . HEALTHCHECKS as dotted import paths to the classes . Defaults are listed in DEFAULT_HEALTHCHECKS .
59,062
def run_healthchecks ( self ) : if not self . _registry_loaded : self . load_healthchecks ( ) def get_healthcheck_name ( hc ) : if hasattr ( hc , 'name' ) : return hc . name return hc . __name__ responses = [ ] for healthcheck in self . _registry : try : if inspect . isclass ( healthcheck ) : healthcheck = healthcheck ( ) response = healthcheck ( ) if isinstance ( response , bool ) : response = HealthcheckResponse ( name = get_healthcheck_name ( healthcheck ) , status = response , ) except Exception as e : response = HealthcheckResponse ( name = get_healthcheck_name ( healthcheck ) , status = False , exception = str ( e ) , exception_class = e . __class__ . __name__ , ) responses . append ( response ) return responses
Runs all registered healthchecks and returns a list of HealthcheckResponse .
59,063
def advance_by ( self , amount ) : if amount < 0 : raise ValueError ( "cannot retreat time reference: amount {} < 0" . format ( amount ) ) self . __delta += amount
Advance the time reference by the given amount .
59,064
def advance_to ( self , timestamp ) : now = self . __original_time ( ) if timestamp < now : raise ValueError ( "cannot retreat time reference: " "target {} < now {}" . format ( timestamp , now ) ) self . __delta = timestamp - now
Advance the time reference so that now is the given timestamp .
59,065
def reset_frequencies ( self , frequency = 0 ) : frequency = max ( frequency , 0 ) for key in self . _store . keys ( ) : self . _store [ key ] = ( self . _store [ key ] [ 0 ] , frequency ) return frequency
Resets all stored frequencies for the cache
59,066
def oldest ( self ) : if len ( self . _store ) == 0 : return kv = min ( self . _store . items ( ) , key = lambda x : x [ 1 ] [ 1 ] ) return kv [ 0 ] , kv [ 1 ] [ 0 ]
Gets key value pair for oldest item in cache
59,067
def parser_helper ( key , val ) : start_bracket = key . find ( "[" ) end_bracket = key . find ( "]" ) pdict = { } if has_variable_name ( key ) : pdict [ key [ : key . find ( "[" ) ] ] = parser_helper ( key [ start_bracket : ] , val ) elif more_than_one_index ( key ) : newkey = get_key ( key ) newkey = int ( newkey ) if is_number ( newkey ) else newkey pdict [ newkey ] = parser_helper ( key [ end_bracket + 1 : ] , val ) else : newkey = key if start_bracket != - 1 : newkey = get_key ( key ) if newkey is None : raise MalformedQueryStringError newkey = int ( newkey ) if is_number ( newkey ) else newkey if key == u'[]' : val = int ( val ) if is_number ( val ) else val pdict [ newkey ] = val return pdict
Helper for parser function
59,068
def parse ( query_string , unquote = True , normalized = False , encoding = DEFAULT_ENCODING ) : mydict = { } plist = [ ] if query_string == "" : return mydict if type ( query_string ) == bytes : query_string = query_string . decode ( ) for element in query_string . split ( "&" ) : try : if unquote : ( var , val ) = element . split ( "=" ) if sys . version_info [ 0 ] == 2 : var = var . encode ( 'ascii' ) val = val . encode ( 'ascii' ) var = urllib . unquote_plus ( var ) val = urllib . unquote_plus ( val ) else : ( var , val ) = element . split ( "=" ) except ValueError : raise MalformedQueryStringError if encoding : var = var . decode ( encoding ) val = val . decode ( encoding ) plist . append ( parser_helper ( var , val ) ) for di in plist : ( k , v ) = di . popitem ( ) tempdict = mydict while k in tempdict and type ( v ) is dict : tempdict = tempdict [ k ] ( k , v ) = v . popitem ( ) if k in tempdict and type ( tempdict [ k ] ) . __name__ == 'list' : tempdict [ k ] . append ( v ) elif k in tempdict : tempdict [ k ] = [ tempdict [ k ] , v ] else : tempdict [ k ] = v if normalized == True : return _normalize ( mydict ) return mydict
Main parse function
59,069
def validate_swagger_schema ( schema_dir , resource_listing ) : schema_filepath = os . path . join ( schema_dir , API_DOCS_FILENAME ) swagger_spec_validator . validator12 . validate_spec ( resource_listing , urlparse . urljoin ( 'file:' , pathname2url ( os . path . abspath ( schema_filepath ) ) ) , )
Validate the structure of Swagger schemas against the spec .
59,070
def build_param_schema ( schema , param_type ) : properties = filter_params_by_type ( schema , param_type ) if not properties : return return { 'type' : 'object' , 'properties' : dict ( ( p [ 'name' ] , p ) for p in properties ) , 'additionalProperties' : param_type == 'header' , }
Turn a swagger endpoint schema into an equivalent one to validate our request .
59,071
def required_validator ( validator , req , instance , schema ) : if schema . get ( 'paramType' ) : if req is True and not instance : return [ ValidationError ( "%s is required" % schema [ 'name' ] ) ] return [ ] return _validators . required_draft4 ( validator , req , instance , schema )
Swagger 1 . 2 expects required to be a bool in the Parameter object but a list of properties in a Model object .
59,072
def load_schema ( schema_path ) : with open ( schema_path , 'r' ) as schema_file : schema = simplejson . load ( schema_file ) resolver = RefResolver ( '' , '' , schema . get ( 'models' , { } ) ) return build_request_to_validator_map ( schema , resolver )
Prepare the api specification for request and response validation .
59,073
def get_swagger_objects ( settings , route_info , registry ) : enabled_swagger_versions = get_swagger_versions ( registry . settings ) schema12 = registry . settings [ 'pyramid_swagger.schema12' ] schema20 = registry . settings [ 'pyramid_swagger.schema20' ] fallback_to_swagger12_route = ( SWAGGER_20 in enabled_swagger_versions and SWAGGER_12 in enabled_swagger_versions and settings . prefer_20_routes and route_info . get ( 'route' ) and route_info [ 'route' ] . name not in settings . prefer_20_routes ) if fallback_to_swagger12_route : return settings . swagger12_handler , schema12 if SWAGGER_20 in enabled_swagger_versions : return settings . swagger20_handler , schema20 if SWAGGER_12 in enabled_swagger_versions : return settings . swagger12_handler , schema12
Returns appropriate swagger handler and swagger spec schema .
59,074
def validation_tween_factory ( handler , registry ) : settings = load_settings ( registry ) route_mapper = registry . queryUtility ( IRoutesMapper ) validation_context = _get_validation_context ( registry ) def validator_tween ( request ) : route_info = route_mapper ( request ) swagger_handler , spec = get_swagger_objects ( settings , route_info , registry ) if should_exclude_request ( settings , request , route_info ) : return handler ( request ) try : op_or_validators_map = swagger_handler . op_for_request ( request , route_info = route_info , spec = spec ) except PathNotMatchedError as exc : if settings . validate_path : with validation_context ( request ) : raise PathNotFoundError ( str ( exc ) , child = exc ) else : return handler ( request ) def operation ( _ ) : return op_or_validators_map if isinstance ( op_or_validators_map , Operation ) else None request . set_property ( operation ) if settings . validate_request : with validation_context ( request , response = None ) : request_data = swagger_handler . handle_request ( PyramidSwaggerRequest ( request , route_info ) , op_or_validators_map , ) def swagger_data ( _ ) : return request_data request . set_property ( swagger_data ) response = handler ( request ) if settings . validate_response : with validation_context ( request , response = response ) : swagger_handler . handle_response ( response , op_or_validators_map ) return response return validator_tween
Pyramid tween for performing validation .
59,075
def handle_request ( request , validator_map , ** kwargs ) : request_data = { } validation_pairs = [ ] for validator , values in [ ( validator_map . query , request . query ) , ( validator_map . path , request . path ) , ( validator_map . form , request . form ) , ( validator_map . headers , request . headers ) , ] : values = cast_params ( validator . schema , values ) validation_pairs . append ( ( validator , values ) ) request_data . update ( values ) if validator_map . body . schema : param_name = validator_map . body . schema [ 'name' ] validation_pairs . append ( ( validator_map . body , request . body ) ) request_data [ param_name ] = request . body validate_request ( validation_pairs ) return request_data
Validate the request against the swagger spec and return a dict with all parameter values available in the request casted to the expected python type .
59,076
def build_swagger12_handler ( schema ) : if schema : return SwaggerHandler ( op_for_request = schema . validators_for_request , handle_request = handle_request , handle_response = validate_response , )
Builds a swagger12 handler or returns None if no schema is present .
59,077
def validate_response ( response , validator_map ) : validator = validator_map . response returns_nothing = validator . schema . get ( 'type' ) == 'void' body_empty = response . body in ( None , b'' , b'{}' , b'null' ) if returns_nothing and body_empty : return if not 200 <= response . status_code <= 203 : return validator . validate ( prepare_body ( response ) )
Validates response against our schemas .
59,078
def swaggerize_response ( response , op ) : response_spec = get_response_spec ( response . status_int , op ) bravado_core . response . validate_response ( response_spec , op , PyramidSwaggerResponse ( response ) )
Delegate handling the Swagger concerns of the response to bravado - core .
59,079
def get_op_for_request ( request , route_info , spec ) : route = route_info [ 'route' ] if hasattr ( route , 'path' ) : route_path = route . path if route_path [ 0 ] != '/' : route_path = '/' + route_path op = spec . get_op_for_request ( request . method , route_path ) if op is not None : return op else : raise PathNotMatchedError ( "Could not find a matching Swagger " "operation for {0} request {1}" . format ( request . method , request . url ) ) else : raise PathNotMatchedError ( "Could not find a matching route for {0} request {1}. " "Have you registered this endpoint with Pyramid?" . format ( request . method , request . url ) )
Find out which operation in the Swagger schema corresponds to the given pyramid request .
59,080
def get_swagger_versions ( settings ) : swagger_versions = set ( aslist ( settings . get ( 'pyramid_swagger.swagger_versions' , DEFAULT_SWAGGER_VERSIONS ) ) ) if len ( swagger_versions ) == 0 : raise ValueError ( 'pyramid_swagger.swagger_versions is empty' ) for swagger_version in swagger_versions : if swagger_version not in SUPPORTED_SWAGGER_VERSIONS : raise ValueError ( 'Swagger version {0} is not supported.' . format ( swagger_version ) ) return swagger_versions
Validates and returns the versions of the Swagger Spec that this pyramid application supports .
59,081
def register_api_doc_endpoints ( config , endpoints , base_path = '/api-docs' ) : for endpoint in endpoints : path = base_path . rstrip ( '/' ) + endpoint . path config . add_route ( endpoint . route_name , path ) config . add_view ( endpoint . view , route_name = endpoint . route_name , renderer = endpoint . renderer )
Create and register pyramid endpoints to service swagger api docs . Routes and views will be registered on the config at path .
59,082
def build_swagger_12_api_declaration_view ( api_declaration_json ) : def view_for_api_declaration ( request ) : return dict ( api_declaration_json , basePath = str ( request . application_url ) , ) return view_for_api_declaration
Thanks to the magic of closures this means we gracefully return JSON without file IO at request time .
59,083
def partial_path_match ( path1 , path2 , kwarg_re = r'\{.*\}' ) : split_p1 = path1 . split ( '/' ) split_p2 = path2 . split ( '/' ) pat = re . compile ( kwarg_re ) if len ( split_p1 ) != len ( split_p2 ) : return False for partial_p1 , partial_p2 in zip ( split_p1 , split_p2 ) : if pat . match ( partial_p1 ) or pat . match ( partial_p2 ) : continue if not partial_p1 == partial_p2 : return False return True
Validates if path1 and path2 matches ignoring any kwargs in the string .
59,084
def validators_for_request ( self , request , ** kwargs ) : for resource_validator in self . resource_validators : for matcher , validator_map in resource_validator . items ( ) : if matcher . matches ( request ) : return validator_map raise PathNotMatchedError ( 'Could not find the relevant path ({0}) in the Swagger schema. ' 'Perhaps you forgot to add it?' . format ( request . path_info ) )
Takes a request and returns a validator mapping for the request .
59,085
def build_schema_mapping ( schema_dir , resource_listing ) : def resource_name_to_filepath ( name ) : return os . path . join ( schema_dir , '{0}.json' . format ( name ) ) return dict ( ( resource , resource_name_to_filepath ( resource ) ) for resource in find_resource_names ( resource_listing ) )
Discovers schema file locations and relations .
59,086
def _load_resource_listing ( resource_listing ) : try : with open ( resource_listing ) as resource_listing_file : return simplejson . load ( resource_listing_file ) except IOError : raise ResourceListingNotFoundError ( 'No resource listing found at {0}. Note that your json file ' 'must be named {1}' . format ( resource_listing , API_DOCS_FILENAME ) )
Load the resource listing from file handling errors .
59,087
def get_resource_listing ( schema_dir , should_generate_resource_listing ) : listing_filename = os . path . join ( schema_dir , API_DOCS_FILENAME ) resource_listing = _load_resource_listing ( listing_filename ) if not should_generate_resource_listing : return resource_listing return generate_resource_listing ( schema_dir , resource_listing )
Return the resource listing document .
59,088
def compile_swagger_schema ( schema_dir , resource_listing ) : mapping = build_schema_mapping ( schema_dir , resource_listing ) resource_validators = ingest_resources ( mapping , schema_dir ) endpoints = list ( build_swagger_12_endpoints ( resource_listing , mapping ) ) return SwaggerSchema ( endpoints , resource_validators )
Build a SwaggerSchema from various files .
59,089
def create_bravado_core_config ( settings ) : config_keys = { 'pyramid_swagger.enable_request_validation' : 'validate_requests' , 'pyramid_swagger.enable_response_validation' : 'validate_responses' , 'pyramid_swagger.enable_swagger_spec_validation' : 'validate_swagger_spec' , 'pyramid_swagger.use_models' : 'use_models' , 'pyramid_swagger.user_formats' : 'formats' , 'pyramid_swagger.include_missing_properties' : 'include_missing_properties' , } configs = { 'use_models' : False } bravado_core_configs_from_pyramid_swagger_configs = { bravado_core_key : settings [ pyramid_swagger_key ] for pyramid_swagger_key , bravado_core_key in iteritems ( config_keys ) if pyramid_swagger_key in settings } if bravado_core_configs_from_pyramid_swagger_configs : warnings . warn ( message = 'Configs {old_configs} are deprecated, please use {new_configs} instead.' . format ( old_configs = ', ' . join ( k for k , v in sorted ( iteritems ( config_keys ) ) ) , new_configs = ', ' . join ( '{}{}' . format ( BRAVADO_CORE_CONFIG_PREFIX , v ) for k , v in sorted ( iteritems ( config_keys ) ) ) , ) , category = DeprecationWarning , ) configs . update ( bravado_core_configs_from_pyramid_swagger_configs ) configs . update ( { key . replace ( BRAVADO_CORE_CONFIG_PREFIX , '' ) : value for key , value in iteritems ( settings ) if key . startswith ( BRAVADO_CORE_CONFIG_PREFIX ) } ) return configs
Create a configuration dict for bravado_core based on pyramid_swagger settings .
59,090
def ingest_resources ( mapping , schema_dir ) : ingested_resources = [ ] for name , filepath in iteritems ( mapping ) : try : ingested_resources . append ( load_schema ( filepath ) ) except IOError : raise ApiDeclarationNotFoundError ( 'No api declaration found at {0}. Attempted to load the `{1}` ' 'resource relative to the schema_directory `{2}`. Perhaps ' 'your resource name and API declaration file do not ' 'match?' . format ( filepath , name , schema_dir ) ) return ingested_resources
Consume the Swagger schemas and produce a queryable datastructure .
59,091
def read_array ( self , infile , var_name ) : file_handle = self . read_cdf ( infile ) try : return file_handle . variables [ var_name ] [ : ] except KeyError : print ( "Cannot find variable: {0}" . format ( var_name ) ) raise KeyError
Directly return a numpy array for a given variable name
59,092
def read_ma_array ( self , infile , var_name ) : file_obj = self . read_cdf ( infile ) data = file_obj . variables [ var_name ] [ : ] try : import numpy as np except Exception : raise ImportError ( "numpy is required to return masked arrays." ) if hasattr ( file_obj . variables [ var_name ] , "_FillValue" ) : fill_val = file_obj . variables [ var_name ] . _FillValue retval = np . ma . masked_where ( data == fill_val , data ) else : retval = np . ma . array ( data ) return retval
Create a masked array based on cdf s FillValue
59,093
def digest ( self , data = None ) : if data is not None : self . update ( data ) b = create_string_buffer ( 256 ) size = c_size_t ( 256 ) if libcrypto . EVP_DigestSignFinal ( self . ctx , b , pointer ( size ) ) <= 0 : raise DigestError ( 'SignFinal' ) self . digest_finalized = True return b . raw [ : size . value ]
Method digest is redefined to return keyed MAC value instead of just digest .
59,094
def bytes ( num , check_result = False ) : if num <= 0 : raise ValueError ( "'num' should be > 0" ) buf = create_string_buffer ( num ) result = libcrypto . RAND_bytes ( buf , num ) if check_result and result == 0 : raise RandError ( "Random Number Generator not seeded sufficiently" ) return buf . raw [ : num ]
Returns num bytes of cryptographically strong pseudo - random bytes . If checkc_result is True raises error if PRNG is not seeded enough
59,095
def create ( dotted , shortname , longname ) : if pyver > 2 : dotted = dotted . encode ( 'ascii' ) shortname = shortname . encode ( 'utf-8' ) longname = longname . encode ( 'utf-8' ) nid = libcrypto . OBJ_create ( dotted , shortname , longname ) if nid == 0 : raise LibCryptoError ( "Problem adding new OID to the database" ) return Oid ( nid )
Creates new OID in the database
59,096
def dotted ( self ) : " Returns dotted-decimal reperesentation " obj = libcrypto . OBJ_nid2obj ( self . nid ) buf = create_string_buffer ( 256 ) libcrypto . OBJ_obj2txt ( buf , 256 , obj , 1 ) if pyver == 2 : return buf . value else : return buf . value . decode ( 'ascii' )
Returns dotted - decimal reperesentation
59,097
def fromobj ( obj ) : nid = libcrypto . OBJ_obj2nid ( obj ) if nid == 0 : buf = create_string_buffer ( 80 ) dotted_len = libcrypto . OBJ_obj2txt ( buf , 80 , obj , 1 ) dotted = buf [ : dotted_len ] oid = create ( dotted , dotted , dotted ) else : oid = Oid ( nid ) return oid
Creates an OID object from the pointer to ASN1_OBJECT c structure . This method intended for internal use for submodules which deal with libcrypto ASN1 parsing functions such as x509 or CMS
59,098
def _password_callback ( c ) : if c is None : return PW_CALLBACK_FUNC ( 0 ) if callable ( c ) : if pyver == 2 : def __cb ( buf , length , rwflag , userdata ) : pwd = c ( rwflag ) cnt = min ( len ( pwd ) , length ) memmove ( buf , pwd , cnt ) return cnt else : def __cb ( buf , length , rwflag , userdata ) : pwd = c ( rwflag ) . encode ( "utf-8" ) cnt = min ( len ( pwd ) , length ) memmove ( buf , pwd , cnt ) return cnt else : if pyver > 2 : c = c . encode ( "utf-8" ) def __cb ( buf , length , rwflag , userdata ) : cnt = min ( len ( c ) , length ) memmove ( buf , c , cnt ) return cnt return PW_CALLBACK_FUNC ( __cb )
Converts given user function or string to C password callback function passable to openssl .
59,099
def verify ( self , digest , signature , ** kwargs ) : ctx = libcrypto . EVP_PKEY_CTX_new ( self . key , None ) if ctx is None : raise PKeyError ( "Initailizing verify context" ) if libcrypto . EVP_PKEY_verify_init ( ctx ) < 1 : raise PKeyError ( "verify_init" ) self . _configure_context ( ctx , kwargs ) ret = libcrypto . EVP_PKEY_verify ( ctx , signature , len ( signature ) , digest , len ( digest ) ) if ret < 0 : raise PKeyError ( "Signature verification" ) libcrypto . EVP_PKEY_CTX_free ( ctx ) return ret > 0
Verifies given signature on given digest Returns True if Ok False if don t match Keyword arguments allows to set algorithm - specific parameters