text_prompt
stringlengths 100
17.7k
⌀ | code_prompt
stringlengths 7
9.86k
⌀ |
---|---|
<SYSTEM_TASK:>
Gets all the ssh keys for the current user
<END_TASK>
<USER_TASK:>
Description:
def getsshkeys(self):
"""
Gets all the ssh keys for the current user
:return: a dictionary with the lists
""" |
request = requests.get(
self.keys_url, headers=self.headers, verify=self.verify_ssl, auth=self.auth, timeout=self.timeout)
if request.status_code == 200:
return request.json()
else:
return False |
<SYSTEM_TASK:>
Add a new ssh key for the current user
<END_TASK>
<USER_TASK:>
Description:
def addsshkey(self, title, key):
"""
Add a new ssh key for the current user
:param title: title of the new key
:param key: the key itself
:return: true if added, false if it didn't add it (it could be because the name or key already exists)
""" |
data = {'title': title, 'key': key}
request = requests.post(
self.keys_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 |
<SYSTEM_TASK:>
Add a new ssh key for the user identified by id
<END_TASK>
<USER_TASK:>
Description:
def addsshkeyuser(self, user_id, title, key):
"""
Add a new ssh key for the user identified by id
:param user_id: id of the user to add the key to
:param title: title of the new key
:param key: the key itself
:return: true if added, false if it didn't add it (it could be because the name or key already exists)
""" |
data = {'title': title, 'key': key}
request = requests.post(
'{0}/{1}/keys'.format(self.users_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 |
<SYSTEM_TASK:>
Deletes an sshkey for the current user identified by id
<END_TASK>
<USER_TASK:>
Description:
def deletesshkey(self, key_id):
"""
Deletes an sshkey for the current user identified by id
:param key_id: the id of the key
:return: False if it didn't delete it, True if it was deleted
""" |
request = requests.delete(
'{0}/{1}'.format(self.keys_url, key_id), headers=self.headers,
verify=self.verify_ssl, auth=self.auth, timeout=self.timeout)
if request.content == b'null':
return False
else:
return True |
<SYSTEM_TASK:>
Call GET on the Gitlab server
<END_TASK>
<USER_TASK:>
Description:
def get(self, uri, default_response=None, **kwargs):
"""
Call GET on the Gitlab server
>>> gitlab = Gitlab(host='http://localhost:10080', verify_ssl=False)
>>> gitlab.login(user='root', password='5iveL!fe')
>>> gitlab.get('/users/5')
:param uri: String with the URI for the endpoint to GET from
:param default_response: Return value if JSONDecodeError
:param kwargs: Key word arguments to use as GET arguments
:return: Dictionary containing response data
:raise: HttpError: If invalid response returned
""" |
url = self.api_url + uri
response = requests.get(url, params=kwargs, headers=self.headers,
verify=self.verify_ssl, auth=self.auth,
timeout=self.timeout)
return self.success_or_raise(response, default_response=default_response) |
<SYSTEM_TASK:>
Call POST on the Gitlab server
<END_TASK>
<USER_TASK:>
Description:
def post(self, uri, default_response=None, **kwargs):
"""
Call POST on the Gitlab server
>>> gitlab = Gitlab(host='http://localhost:10080', verify_ssl=False)
>>> gitlab.login(user='root', password='5iveL!fe')
>>> password = 'MyTestPassword1'
>>> email = '[email protected]'
>>> data = {'name': 'test', 'username': 'test1', 'password': password, 'email': email}
>>> gitlab.post('/users/5', **data)
:param uri: String with the URI for the endpoint to POST to
:param default_response: Return value if JSONDecodeError
:param kwargs: Key word arguments representing the data to use in the POST
:return: Dictionary containing response data
:raise: HttpError: If invalid response returned
""" |
url = self.api_url + uri
response = requests.post(
url, headers=self.headers, data=kwargs,
verify=self.verify_ssl, auth=self.auth, timeout=self.timeout)
return self.success_or_raise(response, default_response=default_response) |
<SYSTEM_TASK:>
Call DELETE on the Gitlab server
<END_TASK>
<USER_TASK:>
Description:
def delete(self, uri, default_response=None):
"""
Call DELETE on the Gitlab server
>>> gitlab = Gitlab(host='http://localhost:10080', verify_ssl=False)
>>> gitlab.login(user='root', password='5iveL!fe')
>>> gitlab.delete('/users/5')
:param uri: String with the URI you wish to delete
:param default_response: Return value if JSONDecodeError
:return: Dictionary containing response data
:raise: HttpError: If invalid response returned
""" |
url = self.api_url + uri
response = requests.delete(
url, headers=self.headers, verify=self.verify_ssl,
auth=self.auth, timeout=self.timeout)
return self.success_or_raise(response, default_response=default_response) |
<SYSTEM_TASK:>
Check if request was successful or raises an HttpError
<END_TASK>
<USER_TASK:>
Description:
def success_or_raise(self, response, default_response=None):
"""
Check if request was successful or raises an HttpError
:param response: Response Object to check
:param default_response: Return value if JSONDecodeError
:returns dict: Dictionary containing response data
:returns bool: :obj:`False` on failure when exceptions are suppressed
:raises requests.exceptions.HTTPError: If invalid response returned
""" |
if self.suppress_http_error and not response.ok:
return False
response_json = default_response
if response_json is None:
response_json = {}
response.raise_for_status()
try:
response_json = response.json()
except ValueError:
pass
return response_json |
<SYSTEM_TASK:>
Auto-iterate over the paginated results of various methods of the API.
<END_TASK>
<USER_TASK:>
Description:
def getall(fn, page=None, *args, **kwargs):
"""
Auto-iterate over the paginated results of various methods of the API.
Pass the GitLabAPI method as the first argument, followed by the
other parameters as normal. Include `page` to determine first page to poll.
Remaining kwargs are passed on to the called method, including `per_page`.
:param fn: Actual method to call
:param page: Optional, page number to start at, defaults to 1
:param args: Positional arguments to actual method
:param kwargs: Keyword arguments to actual method
:return: Yields each item in the result until exhausted, and then implicit StopIteration; or no elements if error
""" |
if not page:
page = 1
while True:
results = fn(*args, page=page, **kwargs)
if not results:
break
for x in results:
yield x
page += 1 |
<SYSTEM_TASK:>
Set the subsequent API calls to the user provided
<END_TASK>
<USER_TASK:>
Description:
def setsudo(self, user=None):
"""
Set the subsequent API calls to the user provided
:param user: User id or username to change to, None to return to the logged user
:return: Nothing
""" |
if user is None:
try:
self.headers.pop('SUDO')
except KeyError:
pass
else:
self.headers['SUDO'] = user |
<SYSTEM_TASK:>
Creates a new project owned by the authenticated user.
<END_TASK>
<USER_TASK:>
Description:
def createproject(self, name, **kwargs):
"""
Creates a new project owned by the authenticated user.
:param name: new project name
:param path: custom repository name for new project. By default generated based on name
:param namespace_id: namespace for the new project (defaults to user)
:param description: short project description
:param issues_enabled:
:param merge_requests_enabled:
:param wiki_enabled:
:param snippets_enabled:
:param public: if true same as setting visibility_level = 20
:param visibility_level:
:param sudo:
:param import_url:
:return:
""" |
data = {'name': name}
if kwargs:
data.update(kwargs)
request = requests.post(
self.projects_url, headers=self.headers, data=data,
verify=self.verify_ssl, auth=self.auth, timeout=self.timeout)
if request.status_code == 201:
return request.json()
elif request.status_code == 403:
if 'Your own projects limit is 0' in request.text:
print(request.text)
return False
else:
return False |
<SYSTEM_TASK:>
Edit an existing project.
<END_TASK>
<USER_TASK:>
Description:
def editproject(self, project_id, **kwargs):
"""
Edit an existing project.
:param name: new project name
:param path: custom repository name for new project. By default generated based on name
:param default_branch: they default branch
:param description: short project description
:param issues_enabled:
:param merge_requests_enabled:
:param wiki_enabled:
:param snippets_enabled:
:param public: if true same as setting visibility_level = 20
:param visibility_level:
:return:
""" |
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 |
<SYSTEM_TASK:>
Allow to share project with group.
<END_TASK>
<USER_TASK:>
Description:
def shareproject(self, project_id, group_id, group_access):
"""
Allow to share project with group.
:param project_id: The ID of a project
:param group_id: The ID of a group
:param group_access: Level of permissions for sharing
:return: True is success
""" |
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 |
<SYSTEM_TASK:>
Delete a project from the Gitlab server
<END_TASK>
<USER_TASK:>
Description:
def delete_project(self, id):
"""
Delete a project from the Gitlab server
Gitlab currently returns a Boolean True if the deleted and as such we return an
empty Dictionary
:param id: The ID of the project or NAMESPACE/PROJECT_NAME
:return: Dictionary
:raise: HttpError: If invalid response returned
""" |
url = '/projects/{id}'.format(id=id)
response = self.delete(url)
if response is True:
return {}
else:
return response |
<SYSTEM_TASK:>
Creates a new project owned by the specified user. Available only for admins.
<END_TASK>
<USER_TASK:>
Description:
def createprojectuser(self, user_id, name, **kwargs):
"""
Creates a new project owned by the specified user. Available only for admins.
:param user_id: user_id of owner
:param name: new project name
:param description: short project description
:param default_branch: 'master' by default
:param issues_enabled:
:param merge_requests_enabled:
:param wiki_enabled:
:param snippets_enabled:
:param public: if true same as setting visibility_level = 20
:param visibility_level:
:param import_url:
:param sudo:
:return:
""" |
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 |
<SYSTEM_TASK:>
Delete a project member
<END_TASK>
<USER_TASK:>
Description:
def deleteprojectmember(self, project_id, user_id):
"""Delete a project member
:param project_id: project id
:param user_id: user id
:return: always true
""" |
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 |
<SYSTEM_TASK:>
add a hook to a project
<END_TASK>
<USER_TASK:>
Description:
def addprojecthook(self, project_id, url, push=False, issues=False, merge_requests=False, tag_push=False):
"""
add a hook to a project
:param project_id: project id
:param url: url of the hook
:return: True if success
""" |
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 |
<SYSTEM_TASK:>
edit an existing hook from a project
<END_TASK>
<USER_TASK:>
Description:
def editprojecthook(self, project_id, hook_id, url, push=False, issues=False, merge_requests=False, tag_push=False):
"""
edit an existing hook from a project
:param id_: project id
:param hook_id: hook id
:param url: the new url
:return: True if success
""" |
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 |
<SYSTEM_TASK:>
Add a system hook
<END_TASK>
<USER_TASK:>
Description:
def addsystemhook(self, url):
"""
Add a system hook
:param url: url of the hook
:return: True if success
""" |
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 |
<SYSTEM_TASK:>
Create branch from commit SHA or existing branch
<END_TASK>
<USER_TASK:>
Description:
def createbranch(self, project_id, branch, ref):
"""
Create branch from commit SHA or existing branch
:param project_id: The ID of a project
:param branch: The name of the branch
:param ref: Create branch from commit SHA or existing branch
:return: True if success, False if not
""" |
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 |
<SYSTEM_TASK:>
Protect a branch from changes
<END_TASK>
<USER_TASK:>
Description:
def protectbranch(self, project_id, branch):
"""
Protect a branch from changes
:param project_id: project id
:param branch: branch id
:return: True if success
""" |
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 |
<SYSTEM_TASK:>
Create a fork relation.
<END_TASK>
<USER_TASK:>
Description:
def createforkrelation(self, project_id, from_project_id):
"""
Create a fork relation.
This DO NOT create a fork but only adds a link as fork the relation between 2 repositories
:param project_id: project id
:param from_project_id: from id
:return: true if success
""" |
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 |
<SYSTEM_TASK:>
Remove an existing fork relation. this DO NOT remove the fork,only the relation between them
<END_TASK>
<USER_TASK:>
Description:
def removeforkrelation(self, project_id):
"""
Remove an existing fork relation. this DO NOT remove the fork,only the relation between them
:param project_id: project id
:return: true if success
""" |
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 |
<SYSTEM_TASK:>
Forks a project into the user namespace of the authenticated user.
<END_TASK>
<USER_TASK:>
Description:
def createfork(self, project_id):
"""
Forks a project into the user namespace of the authenticated user.
:param project_id: Project ID to fork
:return: True if succeed
""" |
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 |
<SYSTEM_TASK:>
Create a new issue
<END_TASK>
<USER_TASK:>
Description:
def createissue(self, project_id, title, **kwargs):
"""
Create a new issue
:param project_id: project id
:param title: title of the issue
:return: dict with the issue created
""" |
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 |
<SYSTEM_TASK:>
Edit an existing issue data
<END_TASK>
<USER_TASK:>
Description:
def editissue(self, project_id, issue_id, **kwargs):
"""
Edit an existing issue data
:param project_id: project id
:param issue_id: issue id
:return: true if success
""" |
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 |
<SYSTEM_TASK:>
Enables a deploy key for a project.
<END_TASK>
<USER_TASK:>
Description:
def enable_deploy_key(self, project, key_id):
"""
Enables a deploy key for a project.
>>> gitlab = Gitlab(host='http://localhost:10080', verify_ssl=False)
>>> gitlab.login(user='root', password='5iveL!fe')
>>> gitlab.enable_deploy_key(15, 5)
:param project: The ID or URL-encoded path of the project owned by the authenticated user
:param key_id: The ID of the deploy key
:return: A dictionary containing deploy key details
:raise: HttpError: If invalid response returned
""" |
url = '/projects/{project}/deploy_keys/{key_id}/enable'.format(
project=project, key_id=key_id)
return self.post(url, default_response={}) |
<SYSTEM_TASK:>
Creates a new deploy key for a project.
<END_TASK>
<USER_TASK:>
Description:
def adddeploykey(self, project_id, title, key):
"""
Creates a new deploy key for a project.
:param project_id: project id
:param title: title of the key
:param key: the key itself
:return: true if success, false if not
""" |
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 |
<SYSTEM_TASK:>
Move a given project into a given group
<END_TASK>
<USER_TASK:>
Description:
def moveproject(self, group_id, project_id):
"""
Move a given project into a given group
:param group_id: ID of the destination group
:param project_id: ID of the project to be moved
:return: dict of the updated project
""" |
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 |
<SYSTEM_TASK:>
Get all the merge requests for a project.
<END_TASK>
<USER_TASK:>
Description:
def getmergerequests(self, project_id, page=1, per_page=20, state=None):
"""
Get all the merge requests for a project.
:param project_id: ID of the project to retrieve merge requests for
:param page: Page Number
:param per_page: Records per page
:param state: Passes merge request state to filter them by it
:return: list with all the merge requests
""" |
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 |
<SYSTEM_TASK:>
Get information about a specific merge request.
<END_TASK>
<USER_TASK:>
Description:
def getmergerequest(self, project_id, mergerequest_id):
"""
Get information about a specific merge request.
:param project_id: ID of the project
:param mergerequest_id: ID of the merge request
:return: dict of the merge request
""" |
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 |
<SYSTEM_TASK:>
Create a new merge request.
<END_TASK>
<USER_TASK:>
Description:
def createmergerequest(self, project_id, sourcebranch, targetbranch,
title, target_project_id=None, assignee_id=None):
"""
Create a new merge request.
:param project_id: ID of the project originating the merge request
:param sourcebranch: name of the branch to merge from
:param targetbranch: name of the branch to merge to
:param title: Title of the merge request
:param assignee_id: Assignee user ID
:return: dict of the new merge request
""" |
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 |
<SYSTEM_TASK:>
Update an existing merge request.
<END_TASK>
<USER_TASK:>
Description:
def acceptmergerequest(self, project_id, mergerequest_id, merge_commit_message=None):
"""
Update an existing merge request.
:param project_id: ID of the project originating the merge request
:param mergerequest_id: ID of the merge request to accept
:param merge_commit_message: Custom merge commit message
:return: dict of the modified merge request
""" |
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 |
<SYSTEM_TASK:>
Add a comment to a merge request.
<END_TASK>
<USER_TASK:>
Description:
def addcommenttomergerequest(self, project_id, mergerequest_id, note):
"""
Add a comment to a merge request.
:param project_id: ID of the project originating the merge request
:param mergerequest_id: ID of the merge request to comment on
:param note: Text of comment
:return: True if success
""" |
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 |
<SYSTEM_TASK:>
Creates an snippet
<END_TASK>
<USER_TASK:>
Description:
def createsnippet(self, project_id, title, file_name, code, visibility_level=0):
"""
Creates an snippet
:param project_id: project id to create the snippet under
:param title: title of the snippet
:param file_name: filename for the snippet
:param code: content of the snippet
:param visibility_level: snippets can be either private (0), internal(10) or public(20)
:return: True if correct, false if failed
""" |
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 |
<SYSTEM_TASK:>
Deletes a given snippet
<END_TASK>
<USER_TASK:>
Description:
def deletesnippet(self, project_id, snippet_id):
"""Deletes a given snippet
:param project_id: project_id
:param snippet_id: snippet id
:return: True if success
""" |
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 |
<SYSTEM_TASK:>
Unprotects a single project repository branch. This is an idempotent function,
<END_TASK>
<USER_TASK:>
Description:
def unprotectrepositorybranch(self, project_id, branch):
"""
Unprotects a single project repository branch. This is an idempotent function,
unprotecting an already unprotected repository branch still returns a 200 OK status code.
:param project_id: project id
:param branch: branch to unprotect
:return: dict with the 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 |
<SYSTEM_TASK:>
Creates new tag in the repository that points to the supplied ref
<END_TASK>
<USER_TASK:>
Description:
def createrepositorytag(self, project_id, tag_name, ref, message=None):
"""
Creates new tag in the repository that points to the supplied ref
:param project_id: project id
:param tag_name: tag
:param ref: sha1 of the commit or branch to tag
:param message: message
:return: dict
""" |
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 |
<SYSTEM_TASK:>
Deletes a tag of a repository with given name.
<END_TASK>
<USER_TASK:>
Description:
def delete_repository_tag(self, project_id, tag_name):
"""
Deletes a tag of a repository with given name.
:param project_id: The ID of a project
:param tag_name: The name of a tag
:return: Dictionary containing delete tag
:raise: HttpError: If invalid response returned
""" |
return self.delete('/projects/{project_id}/repository/tags/{tag_name}'.format(
project_id=project_id, tag_name=tag_name)) |
<SYSTEM_TASK:>
Adds an inline comment to a specific commit
<END_TASK>
<USER_TASK:>
Description:
def addcommenttocommit(self, project_id, author, sha, path, line, note):
"""
Adds an inline comment to a specific commit
:param project_id: project id
:param author: The author info as returned by create mergerequest
:param sha: The name of a repository branch or tag or if not given the default branch
:param path: The file path
:param line: The line number
:param note: Text of comment
:return: True or False
""" |
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 |
<SYSTEM_TASK:>
Get a list of repository files and directories in a project.
<END_TASK>
<USER_TASK:>
Description:
def getrepositorytree(self, project_id, **kwargs):
"""
Get a list of repository files and directories in a project.
:param project_id: The ID of a project
:param path: The path inside repository. Used to get contend of subdirectories
:param ref_name: The name of a repository branch or tag or if not given the default branch
:return: dict with the tree
""" |
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 |
<SYSTEM_TASK:>
Get the raw file contents for a file by commit SHA and path.
<END_TASK>
<USER_TASK:>
Description:
def getrawfile(self, project_id, sha1, filepath):
"""
Get the raw file contents for a file by commit SHA and path.
:param project_id: The ID of a project
:param sha1: The commit or branch name
:param filepath: The path the file
:return: raw file contents
""" |
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 |
<SYSTEM_TASK:>
Get the raw file contents for a blob by blob SHA.
<END_TASK>
<USER_TASK:>
Description:
def getrawblob(self, project_id, sha1):
"""
Get the raw file contents for a blob by blob SHA.
:param project_id: The ID of a project
:param sha1: the commit sha
:return: raw blob
""" |
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 |
<SYSTEM_TASK:>
Compare branches, tags or commits
<END_TASK>
<USER_TASK:>
Description:
def compare_branches_tags_commits(self, project_id, from_id, to_id):
"""
Compare branches, tags or commits
:param project_id: The ID of a project
:param from_id: the commit sha or branch name
:param to_id: the commit sha or branch name
:return: commit list and diff between two branches tags or commits provided by name
:raise: HttpError: If invalid response returned
""" |
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 |
<SYSTEM_TASK:>
Search for projects by name which are accessible to the authenticated user
<END_TASK>
<USER_TASK:>
Description:
def searchproject(self, search, page=1, per_page=20):
"""
Search for projects by name which are accessible to the authenticated user
:param search: Query to search for
:param page: Page number
:param per_page: Records per page
:return: list of results
""" |
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 |
<SYSTEM_TASK:>
Get an archive of the repository
<END_TASK>
<USER_TASK:>
Description:
def getfilearchive(self, project_id, filepath=None):
"""
Get an archive of the repository
:param project_id: project id
:param filepath: path to save the file to
:return: True if the file was saved to the filepath
""" |
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)
# TODO: Catch oserror exceptions as no permissions and such
# TODO: change the filepath to a path and keep always the filename?
return True
else:
msg = request.json()['message']
raise exceptions.HttpError(msg) |
<SYSTEM_TASK:>
Deletes an group by ID
<END_TASK>
<USER_TASK:>
Description:
def deletegroup(self, group_id):
"""
Deletes an group by ID
:param group_id: id of the group to delete
:return: True if it deleted, False if it couldn't. False could happen for several reasons, but there isn't a good way of differentiating them
""" |
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 |
<SYSTEM_TASK:>
Lists the members of a given group id
<END_TASK>
<USER_TASK:>
Description:
def getgroupmembers(self, group_id, page=1, per_page=20):
"""
Lists the members of a given group id
:param group_id: the group id
:param page: which page to return (default is 1)
:param per_page: number of items to return per page (default is 20)
:return: the group's members
""" |
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 |
<SYSTEM_TASK:>
Delete a group member
<END_TASK>
<USER_TASK:>
Description:
def deletegroupmember(self, group_id, user_id):
"""
Delete a group member
:param group_id: group id to remove the member from
:param user_id: user id
:return: always true
""" |
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 |
<SYSTEM_TASK:>
Add LDAP group link
<END_TASK>
<USER_TASK:>
Description:
def addldapgrouplink(self, group_id, cn, group_access, provider):
"""
Add LDAP group link
:param id: The ID of a group
:param cn: The CN of a LDAP group
:param group_access: Minimum access level for members of the LDAP group
:param provider: LDAP provider for the LDAP group (when using several providers)
:return: True if success
""" |
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 |
<SYSTEM_TASK:>
Create a new note
<END_TASK>
<USER_TASK:>
Description:
def createissuewallnote(self, project_id, issue_id, content):
"""Create a new note
:param project_id: Project ID
:param issue_id: Issue ID
:param content: Contents
:return: Json or False
""" |
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 |
<SYSTEM_TASK:>
Creates a new file in the repository
<END_TASK>
<USER_TASK:>
Description:
def createfile(self, project_id, file_path, branch_name, encoding, content, commit_message):
"""
Creates a new file in the repository
:param project_id: project id
:param file_path: Full path to new file. Ex. lib/class.rb
:param branch_name: The name of branch
:param content: File content
:param commit_message: Commit message
:return: true if success, false if not
""" |
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 |
<SYSTEM_TASK:>
Updates an existing file in the repository
<END_TASK>
<USER_TASK:>
Description:
def updatefile(self, project_id, file_path, branch_name, content, commit_message):
"""
Updates an existing file in the repository
:param project_id: project id
:param file_path: Full path to new file. Ex. lib/class.rb
:param branch_name: The name of branch
:param content: File content
:param commit_message: Commit message
:return: true if success, false if not
""" |
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 |
<SYSTEM_TASK:>
Allows you to receive information about file in repository like name, size, content.
<END_TASK>
<USER_TASK:>
Description:
def getfile(self, project_id, file_path, ref):
"""
Allows you to receive information about file in repository like name, size, content.
Note that file content is Base64 encoded.
:param project_id: project_id
:param file_path: Full path to file. Ex. lib/class.rb
:param ref: The name of branch, tag or commit
:return:
""" |
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 |
<SYSTEM_TASK:>
Deletes existing file in the repository
<END_TASK>
<USER_TASK:>
Description:
def deletefile(self, project_id, file_path, branch_name, commit_message):
"""
Deletes existing file in the repository
:param project_id: project id
:param file_path: Full path to new file. Ex. lib/class.rb
:param branch_name: The name of branch
:param commit_message: Commit message
:return: true if success, false if not
""" |
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 |
<SYSTEM_TASK:>
Set GitLab CI service for project
<END_TASK>
<USER_TASK:>
Description:
def setgitlabciservice(self, project_id, token, project_url):
"""
Set GitLab CI service for project
:param project_id: project id
:param token: CI project token
:param project_url: CI project url
:return: true if success, false if not
""" |
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 |
<SYSTEM_TASK:>
Delete GitLab CI service settings
<END_TASK>
<USER_TASK:>
Description:
def deletegitlabciservice(self, project_id, token, project_url):
"""
Delete GitLab CI service settings
:param project_id: Project ID
:param token: Token
:param project_url: Project URL
:return: true if success, false if not
""" |
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 |
<SYSTEM_TASK:>
Creates a new label for given repository with given name and color.
<END_TASK>
<USER_TASK:>
Description:
def createlabel(self, project_id, name, color):
"""
Creates a new label for given repository with given name and color.
:param project_id: The ID of a project
:param name: The name of the label
:param color: Color of the label given in 6-digit hex notation with leading '#' sign (e.g. #FFAABB)
:return:
""" |
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 |
<SYSTEM_TASK:>
Deletes a label given by its name.
<END_TASK>
<USER_TASK:>
Description:
def deletelabel(self, project_id, name):
"""
Deletes a label given by its name.
:param project_id: The ID of a project
:param name: The name of the label
:return: True if succeed
""" |
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 |
<SYSTEM_TASK:>
Updates an existing label with new name or now color.
<END_TASK>
<USER_TASK:>
Description:
def editlabel(self, project_id, name, new_name=None, color=None):
"""
Updates an existing label with new name or now color.
At least one parameter is required, to update the label.
:param project_id: The ID of a project
:param name: The name of the label
:return: True if succeed
""" |
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 |
<SYSTEM_TASK:>
Return a namespace list
<END_TASK>
<USER_TASK:>
Description:
def getnamespaces(self, search=None, page=1, per_page=20):
"""
Return a namespace list
:param search: Optional search query
:param page: Which page to return (default is 1)
:param per_page: Number of items to return per page (default is 20)
:return: returns a list of namespaces, false if there is an error
""" |
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 |
<SYSTEM_TASK:>
Goes up the mro and looks for the specified field.
<END_TASK>
<USER_TASK:>
Description:
def get_field_mro(cls, field_name):
"""Goes up the mro and looks for the specified field.""" |
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 |
<SYSTEM_TASK:>
Create internal connection to AMQP service.
<END_TASK>
<USER_TASK:>
Description:
def connect(self):
"""
Create internal connection to AMQP service.
""" |
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) |
<SYSTEM_TASK:>
Close internal connection to AMQP if connected.
<END_TASK>
<USER_TASK:>
Description:
def close(self):
"""
Close internal connection to AMQP if connected.
""" |
if self.connection:
logging.info("Closing connection to {}.".format(self.host))
self.connection.close()
self.connection = None |
<SYSTEM_TASK:>
Processes incoming WorkRequest messages one at a time via functions specified by add_command.
<END_TASK>
<USER_TASK:>
Description:
def process_messages_loop(self):
"""
Processes incoming WorkRequest messages one at a time via functions specified by add_command.
""" |
self.receiving_messages = True
try:
self.process_messages_loop_internal()
except pika.exceptions.ConnectionClosed as ex:
logging.error("Connection closed {}.".format(ex))
raise |
<SYSTEM_TASK:>
Busy loop that processes incoming WorkRequest messages via functions specified by add_command.
<END_TASK>
<USER_TASK:>
Description:
def process_messages_loop_internal(self):
"""
Busy loop that processes incoming WorkRequest messages via functions specified by add_command.
Terminates if a command runs shutdown method
""" |
logging.info("Starting work queue loop.")
self.connection.receive_loop_with_callback(self.queue_name, self.process_message) |
<SYSTEM_TASK:>
Busy loop that processes incoming WorkRequest messages via functions specified by add_command.
<END_TASK>
<USER_TASK:>
Description:
def process_messages_loop_internal(self):
"""
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
""" |
while self.receiving_messages:
# connect to AMQP server and listen for 1 message then disconnect
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() |
<SYSTEM_TASK:>
Save message body and close connection
<END_TASK>
<USER_TASK:>
Description:
def save_work_request_and_close(self, ch, method, properties, body):
"""
Save message body and close connection
""" |
self.work_request = pickle.loads(body)
ch.basic_ack(delivery_tag=method.delivery_tag)
ch.stop_consuming()
self.connection.close() |
<SYSTEM_TASK:>
Gets latest related galleries from same section as originating gallery.
<END_TASK>
<USER_TASK:>
Description:
def get_related_galleries(gallery, count=5):
"""
Gets latest related galleries from same section as originating gallery.
Count defaults to five but can be overridden.
Usage: {% get_related_galleries gallery <10> %}
""" |
# just get the first cat. If they assigned to more than one, tough
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} |
<SYSTEM_TASK:>
Loads healthchecks.
<END_TASK>
<USER_TASK:>
Description:
def load_healthchecks(self):
"""
Loads healthchecks.
""" |
self.load_default_healthchecks()
if getattr(settings, 'AUTODISCOVER_HEALTHCHECKS', True):
self.autodiscover_healthchecks()
self._registry_loaded = True |
<SYSTEM_TASK:>
Loads healthchecks specified in settings.HEALTHCHECKS as dotted import
<END_TASK>
<USER_TASK:>
Description:
def load_default_healthchecks(self):
"""
Loads healthchecks specified in settings.HEALTHCHECKS as dotted import
paths to the classes. Defaults are listed in `DEFAULT_HEALTHCHECKS`.
""" |
default_healthchecks = getattr(settings, 'HEALTHCHECKS', DEFAULT_HEALTHCHECKS)
for healthcheck in default_healthchecks:
healthcheck = import_string(healthcheck)
self.register_healthcheck(healthcheck) |
<SYSTEM_TASK:>
Runs all registered healthchecks and returns a list of
<END_TASK>
<USER_TASK:>
Description:
def run_healthchecks(self):
"""
Runs all registered healthchecks and returns a list of
HealthcheckResponse.
""" |
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 |
<SYSTEM_TASK:>
Advance the time reference by the given amount.
<END_TASK>
<USER_TASK:>
Description:
def advance_by(self, amount):
"""Advance the time reference by the given amount.
:param `float` amount: number of seconds to advance.
:raise `ValueError`: if *amount* is negative.
""" |
if amount < 0:
raise ValueError("cannot retreat time reference: amount {} < 0"
.format(amount))
self.__delta += amount |
<SYSTEM_TASK:>
Advance the time reference so that now is the given timestamp.
<END_TASK>
<USER_TASK:>
Description:
def advance_to(self, timestamp):
"""Advance the time reference so that now is the given timestamp.
:param `float` timestamp: the new current timestamp.
:raise `ValueError`: if *timestamp* is in the past.
""" |
now = self.__original_time()
if timestamp < now:
raise ValueError("cannot retreat time reference: "
"target {} < now {}"
.format(timestamp, now))
self.__delta = timestamp - now |
<SYSTEM_TASK:>
Resets all stored frequencies for the cache
<END_TASK>
<USER_TASK:>
Description:
def reset_frequencies(self, frequency=0):
"""Resets all stored frequencies for the cache
:keyword int frequency: Frequency to reset to, must be >= 0""" |
frequency = max(frequency, 0)
for key in self._store.keys():
self._store[key] = (self._store[key][0], frequency)
return frequency |
<SYSTEM_TASK:>
Gets key, value pair for oldest item in cache
<END_TASK>
<USER_TASK:>
Description:
def oldest(self):
"""
Gets key, value pair for oldest item in cache
:returns: tuple
""" |
if len(self._store) == 0:
return
kv = min(self._store.items(), key=lambda x: x[1][1])
return kv[0], kv[1][0] |
<SYSTEM_TASK:>
Validate the structure of Swagger schemas against the spec.
<END_TASK>
<USER_TASK:>
Description:
def validate_swagger_schema(schema_dir, resource_listing):
"""Validate the structure of Swagger schemas against the spec.
**Valid only for Swagger v1.2 spec**
Note: It is possible that resource_listing is not present in
the schema_dir. The path is passed in the call so that ssv
can fetch the api-declaration files from the path.
:param resource_listing: Swagger Spec v1.2 resource listing
:type resource_listing: dict
:param schema_dir: A path to Swagger spec directory
:type schema_dir: string
:raises: :py:class:`swagger_spec_validator.SwaggerValidationError`
""" |
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))),
) |
<SYSTEM_TASK:>
Turn a swagger endpoint schema into an equivalent one to validate our
<END_TASK>
<USER_TASK:>
Description:
def build_param_schema(schema, param_type):
"""Turn a swagger endpoint schema into an equivalent one to validate our
request.
As an example, this would take this swagger schema:
{
"paramType": "query",
"name": "query",
"description": "Location to query",
"type": "string",
"required": true
}
To this jsonschema:
{
"type": "object",
"additionalProperties": "False",
"properties:": {
"description": "Location to query",
"type": "string",
"required": true
}
}
Which we can then validate against a JSON object we construct from the
pyramid request.
""" |
properties = filter_params_by_type(schema, param_type)
if not properties:
return
# Generate a jsonschema that describes the set of all query parameters. We
# can then validate this against dict(request.params).
return {
'type': 'object',
'properties': dict((p['name'], p) for p in properties),
# Allow extra headers. Most HTTP requests will have headers which
# are outside the scope of the spec (like `Host`, or `User-Agent`)
'additionalProperties': param_type == 'header',
} |
<SYSTEM_TASK:>
Swagger 1.2 expects `required` to be a bool in the Parameter object, but
<END_TASK>
<USER_TASK:>
Description:
def required_validator(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.
""" |
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) |
<SYSTEM_TASK:>
Prepare the api specification for request and response validation.
<END_TASK>
<USER_TASK:>
Description:
def load_schema(schema_path):
"""Prepare the api specification for request and response validation.
:returns: a mapping from :class:`RequestMatcher` to :class:`ValidatorMap`
for every operation in the api specification.
:rtype: dict
""" |
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) |
<SYSTEM_TASK:>
Returns appropriate swagger handler and swagger spec schema.
<END_TASK>
<USER_TASK:>
Description:
def get_swagger_objects(settings, route_info, registry):
"""Returns appropriate swagger handler and swagger spec schema.
Swagger Handler contains callables that isolate implementation differences
in the tween to handle both Swagger 1.2 and Swagger 2.0.
Exception is made when `settings.prefer_20_routes` are non-empty and
['1.2', '2.0'] both are present in available swagger versions. In this
special scenario, '2.0' spec is chosen only for requests which are listed
in the `prefer_20_routes`. This helps in incremental migration of
routes from v1.2 to v2.0 by making moving to v2.0 opt-in.
:rtype: (:class:`SwaggerHandler`,
:class:`pyramid_swagger.model.SwaggerSchema` OR
:class:`bravado_core.spec.Spec`)
""" |
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 |
<SYSTEM_TASK:>
Pyramid tween for performing validation.
<END_TASK>
<USER_TASK:>
Description:
def validation_tween_factory(handler, registry):
"""Pyramid tween for performing validation.
Note this is very simple -- it validates requests, responses, and paths
while delegating to the relevant matching view.
""" |
settings = load_settings(registry)
route_mapper = registry.queryUtility(IRoutesMapper)
validation_context = _get_validation_context(registry)
def validator_tween(request):
# We don't have access to this yet but let's go ahead and build the
# matchdict so we can validate it and use it to exclude routes from
# validation.
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 |
<SYSTEM_TASK:>
Validate the request against the swagger spec and return a dict with
<END_TASK>
<USER_TASK:>
Description:
def handle_request(request, validator_map, **kwargs):
"""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.
:param request: a :class:`PyramidSwaggerRequest` to validate
:param validator_map: a :class:`pyramid_swagger.load_schema.ValidatorMap`
used to validate the request
:returns: a :class:`dict` of request data for each parameter in the swagger
spec
:raises: RequestValidationError when the request is not valid for the
swagger spec
""" |
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)
# Body is a special case because the key for the request_data comes
# from the name in the schema, instead of keys in the 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 |
<SYSTEM_TASK:>
Builds a swagger12 handler or returns None if no schema is present.
<END_TASK>
<USER_TASK:>
Description:
def build_swagger12_handler(schema):
"""Builds a swagger12 handler or returns None if no schema is present.
:type schema: :class:`pyramid_swagger.model.SwaggerSchema`
:rtype: :class:`SwaggerHandler` or None
""" |
if schema:
return SwaggerHandler(
op_for_request=schema.validators_for_request,
handle_request=handle_request,
handle_response=validate_response,
) |
<SYSTEM_TASK:>
Validates response against our schemas.
<END_TASK>
<USER_TASK:>
Description:
def validate_response(response, validator_map):
"""Validates response against our schemas.
:param response: the response object to validate
:type response: :class:`pyramid.response.Response`
:type validator_map: :class:`pyramid_swagger.load_schema.ValidatorMap`
""" |
validator = validator_map.response
# Short circuit if we are supposed to not validate anything.
returns_nothing = validator.schema.get('type') == 'void'
body_empty = response.body in (None, b'', b'{}', b'null')
if returns_nothing and body_empty:
return
# Don't attempt to validate non-success responses in v1.2
if not 200 <= response.status_code <= 203:
return
validator.validate(prepare_body(response)) |
<SYSTEM_TASK:>
Delegate handling the Swagger concerns of the response to bravado-core.
<END_TASK>
<USER_TASK:>
Description:
def swaggerize_response(response, op):
"""
Delegate handling the Swagger concerns of the response to bravado-core.
:type response: :class:`pyramid.response.Response`
:type op: :class:`bravado_core.operation.Operation`
""" |
response_spec = get_response_spec(response.status_int, op)
bravado_core.response.validate_response(
response_spec, op, PyramidSwaggerResponse(response)) |
<SYSTEM_TASK:>
Find out which operation in the Swagger schema corresponds to the given
<END_TASK>
<USER_TASK:>
Description:
def get_op_for_request(request, route_info, spec):
"""
Find out which operation in the Swagger schema corresponds to the given
pyramid request.
:type request: :class:`pyramid.request.Request`
:type route_info: dict (usually has 'match' and 'route' keys)
:type spec: :class:`bravado_core.spec.Spec`
:rtype: :class:`bravado_core.operation.Operation`
:raises: PathNotMatchedError when a matching Swagger operation is not
found.
""" |
# pyramid.urldispath.Route
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)) |
<SYSTEM_TASK:>
Validates and returns the versions of the Swagger Spec that this pyramid
<END_TASK>
<USER_TASK:>
Description:
def get_swagger_versions(settings):
"""
Validates and returns the versions of the Swagger Spec that this pyramid
application supports.
:type settings: dict
:return: list of strings. eg ['1.2', '2.0']
:raises: ValueError when an unsupported Swagger version is encountered.
""" |
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 |
<SYSTEM_TASK:>
Create and register pyramid endpoints to service swagger api docs.
<END_TASK>
<USER_TASK:>
Description:
def register_api_doc_endpoints(config, endpoints, base_path='/api-docs'):
"""Create and register pyramid endpoints to service swagger api docs.
Routes and views will be registered on the `config` at `path`.
:param config: a pyramid configuration to register the new views and routes
:type config: :class:`pyramid.config.Configurator`
:param endpoints: a list of endpoints to register as routes and views
:type endpoints: a list of :class:`pyramid_swagger.model.PyramidEndpoint`
:param base_path: the base path used to register api doc endpoints.
Defaults to `/api-docs`.
:type base_path: string
""" |
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) |
<SYSTEM_TASK:>
Thanks to the magic of closures, this means we gracefully return JSON
<END_TASK>
<USER_TASK:>
Description:
def build_swagger_12_api_declaration_view(api_declaration_json):
"""Thanks to the magic of closures, this means we gracefully return JSON
without file IO at request time.
""" |
def view_for_api_declaration(request):
# Note that we rewrite basePath to always point at this server's root.
return dict(
api_declaration_json,
basePath=str(request.application_url),
)
return view_for_api_declaration |
<SYSTEM_TASK:>
Validates if path1 and path2 matches, ignoring any kwargs in the string.
<END_TASK>
<USER_TASK:>
Description:
def partial_path_match(path1, path2, kwarg_re=r'\{.*\}'):
"""Validates if path1 and path2 matches, ignoring any kwargs in the string.
We need this to ensure we can match Swagger patterns like:
/foo/{id}
against the observed pyramid path
/foo/1
:param path1: path of a url
:type path1: string
:param path2: path of a url
:type path2: string
:param kwarg_re: regex pattern to identify kwargs
:type kwarg_re: regex string
:returns: boolean
""" |
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 |
<SYSTEM_TASK:>
Takes a request and returns a validator mapping for the request.
<END_TASK>
<USER_TASK:>
Description:
def validators_for_request(self, request, **kwargs):
"""Takes a request and returns a validator mapping for the request.
:param request: A Pyramid request to fetch schemas for
:type request: :class:`pyramid.request.Request`
:returns: a :class:`pyramid_swagger.load_schema.ValidatorMap` which can
be used to validate `request`
""" |
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)
) |
<SYSTEM_TASK:>
Discovers schema file locations and relations.
<END_TASK>
<USER_TASK:>
Description:
def build_schema_mapping(schema_dir, resource_listing):
"""Discovers schema file locations and relations.
:param schema_dir: the directory schema files live inside
:type schema_dir: string
:param resource_listing: A swagger resource listing
:type resource_listing: dict
:returns: a mapping from resource name to file path
:rtype: dict
""" |
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)
) |
<SYSTEM_TASK:>
Load the resource listing from file, handling errors.
<END_TASK>
<USER_TASK:>
Description:
def _load_resource_listing(resource_listing):
"""Load the resource listing from file, handling errors.
:param resource_listing: path to the api-docs resource listing file
:type resource_listing: string
:returns: contents of the resource listing file
:rtype: dict
""" |
try:
with open(resource_listing) as resource_listing_file:
return simplejson.load(resource_listing_file)
# If not found, raise a more user-friendly error.
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)
) |
<SYSTEM_TASK:>
Return the resource listing document.
<END_TASK>
<USER_TASK:>
Description:
def get_resource_listing(schema_dir, should_generate_resource_listing):
"""Return the resource listing document.
:param schema_dir: the directory which contains swagger spec files
:type schema_dir: string
:param should_generate_resource_listing: when True a resource listing will
be generated from the list of *.json files in the schema_dir. Otherwise
return the contents of the resource listing file
:type should_generate_resource_listing: boolean
:returns: the contents of a resource listing document
""" |
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) |
<SYSTEM_TASK:>
Build a SwaggerSchema from various files.
<END_TASK>
<USER_TASK:>
Description:
def compile_swagger_schema(schema_dir, resource_listing):
"""Build a SwaggerSchema from various files.
:param schema_dir: the directory schema files live inside
:type schema_dir: string
:returns: a SwaggerSchema object
""" |
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) |
<SYSTEM_TASK:>
Create a configuration dict for bravado_core based on pyramid_swagger
<END_TASK>
<USER_TASK:>
Description:
def create_bravado_core_config(settings):
"""Create a configuration dict for bravado_core based on pyramid_swagger
settings.
:param settings: pyramid registry settings with configuration for
building a swagger schema
:type settings: dict
:returns: config dict suitable for passing into
bravado_core.spec.Spec.from_dict(..)
:rtype: dict
""" |
# Map pyramid_swagger config key -> bravado_core config key
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 |
<SYSTEM_TASK:>
Consume the Swagger schemas and produce a queryable datastructure.
<END_TASK>
<USER_TASK:>
Description:
def ingest_resources(mapping, schema_dir):
"""Consume the Swagger schemas and produce a queryable datastructure.
:param mapping: Map from resource name to filepath of its api declaration
:type mapping: dict
:param schema_dir: the directory schema files live inside
:type schema_dir: string
:returns: A list of mapping from :class:`RequestMatcher` to
:class:`ValidatorMap`
""" |
ingested_resources = []
for name, filepath in iteritems(mapping):
try:
ingested_resources.append(load_schema(filepath))
# If we have trouble reading any files, raise a more user-friendly
# error.
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 |
<SYSTEM_TASK:>
Directly return a numpy array for a given variable name
<END_TASK>
<USER_TASK:>
Description:
def read_array(self, infile, var_name):
"""Directly return a numpy array for a given variable name""" |
file_handle = self.read_cdf(infile)
try:
# return the data array
return file_handle.variables[var_name][:]
except KeyError:
print("Cannot find variable: {0}".format(var_name))
raise KeyError |
<SYSTEM_TASK:>
Create a masked array based on cdf's FillValue
<END_TASK>
<USER_TASK:>
Description:
def read_ma_array(self, infile, var_name):
"""Create a masked array based on cdf's FillValue""" |
file_obj = self.read_cdf(infile)
# .data is not backwards compatible to old scipy versions, [:] is
data = file_obj.variables[var_name][:]
# load numpy if available
try:
import numpy as np
except Exception:
raise ImportError("numpy is required to return masked arrays.")
if hasattr(file_obj.variables[var_name], "_FillValue"):
# return masked array
fill_val = file_obj.variables[var_name]._FillValue
retval = np.ma.masked_where(data == fill_val, data)
else:
# generate dummy mask which is always valid
retval = np.ma.array(data)
return retval |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.