_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q260400 | ProfitBricksService.create_server | validation | def create_server(self, datacenter_id, server):
"""
Creates a server within the data center.
:param datacenter_id: The unique ID of the data center.
:type datacenter_id: ``str``
:param server: A dict of the server to be created.
:type server: ``dict``
"""
data = json.dumps(self._create_server_dict(server))
response = self._perform_request(
url='/datacenters/%s/servers' % (datacenter_id),
method='POST',
data=data)
return response | python | {
"resource": ""
} |
q260401 | ProfitBricksService.update_server | validation | def update_server(self, datacenter_id, server_id, **kwargs):
"""
Updates a server with the parameters provided.
:param datacenter_id: The unique ID of the data center.
:type datacenter_id: ``str``
:param server_id: The unique ID of the server.
:type server_id: ``str``
"""
data = {}
for attr, value in kwargs.items():
if attr == 'boot_volume':
boot_volume_properties = {
"id": value
}
boot_volume_entities = {
"bootVolume": boot_volume_properties
}
data.update(boot_volume_entities)
else:
data[self._underscore_to_camelcase(attr)] = value
response = self._perform_request(
url='/datacenters/%s/servers/%s' % (
datacenter_id,
server_id),
method='PATCH',
data=json.dumps(data))
return response | python | {
"resource": ""
} |
q260402 | ProfitBricksService.get_attached_volumes | validation | def get_attached_volumes(self, datacenter_id, server_id, depth=1):
"""
Retrieves a list of volumes attached to the server.
:param datacenter_id: The unique ID of the data center.
:type datacenter_id: ``str``
:param server_id: The unique ID of the server.
:type server_id: ``str``
:param depth: The depth of the response data.
:type depth: ``int``
"""
response = self._perform_request(
'/datacenters/%s/servers/%s/volumes?depth=%s' % (
datacenter_id,
server_id,
str(depth)))
return response | python | {
"resource": ""
} |
q260403 | ProfitBricksService.get_attached_volume | validation | def get_attached_volume(self, datacenter_id, server_id, volume_id):
"""
Retrieves volume information.
:param datacenter_id: The unique ID of the data center.
:type datacenter_id: ``str``
:param server_id: The unique ID of the server.
:type server_id: ``str``
:param volume_id: The unique ID of the volume.
:type volume_id: ``str``
"""
response = self._perform_request(
'/datacenters/%s/servers/%s/volumes/%s' % (
datacenter_id,
server_id,
volume_id))
return response | python | {
"resource": ""
} |
q260404 | ProfitBricksService.attach_volume | validation | def attach_volume(self, datacenter_id, server_id, volume_id):
"""
Attaches a volume to a server.
:param datacenter_id: The unique ID of the data center.
:type datacenter_id: ``str``
:param server_id: The unique ID of the server.
:type server_id: ``str``
:param volume_id: The unique ID of the volume.
:type volume_id: ``str``
"""
data = '{ "id": "' + volume_id + '" }'
response = self._perform_request(
url='/datacenters/%s/servers/%s/volumes' % (
datacenter_id,
server_id),
method='POST',
data=data)
return response | python | {
"resource": ""
} |
q260405 | ProfitBricksService.get_attached_cdroms | validation | def get_attached_cdroms(self, datacenter_id, server_id, depth=1):
"""
Retrieves a list of CDROMs attached to the server.
:param datacenter_id: The unique ID of the data center.
:type datacenter_id: ``str``
:param server_id: The unique ID of the server.
:type server_id: ``str``
:param depth: The depth of the response data.
:type depth: ``int``
"""
response = self._perform_request(
'/datacenters/%s/servers/%s/cdroms?depth=%s' % (
datacenter_id,
server_id,
str(depth)))
return response | python | {
"resource": ""
} |
q260406 | ProfitBricksService.get_attached_cdrom | validation | def get_attached_cdrom(self, datacenter_id, server_id, cdrom_id):
"""
Retrieves an attached CDROM.
:param datacenter_id: The unique ID of the data center.
:type datacenter_id: ``str``
:param server_id: The unique ID of the server.
:type server_id: ``str``
:param cdrom_id: The unique ID of the CDROM.
:type cdrom_id: ``str``
"""
response = self._perform_request(
'/datacenters/%s/servers/%s/cdroms/%s' % (
datacenter_id,
server_id,
cdrom_id))
return response | python | {
"resource": ""
} |
q260407 | ProfitBricksService.attach_cdrom | validation | def attach_cdrom(self, datacenter_id, server_id, cdrom_id):
"""
Attaches a CDROM to a server.
:param datacenter_id: The unique ID of the data center.
:type datacenter_id: ``str``
:param server_id: The unique ID of the server.
:type server_id: ``str``
:param cdrom_id: The unique ID of the CDROM.
:type cdrom_id: ``str``
"""
data = '{ "id": "' + cdrom_id + '" }'
response = self._perform_request(
url='/datacenters/%s/servers/%s/cdroms' % (
datacenter_id,
server_id),
method='POST',
data=data)
return response | python | {
"resource": ""
} |
q260408 | ProfitBricksService.start_server | validation | def start_server(self, datacenter_id, server_id):
"""
Starts the server.
:param datacenter_id: The unique ID of the data center.
:type datacenter_id: ``str``
:param server_id: The unique ID of the server.
:type server_id: ``str``
"""
response = self._perform_request(
url='/datacenters/%s/servers/%s/start' % (
datacenter_id,
server_id),
method='POST-ACTION')
return response | python | {
"resource": ""
} |
q260409 | ProfitBricksService.stop_server | validation | def stop_server(self, datacenter_id, server_id):
"""
Stops the server.
:param datacenter_id: The unique ID of the data center.
:type datacenter_id: ``str``
:param server_id: The unique ID of the server.
:type server_id: ``str``
"""
response = self._perform_request(
url='/datacenters/%s/servers/%s/stop' % (
datacenter_id,
server_id),
method='POST-ACTION')
return response | python | {
"resource": ""
} |
q260410 | ProfitBricksService.reboot_server | validation | def reboot_server(self, datacenter_id, server_id):
"""
Reboots the server.
:param datacenter_id: The unique ID of the data center.
:type datacenter_id: ``str``
:param server_id: The unique ID of the server.
:type server_id: ``str``
"""
response = self._perform_request(
url='/datacenters/%s/servers/%s/reboot' % (
datacenter_id,
server_id),
method='POST-ACTION')
return response | python | {
"resource": ""
} |
q260411 | ProfitBricksService.create_snapshot | validation | def create_snapshot(self, datacenter_id, volume_id,
name=None, description=None):
"""
Creates a snapshot of the specified volume.
:param datacenter_id: The unique ID of the data center.
:type datacenter_id: ``str``
:param volume_id: The unique ID of the volume.
:type volume_id: ``str``
:param name: The name given to the volume.
:type name: ``str``
:param description: The description given to the volume.
:type description: ``str``
"""
data = {'name': name, 'description': description}
response = self._perform_request(
'/datacenters/%s/volumes/%s/create-snapshot' % (
datacenter_id, volume_id),
method='POST-ACTION-JSON',
data=urlencode(data))
return response | python | {
"resource": ""
} |
q260412 | ProfitBricksService.restore_snapshot | validation | def restore_snapshot(self, datacenter_id, volume_id, snapshot_id):
"""
Restores a snapshot to the specified volume.
:param datacenter_id: The unique ID of the data center.
:type datacenter_id: ``str``
:param volume_id: The unique ID of the volume.
:type volume_id: ``str``
:param snapshot_id: The unique ID of the snapshot.
:type snapshot_id: ``str``
"""
data = {'snapshotId': snapshot_id}
response = self._perform_request(
url='/datacenters/%s/volumes/%s/restore-snapshot' % (
datacenter_id,
volume_id),
method='POST-ACTION',
data=urlencode(data))
return response | python | {
"resource": ""
} |
q260413 | ProfitBricksService.remove_snapshot | validation | def remove_snapshot(self, snapshot_id):
"""
Removes a snapshot.
:param snapshot_id: The ID of the snapshot
you wish to remove.
:type snapshot_id: ``str``
"""
response = self._perform_request(
url='/snapshots/' + snapshot_id, method='DELETE')
return response | python | {
"resource": ""
} |
q260414 | ProfitBricksService.get_group | validation | def get_group(self, group_id, depth=1):
"""
Retrieves a single group by ID.
:param group_id: The unique ID of the group.
:type group_id: ``str``
:param depth: The depth of the response data.
:type depth: ``int``
"""
response = self._perform_request(
'/um/groups/%s?depth=%s' % (group_id, str(depth)))
return response | python | {
"resource": ""
} |
q260415 | ProfitBricksService.create_group | validation | def create_group(self, group):
"""
Creates a new group and set group privileges.
:param group: The group object to be created.
:type group: ``dict``
"""
data = json.dumps(self._create_group_dict(group))
response = self._perform_request(
url='/um/groups',
method='POST',
data=data)
return response | python | {
"resource": ""
} |
q260416 | ProfitBricksService.update_group | validation | def update_group(self, group_id, **kwargs):
"""
Updates a group.
:param group_id: The unique ID of the group.
:type group_id: ``str``
"""
properties = {}
# make the key camel-case transformable
if 'create_datacenter' in kwargs:
kwargs['create_data_center'] = kwargs.pop('create_datacenter')
for attr, value in kwargs.items():
properties[self._underscore_to_camelcase(attr)] = value
data = {
"properties": properties
}
response = self._perform_request(
url='/um/groups/%s' % group_id,
method='PUT',
data=json.dumps(data))
return response | python | {
"resource": ""
} |
q260417 | ProfitBricksService.delete_group | validation | def delete_group(self, group_id):
"""
Removes a group.
:param group_id: The unique ID of the group.
:type group_id: ``str``
"""
response = self._perform_request(
url='/um/groups/%s' % group_id,
method='DELETE')
return response | python | {
"resource": ""
} |
q260418 | ProfitBricksService.list_shares | validation | def list_shares(self, group_id, depth=1):
"""
Retrieves a list of all shares though a group.
:param group_id: The unique ID of the group.
:type group_id: ``str``
:param depth: The depth of the response data.
:type depth: ``int``
"""
response = self._perform_request(
'/um/groups/%s/shares?depth=%s' % (group_id, str(depth)))
return response | python | {
"resource": ""
} |
q260419 | ProfitBricksService.get_share | validation | def get_share(self, group_id, resource_id, depth=1):
"""
Retrieves a specific resource share available to a group.
:param group_id: The unique ID of the group.
:type group_id: ``str``
:param resource_id: The unique ID of the resource.
:type resource_id: ``str``
:param depth: The depth of the response data.
:type depth: ``int``
"""
response = self._perform_request(
'/um/groups/%s/shares/%s?depth=%s'
% (group_id, resource_id, str(depth)))
return response | python | {
"resource": ""
} |
q260420 | ProfitBricksService.add_share | validation | def add_share(self, group_id, resource_id, **kwargs):
"""
Shares a resource through a group.
:param group_id: The unique ID of the group.
:type group_id: ``str``
:param resource_id: The unique ID of the resource.
:type resource_id: ``str``
"""
properties = {}
for attr, value in kwargs.items():
properties[self._underscore_to_camelcase(attr)] = value
data = {
"properties": properties
}
response = self._perform_request(
url='/um/groups/%s/shares/%s' % (group_id, resource_id),
method='POST',
data=json.dumps(data))
return response | python | {
"resource": ""
} |
q260421 | ProfitBricksService.delete_share | validation | def delete_share(self, group_id, resource_id):
"""
Removes a resource share from a group.
:param group_id: The unique ID of the group.
:type group_id: ``str``
:param resource_id: The unique ID of the resource.
:type resource_id: ``str``
"""
response = self._perform_request(
url='/um/groups/%s/shares/%s' % (group_id, resource_id),
method='DELETE')
return response | python | {
"resource": ""
} |
q260422 | ProfitBricksService.get_user | validation | def get_user(self, user_id, depth=1):
"""
Retrieves a single user by ID.
:param user_id: The unique ID of the user.
:type user_id: ``str``
:param depth: The depth of the response data.
:type depth: ``int``
"""
response = self._perform_request(
'/um/users/%s?depth=%s' % (user_id, str(depth)))
return response | python | {
"resource": ""
} |
q260423 | ProfitBricksService.create_user | validation | def create_user(self, user):
"""
Creates a new user.
:param user: The user object to be created.
:type user: ``dict``
"""
data = self._create_user_dict(user=user)
response = self._perform_request(
url='/um/users',
method='POST',
data=json.dumps(data))
return response | python | {
"resource": ""
} |
q260424 | ProfitBricksService.update_user | validation | def update_user(self, user_id, **kwargs):
"""
Updates a user.
:param user_id: The unique ID of the user.
:type user_id: ``str``
"""
properties = {}
for attr, value in kwargs.items():
properties[self._underscore_to_camelcase(attr)] = value
data = {
"properties": properties
}
response = self._perform_request(
url='/um/users/%s' % user_id,
method='PUT',
data=json.dumps(data))
return response | python | {
"resource": ""
} |
q260425 | ProfitBricksService.delete_user | validation | def delete_user(self, user_id):
"""
Removes a user.
:param user_id: The unique ID of the user.
:type user_id: ``str``
"""
response = self._perform_request(
url='/um/users/%s' % user_id,
method='DELETE')
return response | python | {
"resource": ""
} |
q260426 | ProfitBricksService.list_group_users | validation | def list_group_users(self, group_id, depth=1):
"""
Retrieves a list of all users that are members of a particular group.
:param group_id: The unique ID of the group.
:type group_id: ``str``
:param depth: The depth of the response data.
:type depth: ``int``
"""
response = self._perform_request(
'/um/groups/%s/users?depth=%s' % (group_id, str(depth)))
return response | python | {
"resource": ""
} |
q260427 | ProfitBricksService.add_group_user | validation | def add_group_user(self, group_id, user_id):
"""
Adds an existing user to a group.
:param group_id: The unique ID of the group.
:type group_id: ``str``
:param user_id: The unique ID of the user.
:type user_id: ``str``
"""
data = {
"id": user_id
}
response = self._perform_request(
url='/um/groups/%s/users' % group_id,
method='POST',
data=json.dumps(data))
return response | python | {
"resource": ""
} |
q260428 | ProfitBricksService.remove_group_user | validation | def remove_group_user(self, group_id, user_id):
"""
Removes a user from a group.
:param group_id: The unique ID of the group.
:type group_id: ``str``
:param user_id: The unique ID of the user.
:type user_id: ``str``
"""
response = self._perform_request(
url='/um/groups/%s/users/%s' % (group_id, user_id),
method='DELETE')
return response | python | {
"resource": ""
} |
q260429 | ProfitBricksService.list_resources | validation | def list_resources(self, resource_type=None, depth=1):
"""
Retrieves a list of all resources.
:param resource_type: The resource type: datacenter, image,
snapshot or ipblock. Default is None,
i.e., all resources are listed.
:type resource_type: ``str``
:param depth: The depth of the response data.
:type depth: ``int``
"""
if resource_type is not None:
response = self._perform_request(
'/um/resources/%s?depth=%s' % (resource_type, str(depth)))
else:
response = self._perform_request(
'/um/resources?depth=' + str(depth))
return response | python | {
"resource": ""
} |
q260430 | ProfitBricksService.get_resource | validation | def get_resource(self, resource_type, resource_id, depth=1):
"""
Retrieves a single resource of a particular type.
:param resource_type: The resource type: datacenter, image,
snapshot or ipblock.
:type resource_type: ``str``
:param resource_id: The unique ID of the resource.
:type resource_id: ``str``
:param depth: The depth of the response data.
:type depth: ``int``
"""
response = self._perform_request(
'/um/resources/%s/%s?depth=%s' % (
resource_type, resource_id, str(depth)))
return response | python | {
"resource": ""
} |
q260431 | ProfitBricksService.get_volume | validation | def get_volume(self, datacenter_id, volume_id):
"""
Retrieves a single volume by ID.
:param datacenter_id: The unique ID of the data center.
:type datacenter_id: ``str``
:param volume_id: The unique ID of the volume.
:type volume_id: ``str``
"""
response = self._perform_request(
'/datacenters/%s/volumes/%s' % (datacenter_id, volume_id))
return response | python | {
"resource": ""
} |
q260432 | ProfitBricksService.list_volumes | validation | def list_volumes(self, datacenter_id, depth=1):
"""
Retrieves a list of volumes in the data center.
:param datacenter_id: The unique ID of the data center.
:type datacenter_id: ``str``
:param depth: The depth of the response data.
:type depth: ``int``
"""
response = self._perform_request(
'/datacenters/%s/volumes?depth=%s' % (datacenter_id, str(depth)))
return response | python | {
"resource": ""
} |
q260433 | ProfitBricksService.delete_volume | validation | def delete_volume(self, datacenter_id, volume_id):
"""
Removes a volume from the data center.
:param datacenter_id: The unique ID of the data center.
:type datacenter_id: ``str``
:param volume_id: The unique ID of the volume.
:type volume_id: ``str``
"""
response = self._perform_request(
url='/datacenters/%s/volumes/%s' % (
datacenter_id, volume_id), method='DELETE')
return response | python | {
"resource": ""
} |
q260434 | ProfitBricksService.create_volume | validation | def create_volume(self, datacenter_id, volume):
"""
Creates a volume within the specified data center.
:param datacenter_id: The unique ID of the data center.
:type datacenter_id: ``str``
:param volume: A volume dict.
:type volume: ``dict``
"""
data = (json.dumps(self._create_volume_dict(volume)))
response = self._perform_request(
url='/datacenters/%s/volumes' % datacenter_id,
method='POST',
data=data)
return response | python | {
"resource": ""
} |
q260435 | ProfitBricksService.wait_for_completion | validation | def wait_for_completion(self, response, timeout=3600, initial_wait=5, scaleup=10):
"""
Poll resource request status until resource is provisioned.
:param response: A response dict, which needs to have a 'requestId' item.
:type response: ``dict``
:param timeout: Maximum waiting time in seconds. None means infinite waiting time.
:type timeout: ``int``
:param initial_wait: Initial polling interval in seconds.
:type initial_wait: ``int``
:param scaleup: Double polling interval every scaleup steps, which will be doubled.
:type scaleup: ``int``
"""
if not response:
return
logger = logging.getLogger(__name__)
wait_period = initial_wait
next_increase = time.time() + wait_period * scaleup
if timeout:
timeout = time.time() + timeout
while True:
request = self.get_request(request_id=response['requestId'], status=True)
if request['metadata']['status'] == 'DONE':
break
elif request['metadata']['status'] == 'FAILED':
raise PBFailedRequest(
'Request {0} failed to complete: {1}'.format(
response['requestId'], request['metadata']['message']),
response['requestId']
)
current_time = time.time()
if timeout and current_time > timeout:
raise PBTimeoutError('Timed out waiting for request {0}.'.format(
response['requestId']), response['requestId'])
if current_time > next_increase:
wait_period *= 2
next_increase = time.time() + wait_period * scaleup
scaleup *= 2
logger.info("Request %s is in state '%s'. Sleeping for %i seconds...",
response['requestId'], request['metadata']['status'], wait_period)
time.sleep(wait_period) | python | {
"resource": ""
} |
q260436 | ProfitBricksService._b | validation | def _b(s, encoding='utf-8'):
"""
Returns the given string as a string of bytes. That means in
Python2 as a str object, and in Python3 as a bytes object.
Raises a TypeError, if it cannot be converted.
"""
if six.PY2:
# This is Python2
if isinstance(s, str):
return s
elif isinstance(s, unicode): # noqa, pylint: disable=undefined-variable
return s.encode(encoding)
else:
# And this is Python3
if isinstance(s, bytes):
return s
elif isinstance(s, str):
return s.encode(encoding)
raise TypeError("Invalid argument %r for _b()" % (s,)) | python | {
"resource": ""
} |
q260437 | ProfitBricksService._underscore_to_camelcase | validation | def _underscore_to_camelcase(value):
"""
Convert Python snake case back to mixed case.
"""
def camelcase():
yield str.lower
while True:
yield str.capitalize
c = camelcase()
return "".join(next(c)(x) if x else '_' for x in value.split("_")) | python | {
"resource": ""
} |
q260438 | find_item_by_name | validation | def find_item_by_name(list_, namegetter, name):
"""
Find a item a given list by a matching name.
The search for the name is done in this relaxing way:
- exact name match
- case-insentive name match
- attribute starts with the name
- attribute starts with the name (case insensitive)
- name appears in the attribute
- name appears in the attribute (case insensitive)
:param list_: A list of elements
:type list_: ``list``
:param namegetter: Function that returns the name for a given
element in the list
:type namegetter: ``function``
:param name: Name to search for
:type name: ``str``
"""
matching_items = [i for i in list_ if namegetter(i) == name]
if not matching_items:
prog = re.compile(re.escape(name) + '$', re.IGNORECASE)
matching_items = [i for i in list_ if prog.match(namegetter(i))]
if not matching_items:
prog = re.compile(re.escape(name))
matching_items = [i for i in list_ if prog.match(namegetter(i))]
if not matching_items:
prog = re.compile(re.escape(name), re.IGNORECASE)
matching_items = [i for i in list_ if prog.match(namegetter(i))]
if not matching_items:
prog = re.compile(re.escape(name))
matching_items = [i for i in list_ if prog.search(namegetter(i))]
if not matching_items:
prog = re.compile(re.escape(name), re.IGNORECASE)
matching_items = [i for i in list_ if prog.search(namegetter(i))]
return matching_items | python | {
"resource": ""
} |
q260439 | getServerInfo | validation | def getServerInfo(pbclient=None, dc_id=None):
''' gets info of servers of a data center'''
if pbclient is None:
raise ValueError("argument 'pbclient' must not be None")
if dc_id is None:
raise ValueError("argument 'dc_id' must not be None")
# list of all found server's info
server_info = []
# depth 1 is enough for props/meta
servers = pbclient.list_servers(dc_id, 1)
for server in servers['items']:
props = server['properties']
info = dict(id=server['id'], name=props['name'],
state=server['metadata']['state'],
vmstate=props['vmState'])
server_info.append(info)
# end for(servers)
return server_info | python | {
"resource": ""
} |
q260440 | getServerStates | validation | def getServerStates(pbclient=None, dc_id=None, serverid=None, servername=None):
''' gets states of a server'''
if pbclient is None:
raise ValueError("argument 'pbclient' must not be None")
if dc_id is None:
raise ValueError("argument 'dc_id' must not be None")
server = None
if serverid is None:
if servername is None:
raise ValueError("one of 'serverid' or 'servername' must be specified")
# so, arg.servername is set (to whatever)
server_info = select_where(getServerInfo(pbclient, dc_id),
['id', 'name', 'state', 'vmstate'],
name=servername)
if len(server_info) > 1:
raise NameError("ambiguous server name '{}'".format(servername))
if len(server_info) == 1:
server = server_info[0]
else:
# get by ID may also fail if it's removed
# in this case, catch exception (message 404) and be quiet for a while
# unfortunately this has changed from Py2 to Py3
try:
server_info = pbclient.get_server(dc_id, serverid, 1)
server = dict(id=server_info['id'],
name=server_info['properties']['name'],
state=server_info['metadata']['state'],
vmstate=server_info['properties']['vmState'])
except Exception:
ex = sys.exc_info()[1]
if ex.args[0] is not None and ex.args[0] == 404:
print("Server w/ ID {} not found".format(serverid))
server = None
else:
raise ex
# end try/except
# end if/else(serverid)
return server | python | {
"resource": ""
} |
q260441 | get_self | validation | def get_self(session, user_details=None):
"""
Get details about the currently authenticated user
"""
# Set compact to true
if user_details:
user_details['compact'] = True
response = make_get_request(session, 'self', params_data=user_details)
json_data = response.json()
if response.status_code == 200:
return json_data['result']
else:
raise SelfNotRetrievedException(
message=json_data['message'],
error_code=json_data['error_code'],
request_id=json_data['request_id']
) | python | {
"resource": ""
} |
q260442 | get_user_by_id | validation | def get_user_by_id(session, user_id, user_details=None):
"""
Get details about specific user
"""
if user_details:
user_details['compact'] = True
response = make_get_request(
session, 'users/{}'.format(user_id), params_data=user_details)
json_data = response.json()
if response.status_code == 200:
return json_data['result']
else:
raise UserNotFoundException(
message=json_data['message'],
error_code=json_data['error_code'],
request_id=json_data['request_id']
) | python | {
"resource": ""
} |
q260443 | get_self_user_id | validation | def get_self_user_id(session):
"""
Get the currently authenticated user ID
"""
response = make_get_request(session, 'self')
if response.status_code == 200:
return response.json()['result']['id']
else:
raise UserIdNotRetrievedException(
'Error retrieving user id: %s' % response.text, response.text) | python | {
"resource": ""
} |
q260444 | add_user_jobs | validation | def add_user_jobs(session, job_ids):
"""
Add a list of jobs to the currently authenticated user
"""
jobs_data = {
'jobs[]': job_ids
}
response = make_post_request(session, 'self/jobs', json_data=jobs_data)
json_data = response.json()
if response.status_code == 200:
return json_data['status']
else:
raise UserJobsNotAddedException(
message=json_data['message'],
error_code=json_data['error_code'],
request_id=json_data['request_id']) | python | {
"resource": ""
} |
q260445 | set_user_jobs | validation | def set_user_jobs(session, job_ids):
"""
Replace the currently authenticated user's list of jobs with a new list of
jobs
"""
jobs_data = {
'jobs[]': job_ids
}
response = make_put_request(session, 'self/jobs', json_data=jobs_data)
json_data = response.json()
if response.status_code == 200:
return json_data['status']
else:
raise UserJobsNotSetException(
message=json_data['message'],
error_code=json_data['error_code'],
request_id=json_data['request_id']) | python | {
"resource": ""
} |
q260446 | delete_user_jobs | validation | def delete_user_jobs(session, job_ids):
"""
Remove a list of jobs from the currently authenticated user
"""
jobs_data = {
'jobs[]': job_ids
}
response = make_delete_request(session, 'self/jobs', json_data=jobs_data)
json_data = response.json()
if response.status_code == 200:
return json_data['status']
else:
raise UserJobsNotDeletedException(
message=json_data['message'],
error_code=json_data['error_code'],
request_id=json_data['request_id']) | python | {
"resource": ""
} |
q260447 | get_users | validation | def get_users(session, query):
"""
Get one or more users
"""
# GET /api/users/0.1/users
response = make_get_request(session, 'users', params_data=query)
json_data = response.json()
if response.status_code == 200:
return json_data['result']
else:
raise UsersNotFoundException(
message=json_data['message'],
error_code=json_data['error_code'],
request_id=json_data['request_id']) | python | {
"resource": ""
} |
q260448 | create_project | validation | def create_project(session, title, description,
currency, budget, jobs):
"""
Create a project
"""
project_data = {'title': title,
'description': description,
'currency': currency,
'budget': budget,
'jobs': jobs
}
# POST /api/projects/0.1/projects/
response = make_post_request(session, 'projects', json_data=project_data)
json_data = response.json()
if response.status_code == 200:
project_data = json_data['result']
p = Project(project_data)
p.url = urljoin(session.url, 'projects/%s' % p.seo_url)
return p
else:
raise ProjectNotCreatedException(message=json_data['message'],
error_code=json_data['error_code'],
request_id=json_data['request_id'],
) | python | {
"resource": ""
} |
q260449 | create_hireme_project | validation | def create_hireme_project(session, title, description,
currency, budget, jobs, hireme_initial_bid):
"""
Create a fixed project
"""
jobs.append(create_job_object(id=417)) # Hire Me job, required
project_data = {'title': title,
'description': description,
'currency': currency,
'budget': budget,
'jobs': jobs,
'hireme': True,
'hireme_initial_bid': hireme_initial_bid
}
# POST /api/projects/0.1/projects/
response = make_post_request(session, 'projects', json_data=project_data)
json_data = response.json()
if response.status_code == 200:
project_data = json_data['result']
p = Project(project_data)
p.url = urljoin(session.url, 'projects/%s' % p.seo_url)
return p
else:
raise ProjectNotCreatedException(message=json_data['message'],
error_code=json_data['error_code'],
request_id=json_data['request_id'],
) | python | {
"resource": ""
} |
q260450 | get_projects | validation | def get_projects(session, query):
"""
Get one or more projects
"""
# GET /api/projects/0.1/projects
response = make_get_request(session, 'projects', params_data=query)
json_data = response.json()
if response.status_code == 200:
return json_data['result']
else:
raise ProjectsNotFoundException(
message=json_data['message'],
error_code=json_data['error_code'],
request_id=json_data['request_id']) | python | {
"resource": ""
} |
q260451 | get_project_by_id | validation | def get_project_by_id(session, project_id, project_details=None, user_details=None):
"""
Get a single project by ID
"""
# GET /api/projects/0.1/projects/<int:project_id>
query = {}
if project_details:
query.update(project_details)
if user_details:
query.update(user_details)
response = make_get_request(
session, 'projects/{}'.format(project_id), params_data=query)
json_data = response.json()
if response.status_code == 200:
return json_data['result']
else:
raise ProjectsNotFoundException(
message=json_data['message'],
error_code=json_data['error_code'],
request_id=json_data['request_id']
) | python | {
"resource": ""
} |
q260452 | search_projects | validation | def search_projects(session,
query,
search_filter=None,
project_details=None,
user_details=None,
limit=10,
offset=0,
active_only=None):
"""
Search for all projects
"""
search_data = {
'query': query,
'limit': limit,
'offset': offset,
}
if search_filter:
search_data.update(search_filter)
if project_details:
search_data.update(project_details)
if user_details:
search_data.update(user_details)
# GET /api/projects/0.1/projects/all/
# GET /api/projects/0.1/projects/active/
endpoint = 'projects/{}'.format('active' if active_only else 'all')
response = make_get_request(session, endpoint, params_data=search_data)
json_data = response.json()
if response.status_code == 200:
return json_data['result']
else:
raise ProjectsNotFoundException(
message=json_data['message'],
error_code=json_data['error_code'],
request_id=json_data['request_id']) | python | {
"resource": ""
} |
q260453 | place_project_bid | validation | def place_project_bid(session, project_id, bidder_id, description, amount,
period, milestone_percentage):
"""
Place a bid on a project
"""
bid_data = {
'project_id': project_id,
'bidder_id': bidder_id,
'description': description,
'amount': amount,
'period': period,
'milestone_percentage': milestone_percentage,
}
# POST /api/projects/0.1/bids/
response = make_post_request(session, 'bids', json_data=bid_data)
json_data = response.json()
if response.status_code == 200:
bid_data = json_data['result']
return Bid(bid_data)
else:
raise BidNotPlacedException(message=json_data['message'],
error_code=json_data['error_code'],
request_id=json_data['request_id']) | python | {
"resource": ""
} |
q260454 | get_bids | validation | def get_bids(session, project_ids=[], bid_ids=[], limit=10, offset=0):
"""
Get the list of bids
"""
get_bids_data = {}
if bid_ids:
get_bids_data['bids[]'] = bid_ids
if project_ids:
get_bids_data['projects[]'] = project_ids
get_bids_data['limit'] = limit
get_bids_data['offset'] = offset
# GET /api/projects/0.1/bids/
response = make_get_request(session, 'bids', params_data=get_bids_data)
json_data = response.json()
if response.status_code == 200:
return json_data['result']
else:
raise BidsNotFoundException(
message=json_data['message'], error_code=json_data['error_code'],
request_id=json_data['request_id']
) | python | {
"resource": ""
} |
q260455 | get_milestones | validation | def get_milestones(session, project_ids=[], milestone_ids=[], user_details=None, limit=10, offset=0):
"""
Get the list of milestones
"""
get_milestones_data = {}
if milestone_ids:
get_milestones_data['milestones[]'] = milestone_ids
if project_ids:
get_milestones_data['projects[]'] = project_ids
get_milestones_data['limit'] = limit
get_milestones_data['offset'] = offset
# Add projections if they exist
if user_details:
get_milestones_data.update(user_details)
# GET /api/projects/0.1/milestones/
response = make_get_request(
session, 'milestones', params_data=get_milestones_data)
json_data = response.json()
if response.status_code == 200:
return json_data['result']
else:
raise MilestonesNotFoundException(
message=json_data['message'],
error_code=json_data['error_code'],
request_id=json_data['request_id']
) | python | {
"resource": ""
} |
q260456 | get_milestone_by_id | validation | def get_milestone_by_id(session, milestone_id, user_details=None):
"""
Get a specific milestone
"""
# GET /api/projects/0.1/milestones/{milestone_id}/
endpoint = 'milestones/{}'.format(milestone_id)
response = make_get_request(session, endpoint, params_data=user_details)
json_data = response.json()
if response.status_code == 200:
return json_data['result']
else:
raise MilestonesNotFoundException(
message=json_data['message'],
error_code=json_data['error_code'],
request_id=json_data['request_id']
) | python | {
"resource": ""
} |
q260457 | award_project_bid | validation | def award_project_bid(session, bid_id):
"""
Award a bid on a project
"""
headers = {
'Content-Type': 'application/x-www-form-urlencoded'
}
bid_data = {
'action': 'award'
}
# POST /api/projects/0.1/bids/{bid_id}/?action=award
endpoint = 'bids/{}'.format(bid_id)
response = make_put_request(session, endpoint, headers=headers,
params_data=bid_data)
json_data = response.json()
if response.status_code == 200:
return json_data['status']
else:
json_data = response.json()
raise BidNotAwardedException(
message=json_data['message'],
error_code=json_data['error_code'],
request_id=json_data['request_id']
) | python | {
"resource": ""
} |
q260458 | revoke_project_bid | validation | def revoke_project_bid(session, bid_id):
"""
Revoke a bid on a project
"""
headers = {
'Content-Type': 'application/x-www-form-urlencoded'
}
bid_data = {
'action': 'revoke'
}
# POST /api/projects/0.1/bids/{bid_id}/?action=revoke
endpoint = 'bids/{}'.format(bid_id)
response = make_put_request(session, endpoint, headers=headers,
params_data=bid_data)
json_data = response.json()
if response.status_code == 200:
return json_data['status']
else:
json_data = response.json()
raise BidNotRevokedException(message=json_data['message'],
error_code=json_data['error_code'],
request_id=json_data['request_id']) | python | {
"resource": ""
} |
q260459 | accept_project_bid | validation | def accept_project_bid(session, bid_id):
"""
Accept a bid on a project
"""
headers = {
'Content-Type': 'application/x-www-form-urlencoded'
}
bid_data = {
'action': 'accept'
}
# POST /api/projects/0.1/bids/{bid_id}/?action=revoke
endpoint = 'bids/{}'.format(bid_id)
response = make_put_request(session, endpoint, headers=headers,
params_data=bid_data)
json_data = response.json()
if response.status_code == 200:
return json_data['status']
else:
json_data = response.json()
raise BidNotAcceptedException(message=json_data['message'],
error_code=json_data['error_code'],
request_id=json_data['request_id']) | python | {
"resource": ""
} |
q260460 | retract_project_bid | validation | def retract_project_bid(session, bid_id):
"""
Retract a bid on a project
"""
headers = {
'Content-Type': 'application/x-www-form-urlencoded'
}
bid_data = {
'action': 'retract'
}
# POST /api/projects/0.1/bids/{bid_id}/?action=revoke
endpoint = 'bids/{}'.format(bid_id)
response = make_put_request(session, endpoint, headers=headers,
params_data=bid_data)
json_data = response.json()
if response.status_code == 200:
return json_data['status']
else:
json_data = response.json()
raise BidNotRetractedException(message=json_data['message'],
error_code=json_data['error_code'],
request_id=json_data['request_id']) | python | {
"resource": ""
} |
q260461 | highlight_project_bid | validation | def highlight_project_bid(session, bid_id):
"""
Highlight a bid on a project
"""
headers = {
'Content-Type': 'application/x-www-form-urlencoded'
}
bid_data = {
'action': 'highlight'
}
# POST /api/projects/0.1/bids/{bid_id}/?action=revoke
endpoint = 'bids/{}'.format(bid_id)
response = make_put_request(session, endpoint, headers=headers,
params_data=bid_data)
json_data = response.json()
if response.status_code == 200:
return json_data['status']
else:
json_data = response.json()
raise BidNotHighlightedException(message=json_data['message'],
error_code=json_data['error_code'],
request_id=json_data['request_id']) | python | {
"resource": ""
} |
q260462 | create_milestone_payment | validation | def create_milestone_payment(session, project_id, bidder_id, amount,
reason, description):
"""
Create a milestone payment
"""
milestone_data = {
'project_id': project_id,
'bidder_id': bidder_id,
'amount': amount,
'reason': reason,
'description': description
}
# POST /api/projects/0.1/milestones/
response = make_post_request(session, 'milestones',
json_data=milestone_data)
json_data = response.json()
if response.status_code == 200:
milestone_data = json_data['result']
return Milestone(milestone_data)
else:
raise MilestoneNotCreatedException(message=json_data['message'],
error_code=json_data['error_code'],
request_id=json_data['request_id']) | python | {
"resource": ""
} |
q260463 | post_track | validation | def post_track(session, user_id, project_id, latitude, longitude):
"""
Start tracking a project by creating a track
"""
tracking_data = {
'user_id': user_id,
'project_id': project_id,
'track_point': {
'latitude': latitude,
'longitude': longitude
}
}
# POST /api/projects/0.1/tracks/
response = make_post_request(session, 'tracks',
json_data=tracking_data)
json_data = response.json()
if response.status_code == 200:
return json_data['result']
else:
raise TrackNotCreatedException(message=json_data['message'],
error_code=json_data['error_code'],
request_id=json_data['request_id']) | python | {
"resource": ""
} |
q260464 | update_track | validation | def update_track(session, track_id, latitude, longitude, stop_tracking=False):
"""
Updates the current location by creating a new track point and appending
it to the given track
"""
tracking_data = {
'track_point': {
'latitude': latitude,
'longitude': longitude,
},
'stop_tracking': stop_tracking
}
# PUT /api/projects/0.1/tracks/{track_id}/
response = make_put_request(session, 'tracks/{}'.format(track_id),
json_data=tracking_data)
json_data = response.json()
if response.status_code == 200:
return json_data['result']
else:
raise TrackNotUpdatedException(message=json_data['message'],
error_code=json_data['error_code'],
request_id=json_data['request_id']) | python | {
"resource": ""
} |
q260465 | get_track_by_id | validation | def get_track_by_id(session, track_id, track_point_limit=None, track_point_offset=None):
"""
Gets a specific track
"""
tracking_data = {}
if track_point_limit:
tracking_data['track_point_limit'] = track_point_limit
if track_point_offset:
tracking_data['track_point_offset'] = track_point_offset
# GET /api/projects/0.1/tracks/{track_id}/
response = make_get_request(session, 'tracks/{}'.format(track_id),
params_data=tracking_data)
json_data = response.json()
if response.status_code == 200:
return json_data['result']
else:
raise TrackNotFoundException(message=json_data['message'],
error_code=json_data['error_code'],
request_id=json_data['request_id']) | python | {
"resource": ""
} |
q260466 | create_milestone_request | validation | def create_milestone_request(session, project_id, bid_id, description, amount):
"""
Create a milestone request
"""
milestone_request_data = {
'project_id': project_id,
'bid_id': bid_id,
'description': description,
'amount': amount,
}
# POST /api/projects/0.1/milestone_requests/
response = make_post_request(session, 'milestone_requests',
json_data=milestone_request_data)
json_data = response.json()
if response.status_code == 200:
milestone_request_data = json_data['result']
return MilestoneRequest(milestone_request_data)
else:
raise MilestoneRequestNotCreatedException(
message=json_data['message'],
error_code=json_data['error_code'],
request_id=json_data['request_id']) | python | {
"resource": ""
} |
q260467 | accept_milestone_request | validation | def accept_milestone_request(session, milestone_request_id):
"""
Accept a milestone request
"""
params_data = {
'action': 'accept',
}
# POST /api/projects/0.1/milestone_requests/{milestone_request_id}/?action=
# accept
endpoint = 'milestone_requests/{}'.format(milestone_request_id)
response = make_put_request(session, endpoint, params_data=params_data)
json_data = response.json()
if response.status_code == 200:
return json_data['status']
else:
raise MilestoneRequestNotAcceptedException(
message=json_data['message'],
error_code=json_data['error_code'],
request_id=json_data['request_id']) | python | {
"resource": ""
} |
q260468 | reject_milestone_request | validation | def reject_milestone_request(session, milestone_request_id):
"""
Reject a milestone request
"""
params_data = {
'action': 'reject',
}
# POST /api/projects/0.1/milestone_requests/{milestone_request_id}/?action=
# reject
endpoint = 'milestone_requests/{}'.format(milestone_request_id)
response = make_put_request(session, endpoint, params_data=params_data)
json_data = response.json()
if response.status_code == 200:
return json_data['status']
else:
raise MilestoneRequestNotRejectedException(
message=json_data['message'],
error_code=json_data['error_code'],
request_id=json_data['request_id']) | python | {
"resource": ""
} |
q260469 | delete_milestone_request | validation | def delete_milestone_request(session, milestone_request_id):
"""
Delete a milestone request
"""
params_data = {
'action': 'delete',
}
# POST /api/projects/0.1/milestone_requests/{milestone_request_id}/?action=
# delete
endpoint = 'milestone_requests/{}'.format(milestone_request_id)
response = make_put_request(session, endpoint, params_data=params_data)
json_data = response.json()
if response.status_code == 200:
return json_data['status']
else:
raise MilestoneRequestNotDeletedException(
message=json_data['message'],
error_code=json_data['error_code'],
request_id=json_data['request_id']) | python | {
"resource": ""
} |
q260470 | post_review | validation | def post_review(session, review):
"""
Post a review
"""
# POST /api/projects/0.1/reviews/
response = make_post_request(session, 'reviews', json_data=review)
json_data = response.json()
if response.status_code == 200:
return json_data['status']
else:
raise ReviewNotPostedException(
message=json_data['message'],
error_code=json_data['error_code'],
request_id=json_data['request_id']) | python | {
"resource": ""
} |
q260471 | get_jobs | validation | def get_jobs(session, job_ids, seo_details, lang):
"""
Get a list of jobs
"""
get_jobs_data = {
'jobs[]': job_ids,
'seo_details': seo_details,
'lang': lang,
}
# GET /api/projects/0.1/jobs/
response = make_get_request(session, 'jobs', params_data=get_jobs_data)
json_data = response.json()
if response.status_code == 200:
return json_data['result']
else:
raise JobsNotFoundException(
message=json_data['message'],
error_code=json_data['error_code'],
request_id=json_data['request_id']) | python | {
"resource": ""
} |
q260472 | create_thread | validation | def create_thread(session, member_ids, context_type, context, message):
"""
Create a thread
"""
headers = {
'Content-Type': 'application/x-www-form-urlencoded'
}
thread_data = {
'members[]': member_ids,
'context_type': context_type,
'context': context,
'message': message,
}
# POST /api/messages/0.1/threads/
response = make_post_request(session, 'threads', headers,
form_data=thread_data)
json_data = response.json()
if response.status_code == 200:
return Thread(json_data['result'])
else:
raise ThreadNotCreatedException(message=json_data['message'],
error_code=json_data['error_code'],
request_id=json_data['request_id']) | python | {
"resource": ""
} |
q260473 | create_project_thread | validation | def create_project_thread(session, member_ids, project_id, message):
"""
Create a project thread
"""
return create_thread(session, member_ids, 'project', project_id, message) | python | {
"resource": ""
} |
q260474 | get_messages | validation | def get_messages(session, query, limit=10, offset=0):
"""
Get one or more messages
"""
query['limit'] = limit
query['offset'] = offset
# GET /api/messages/0.1/messages
response = make_get_request(session, 'messages', params_data=query)
json_data = response.json()
if response.status_code == 200:
return json_data['result']
else:
raise MessagesNotFoundException(
message=json_data['message'],
error_code=json_data['error_code'],
request_id=json_data['request_id']
) | python | {
"resource": ""
} |
q260475 | search_messages | validation | def search_messages(session, thread_id, query, limit=20,
offset=0, message_context_details=None,
window_above=None, window_below=None):
"""
Search for messages
"""
query = {
'thread_id': thread_id,
'query': query,
'limit': limit,
'offset': offset
}
if message_context_details:
query['message_context_details'] = message_context_details
if window_above:
query['window_above'] = window_above
if window_below:
query['window_below'] = window_below
# GET /api/messages/0.1/messages/search
response = make_get_request(session, 'messages/search', params_data=query)
json_data = response.json()
if response.status_code == 200:
return json_data['result']
else:
raise MessagesNotFoundException(
message=json_data['message'],
error_code=json_data['error_code'],
request_id=json_data['request_id']
) | python | {
"resource": ""
} |
q260476 | get_threads | validation | def get_threads(session, query):
"""
Get one or more threads
"""
# GET /api/messages/0.1/threads
response = make_get_request(session, 'threads', params_data=query)
json_data = response.json()
if response.status_code == 200:
return json_data['result']
else:
raise ThreadsNotFoundException(
message=json_data['message'],
error_code=json_data['error_code'],
request_id=json_data['request_id']
) | python | {
"resource": ""
} |
q260477 | _clean | validation | def _clean(zipcode, valid_length=_valid_zipcode_length):
""" Assumes zipcode is of type `str` """
zipcode = zipcode.split("-")[0] # Convert #####-#### to #####
if len(zipcode) != valid_length:
raise ValueError(
'Invalid format, zipcode must be of the format: "#####" or "#####-####"'
)
if _contains_nondigits(zipcode):
raise ValueError('Invalid characters, zipcode may only contain digits and "-".')
return zipcode | python | {
"resource": ""
} |
q260478 | similar_to | validation | def similar_to(partial_zipcode, zips=_zips):
""" List of zipcode dicts where zipcode prefix matches `partial_zipcode` """
return [z for z in zips if z["zip_code"].startswith(partial_zipcode)] | python | {
"resource": ""
} |
q260479 | filter_by | validation | def filter_by(zips=_zips, **kwargs):
""" Use `kwargs` to select for desired attributes from list of zipcode dicts """
return [z for z in zips if all([k in z and z[k] == v for k, v in kwargs.items()])] | python | {
"resource": ""
} |
q260480 | is_valid_identifier | validation | def is_valid_identifier(name):
"""Pedantic yet imperfect. Test to see if "name" is a valid python identifier
"""
if not isinstance(name, str):
return False
if '\n' in name:
return False
if name.strip() != name:
return False
try:
code = compile('\n{0}=None'.format(name), filename='<string>', mode='single')
exec(code)
return True
except SyntaxError:
return False | python | {
"resource": ""
} |
q260481 | PaletteEntry.from_config | validation | def from_config(
cls, cfg,
default_fg=DEFAULT_FG_16, default_bg=DEFAULT_BG_16,
default_fg_hi=DEFAULT_FG_256, default_bg_hi=DEFAULT_BG_256,
max_colors=2**24
):
"""
Build a palette definition from either a simple string or a dictionary,
filling in defaults for items not specified.
e.g.:
"dark green"
dark green foreground, black background
{lo: dark gray, hi: "#666"}
dark gray on 16-color terminals, #666 for 256+ color
"""
# TODO: mono
e = PaletteEntry(mono = default_fg,
foreground=default_fg,
background=default_bg,
foreground_high=default_fg_hi,
background_high=default_bg_hi)
if isinstance(cfg, str):
e.foreground_high = cfg
if e.allowed(cfg, 16):
e.foreground = cfg
else:
rgb = AttrSpec(fg=cfg, bg="", colors=max_colors).get_rgb_values()[0:3]
e.foreground = nearest_basic_color(rgb)
elif isinstance(cfg, dict):
bg = cfg.get("bg", None)
if isinstance(bg, str):
e.background_high = bg
if e.allowed(bg, 16):
e.background = bg
else:
rgb = AttrSpec(fg=bg, bg="", colors=max_colors).get_rgb_values()[0:3]
e.background = nearest_basic_color(rgb)
elif isinstance(bg, dict):
e.background_high = bg.get("hi", default_bg_hi)
if "lo" in bg:
if e.allowed(bg["lo"], 16):
e.background = bg["lo"]
else:
rgb = AttrSpec(fg=bg["lo"], bg="", colors=max_colors).get_rgb_values()[0:3]
e.background = nearest_basic_color(rgb)
fg = cfg.get("fg", cfg)
if isinstance(fg, str):
e.foreground_high = fg
if e.allowed(fg, 16):
e.foreground = fg
else:
rgb = AttrSpec(fg=fg, bg="", colors=max_colors).get_rgb_values()[0:3]
e.foreground = nearest_basic_color(rgb)
elif isinstance(fg, dict):
e.foreground_high = fg.get("hi", default_fg_hi)
if "lo" in fg:
if e.allowed(fg["lo"], 16):
e.foreground = fg["lo"]
else:
rgb = AttrSpec(fg=fg["lo"], bg="", colors=max_colors).get_rgb_values()[0:3]
e.foreground = nearest_basic_color(rgb)
return e | python | {
"resource": ""
} |
q260482 | migrate | validation | def migrate(src_path,
src_passphrase,
src_backend,
dst_path,
dst_passphrase,
dst_backend):
"""Migrate all keys in a source stash to a destination stash
The migration process will decrypt all keys using the source
stash's passphrase and then encrypt them based on the destination
stash's passphrase.
re-encryption will take place only if the passphrases are differing
"""
src_storage = STORAGE_MAPPING[src_backend](**_parse_path_string(src_path))
dst_storage = STORAGE_MAPPING[dst_backend](**_parse_path_string(dst_path))
src_stash = Stash(src_storage, src_passphrase)
dst_stash = Stash(dst_storage, dst_passphrase)
# TODO: Test that re-encryption does not occur on similar
# passphrases
keys = src_stash.export()
dst_stash.load(src_passphrase, keys=keys) | python | {
"resource": ""
} |
q260483 | generate_passphrase | validation | def generate_passphrase(size=12):
"""Return a generate string `size` long based on lowercase, uppercase,
and digit chars
"""
chars = string.ascii_lowercase + string.ascii_uppercase + string.digits
return str(''.join(random.choice(chars) for _ in range(size))) | python | {
"resource": ""
} |
q260484 | _build_dict_from_key_value | validation | def _build_dict_from_key_value(keys_and_values):
"""Return a dict from a list of key=value pairs
"""
key_dict = {}
for key_value in keys_and_values:
if '=' not in key_value:
raise GhostError('Pair {0} is not of `key=value` format'.format(
key_value))
key, value = key_value.split('=', 1)
key_dict.update({str(key): str(value)})
return key_dict | python | {
"resource": ""
} |
q260485 | _prettify_list | validation | def _prettify_list(items):
"""Return a human readable format of a list.
Example:
Available Keys:
- my_first_key
- my_second_key
"""
assert isinstance(items, list)
keys_list = 'Available Keys:'
for item in items:
keys_list += '\n - {0}'.format(item)
return keys_list | python | {
"resource": ""
} |
q260486 | init_stash | validation | def init_stash(stash_path, passphrase, passphrase_size, backend):
r"""Init a stash
`STASH_PATH` is the path to the storage endpoint. If this isn't supplied,
a default path will be used. In the path, you can specify a name
for the stash (which, if omitted, will default to `ghost`) like so:
`ghost init http://10.10.1.1:8500;stash1`.
After initializing a stash, don't forget you can set environment
variables for both your stash's path and its passphrase.
On Linux/OSx you can run:
export GHOST_STASH_PATH='http://10.10.1.1:8500;stash1'
export GHOST_PASSPHRASE=$(cat passphrase.ghost)
export GHOST_BACKEND='tinydb'
"""
stash_path = stash_path or STORAGE_DEFAULT_PATH_MAPPING[backend]
click.echo('Stash: {0} at {1}'.format(backend, stash_path))
storage = STORAGE_MAPPING[backend](**_parse_path_string(stash_path))
try:
click.echo('Initializing stash...')
if os.path.isfile(PASSPHRASE_FILENAME):
raise GhostError(
'{0} already exists. Overwriting might prevent you '
'from accessing the stash it was generated for. '
'Please make sure to save and remove the file before '
'initializing another stash.'.format(PASSPHRASE_FILENAME))
stash = Stash(
storage,
passphrase=passphrase,
passphrase_size=passphrase_size)
passphrase = stash.init()
if not passphrase:
click.echo('Stash already initialized.')
sys.exit(0)
_write_passphrase_file(passphrase)
except GhostError as ex:
sys.exit(ex)
except (OSError, IOError) as ex:
click.echo("Seems like we've run into a problem.")
file_path = _parse_path_string(stash_path)['db_path']
click.echo(
'Removing stale stash and passphrase: {0}. Note that any '
'directories created are not removed for safety reasons and you '
'might want to remove them manually.'.format(file_path))
if os.path.isfile(file_path):
os.remove(file_path)
sys.exit(ex)
click.echo('Initialized stash at: {0}'.format(stash_path))
click.echo(
'Your passphrase can be found under the `{0}` file in the '
'current directory.'.format(PASSPHRASE_FILENAME))
click.echo(
'Make sure you save your passphrase somewhere safe. '
'If lost, you will lose access to your stash.') | python | {
"resource": ""
} |
q260487 | put_key | validation | def put_key(key_name,
value,
description,
meta,
modify,
add,
lock,
key_type,
stash,
passphrase,
backend):
"""Insert a key to the stash
`KEY_NAME` is the name of the key to insert
`VALUE` is a key=value argument which can be provided multiple times.
it is the encrypted value of your key
"""
stash = _get_stash(backend, stash, passphrase)
try:
click.echo('Stashing {0} key...'.format(key_type))
stash.put(
name=key_name,
value=_build_dict_from_key_value(value),
modify=modify,
metadata=_build_dict_from_key_value(meta),
description=description,
lock=lock,
key_type=key_type,
add=add)
click.echo('Key stashed successfully')
except GhostError as ex:
sys.exit(ex) | python | {
"resource": ""
} |
q260488 | lock_key | validation | def lock_key(key_name,
stash,
passphrase,
backend):
"""Lock a key to prevent it from being deleted, purged or modified
`KEY_NAME` is the name of the key to lock
"""
stash = _get_stash(backend, stash, passphrase)
try:
click.echo('Locking key...')
stash.lock(key_name=key_name)
click.echo('Key locked successfully')
except GhostError as ex:
sys.exit(ex) | python | {
"resource": ""
} |
q260489 | unlock_key | validation | def unlock_key(key_name,
stash,
passphrase,
backend):
"""Unlock a key to allow it to be modified, deleted or purged
`KEY_NAME` is the name of the key to unlock
"""
stash = _get_stash(backend, stash, passphrase)
try:
click.echo('Unlocking key...')
stash.unlock(key_name=key_name)
click.echo('Key unlocked successfully')
except GhostError as ex:
sys.exit(ex) | python | {
"resource": ""
} |
q260490 | get_key | validation | def get_key(key_name,
value_name,
jsonify,
no_decrypt,
stash,
passphrase,
backend):
"""Retrieve a key from the stash
\b
`KEY_NAME` is the name of the key to retrieve
`VALUE_NAME` is a single value to retrieve e.g. if the value
of the key `test` is `a=b,b=c`, `ghost get test a`a will return
`b`
"""
if value_name and no_decrypt:
sys.exit('VALUE_NAME cannot be used in conjuction with --no-decrypt')
stash = _get_stash(backend, stash, passphrase, quiet=jsonify or value_name)
try:
key = stash.get(key_name=key_name, decrypt=not no_decrypt)
except GhostError as ex:
sys.exit(ex)
if not key:
sys.exit('Key `{0}` not found'.format(key_name))
if value_name:
key = key['value'].get(value_name)
if not key:
sys.exit(
'Value name `{0}` could not be found under key `{1}`'.format(
value_name, key_name))
if jsonify or value_name:
click.echo(
json.dumps(key, indent=4, sort_keys=False).strip('"'),
nl=True)
else:
click.echo('Retrieving key...')
click.echo('\n' + _prettify_dict(key)) | python | {
"resource": ""
} |
q260491 | delete_key | validation | def delete_key(key_name, stash, passphrase, backend):
"""Delete a key from the stash
`KEY_NAME` is the name of the key to delete
You can provide that multiple times to delete multiple keys at once
"""
stash = _get_stash(backend, stash, passphrase)
for key in key_name:
try:
click.echo('Deleting key {0}...'.format(key))
stash.delete(key_name=key)
except GhostError as ex:
sys.exit(ex)
click.echo('Keys deleted successfully') | python | {
"resource": ""
} |
q260492 | list_keys | validation | def list_keys(key_name,
max_suggestions,
cutoff,
jsonify,
locked,
key_type,
stash,
passphrase,
backend):
"""List all keys in the stash
If `KEY_NAME` is provided, will look for keys containing `KEY_NAME`.
If `KEY_NAME` starts with `~`, close matches will be provided according
to `max_suggestions` and `cutoff`.
"""
stash = _get_stash(backend, stash, passphrase, quiet=jsonify)
try:
keys = stash.list(
key_name=key_name,
max_suggestions=max_suggestions,
cutoff=cutoff,
locked_only=locked,
key_type=key_type)
except GhostError as ex:
sys.exit(ex)
if jsonify:
click.echo(json.dumps(keys, indent=4, sort_keys=True))
elif not keys:
click.echo('The stash is empty. Go on, put some keys in there...')
else:
click.echo('Listing all keys...')
click.echo(_prettify_list(keys)) | python | {
"resource": ""
} |
q260493 | purge_stash | validation | def purge_stash(force, stash, passphrase, backend):
"""Purge the stash from all of its keys
"""
stash = _get_stash(backend, stash, passphrase)
try:
click.echo('Purging stash...')
stash.purge(force)
# Maybe we should verify that the list is empty
# afterwards?
click.echo('Purge complete!')
except GhostError as ex:
sys.exit(ex) | python | {
"resource": ""
} |
q260494 | export_keys | validation | def export_keys(output_path, stash, passphrase, backend):
"""Export all keys to a file
"""
stash = _get_stash(backend, stash, passphrase)
try:
click.echo('Exporting stash to {0}...'.format(output_path))
stash.export(output_path=output_path)
click.echo('Export complete!')
except GhostError as ex:
sys.exit(ex) | python | {
"resource": ""
} |
q260495 | load_keys | validation | def load_keys(key_file, origin_passphrase, stash, passphrase, backend):
"""Load all keys from an exported key file to the stash
`KEY_FILE` is the exported stash file to load keys from
"""
stash = _get_stash(backend, stash, passphrase)
click.echo('Importing all keys from {0}...'.format(key_file))
stash.load(origin_passphrase, key_file=key_file)
click.echo('Import complete!') | python | {
"resource": ""
} |
q260496 | migrate_stash | validation | def migrate_stash(source_stash_path,
source_passphrase,
source_backend,
destination_stash_path,
destination_passphrase,
destination_backend):
"""Migrate all keys from a source stash to a destination stash.
`SOURCE_STASH_PATH` and `DESTINATION_STASH_PATH` are the paths
to the stashs you wish to perform the migration on.
"""
click.echo('Migrating all keys from {0} to {1}...'.format(
source_stash_path, destination_stash_path))
try:
migrate(
src_path=source_stash_path,
src_passphrase=source_passphrase,
src_backend=source_backend,
dst_path=destination_stash_path,
dst_passphrase=destination_passphrase,
dst_backend=destination_backend)
except GhostError as ex:
sys.exit(ex)
click.echo('Migration complete!') | python | {
"resource": ""
} |
q260497 | ssh | validation | def ssh(key_name, no_tunnel, stash, passphrase, backend):
"""Use an ssh type key to connect to a machine via ssh
Note that trying to use a key of the wrong type (e.g. `secret`)
will result in an error.
`KEY_NAME` is the key to use.
For additional information on the different configuration options
for an ssh type key, see the repo's readme.
"""
# TODO: find_executable or raise
def execute(command):
try:
click.echo('Executing: {0}'.format(' '.join(command)))
subprocess.check_call(' '.join(command), shell=True)
except subprocess.CalledProcessError:
sys.exit(1)
stash = _get_stash(backend, stash, passphrase)
key = stash.get(key_name)
if key:
_assert_is_ssh_type_key(key)
else:
sys.exit('Key `{0}` not found'.format(key_name))
conn_info = key['value']
ssh_key_path = conn_info.get('ssh_key_path')
ssh_key = conn_info.get('ssh_key')
proxy_key_path = conn_info.get('proxy_key_path')
proxy_key = conn_info.get('proxy_key')
id_file = _write_tmp(ssh_key) if ssh_key else ssh_key_path
conn_info['ssh_key_path'] = id_file
if conn_info.get('proxy'):
proxy_id_file = _write_tmp(proxy_key) if proxy_key else proxy_key_path
conn_info['proxy_key_path'] = proxy_id_file
ssh_command = _build_ssh_command(conn_info, no_tunnel)
try:
execute(ssh_command)
finally:
# If they're not equal, that means we've created a temp one which
# should be deleted, else, it's a path to an existing key file.
if id_file != ssh_key_path:
click.echo('Removing temp ssh key file: {0}...'.format(id_file))
os.remove(id_file)
if conn_info.get('proxy') and proxy_id_file != proxy_key_path:
click.echo('Removing temp proxy key file: {0}...'.format(
proxy_id_file))
os.remove(proxy_id_file) | python | {
"resource": ""
} |
q260498 | Stash.put | validation | def put(self,
name,
value=None,
modify=False,
metadata=None,
description='',
encrypt=True,
lock=False,
key_type='secret',
add=False):
"""Put a key inside the stash
if key exists and modify true: delete and create
if key exists and modify false: fail
if key doesn't exist and modify true: fail
if key doesn't exist and modify false: create
`name` is unique and cannot be changed.
`value` must be provided if the key didn't already exist, otherwise,
the previous value will be retained.
`created_at` will be left unmodified if the key
already existed. Otherwise, the current time will be used.
`modified_at` will be changed to the current time
if the field is being modified.
`metadata` will be updated if provided. If it wasn't
provided the field from the existing key will be used and the
same goes for the `uid` which will be generated if it didn't
previously exist.
`lock` will lock the key to prevent it from being modified or deleted
`add` allows to add values to an existing key instead of overwriting.
Returns the id of the key in the database
"""
def assert_key_is_unlocked(existing_key):
if existing_key and existing_key.get('lock'):
raise GhostError(
'Key `{0}` is locked and therefore cannot be modified. '
'Unlock the key and try again'.format(name))
def assert_value_provided_for_new_key(value, existing_key):
if not value and not existing_key.get('value'):
raise GhostError('You must provide a value for new keys')
self._assert_valid_stash()
self._validate_key_schema(value, key_type)
if value and encrypt and not isinstance(value, dict):
raise GhostError('Value must be of type dict')
# TODO: This should be refactored. `_handle_existing_key` deletes
# the key rather implicitly. It shouldn't do that.
# `existing_key` will be an empty dict if it doesn't exist
key = self._handle_existing_key(name, modify or add)
assert_key_is_unlocked(key)
assert_value_provided_for_new_key(value, key)
new_key = dict(name=name, lock=lock)
if value:
# TODO: fix edge case in which encrypt is false and yet we might
# try to add to an existing key. encrypt=false is only used when
# `load`ing into a new stash, but someone might use it directly
# from the API.
if add:
value = self._update_existing_key(key, value)
new_key['value'] = self._encrypt(value) if encrypt else value
else:
new_key['value'] = key.get('value')
# TODO: Treat a case in which we try to update an existing key
# but don't provide a value in which nothing will happen.
new_key['description'] = description or key.get('description')
new_key['created_at'] = key.get('created_at') or _get_current_time()
new_key['modified_at'] = _get_current_time()
new_key['metadata'] = metadata or key.get('metadata')
new_key['uid'] = key.get('uid') or str(uuid.uuid4())
new_key['type'] = key.get('type') or key_type
key_id = self._storage.put(new_key)
audit(
storage=self._storage.db_path,
action='MODIFY' if (modify or add) else 'PUT',
message=json.dumps(dict(
key_name=new_key['name'],
value='HIDDEN',
description=new_key['description'],
uid=new_key['uid'],
metadata=json.dumps(new_key['metadata']),
lock=new_key['lock'],
type=new_key['type'])))
return key_id | python | {
"resource": ""
} |
q260499 | Stash.get | validation | def get(self, key_name, decrypt=True):
"""Return a key with its parameters if it was found.
"""
self._assert_valid_stash()
key = self._storage.get(key_name).copy()
if not key.get('value'):
return None
if decrypt:
key['value'] = self._decrypt(key['value'])
audit(
storage=self._storage.db_path,
action='GET',
message=json.dumps(dict(key_name=key_name)))
return key | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.