desc stringlengths 3 26.7k | decl stringlengths 11 7.89k | bodies stringlengths 8 553k |
|---|---|---|
'Remove ``repository`` from this team.
:param str repository: (required), form: \'user/repo\'
:returns: bool'
| @requires_auth
def remove_repository(self, repository):
| url = self._build_url(u'repos', repository, base_url=self._api)
return self._boolean(self._delete(url), 204, 404)
|
'Add ``username`` to ``team`` and thereby to this organization.
.. warning::
This method is no longer valid. To add a member to a team, you
must now retrieve the team directly, and use the ``invite``
method.
.. warning::
This method is no longer valid. To add a member to a team, you
must now retrieve the team directly,... | @requires_auth
def add_member(self, username, team_id):
| warnings.warn(u'This is no longer supported by the GitHub API, see https://developer.github.com/changes/2014-09-23-one-more-week-before-the-add-team-member-api-breaking-change/', DeprecationWarning)
if (int(team_id) < 0):
return False
url = self._build_url(u'teams', str... |
'Add ``repository`` to ``team``.
.. versionchanged:: 1.0
The second parameter used to be ``team`` but has been changed to
``team_id``. This parameter is now required to be an integer to
improve performance of this method.
:param str repository: (required), form: \'user/repo\'
:param int team_id: (required), team id
:re... | @requires_auth
def add_repository(self, repository, team_id):
| if (int(team_id) < 0):
return False
url = self._build_url(u'teams', str(team_id), u'repos', str(repository))
return self._boolean(self._put(url), 204, 404)
|
'Create a repository for this organization.
If the client is authenticated and a member of the organization, this
will create a new repository in the organization.
:param str name: (required), name of the repository
:param str description: (optional)
:param str homepage: (optional)
:param bool private: (optional), If `... | @requires_auth
def create_repository(self, name, description=u'', homepage=u'', private=False, has_issues=True, has_wiki=True, team_id=0, auto_init=False, gitignore_template=u'', license_template=u''):
| url = self._build_url(u'repos', base_url=self._api)
data = {u'name': name, u'description': description, u'homepage': homepage, u'private': private, u'has_issues': has_issues, u'has_wiki': has_wiki, u'license_template': license_template, u'auto_init': auto_init, u'gitignore_template': gitignore_template}
if ... |
'Conceal ``username``\'s membership in this organization.
:param str username: username of the organization member to conceal
:returns: bool'
| @requires_auth
def conceal_member(self, username):
| url = self._build_url(u'public_members', username, base_url=self._api)
return self._boolean(self._delete(url), 204, 404)
|
'Create a new team and return it.
This only works if the authenticated user owns this organization.
:param str name: (required), name to be given to the team
:param list repo_names: (optional) repositories, e.g.
[\'github/dotfiles\']
:param str permission: (optional), options:
- ``pull`` -- (default) members can not pu... | @requires_auth
def create_team(self, name, repo_names=[], permission=u''):
| data = {u'name': name, u'repo_names': repo_names, u'permission': permission}
url = self._build_url(u'teams', base_url=self._api)
json = self._json(self._post(url, data), 201)
return self._instance_or_null(Team, json)
|
'Edit this organization.
:param str billing_email: (optional) Billing email address (private)
:param str company: (optional)
:param str email: (optional) Public email address
:param str location: (optional)
:param str name: (optional)
:returns: bool'
| @requires_auth
def edit(self, billing_email=None, company=None, email=None, location=None, name=None):
| json = None
data = {u'billing_email': billing_email, u'company': company, u'email': email, u'location': location, u'name': name}
self._remove_none(data)
if data:
json = self._json(self._patch(self._api, data=dumps(data)), 200)
if json:
self._update_attributes(json)
return Tru... |
'Check if the user named ``username`` is a member.
:param str username: name of the user you\'d like to check
:returns: bool'
| def is_member(self, username):
| url = self._build_url(u'members', username, base_url=self._api)
return self._boolean(self._get(url), 204, 404)
|
'Check if the user named ``username`` is a public member.
:param str username: name of the user you\'d like to check
:returns: bool'
| def is_public_member(self, username):
| url = self._build_url(u'public_members', username, base_url=self._api)
return self._boolean(self._get(url), 204, 404)
|
'Iterate over all org events visible to the authenticated user.
:param str username: (required), the username of the currently
authenticated user.
:param int number: (optional), number of events to return. Default: -1
iterates over all events available.
:param str etag: (optional), ETag from a previous request to the s... | def all_events(self, username, number=(-1), etag=None):
| url = self._build_url(u'users', username, u'events', u'orgs', self.login)
return self._iter(int(number), url, Event, etag=etag)
|
'Iterate over public events for this org (deprecated).
:param int number: (optional), number of events to return. Default: -1
iterates over all events available.
:param str etag: (optional), ETag from a previous request to the same
endpoint
:returns: generator of :class:`Event <github3.events.Event>`\ s
Deprecated: Use... | def events(self, number=(-1), etag=None):
| warnings.warn(u'This method is deprecated. Please use ``public_events`` instead.', DeprecationWarning)
return self.public_events(number, etag=etag)
|
'Iterate over public events for this org.
:param int number: (optional), number of events to return. Default: -1
iterates over all events available.
:param str etag: (optional), ETag from a previous request to the same
endpoint
:returns: generator of :class:`Event <github3.events.Event>`\ s'
| def public_events(self, number=(-1), etag=None):
| url = self._build_url(u'events', base_url=self._api)
return self._iter(int(number), url, Event, etag=etag)
|
'Iterate over members of this organization.
:param str filter: (optional), filter members returned by this method.
Can be one of: ``"2fa_disabled"``, ``"all",``. Default: ``"all"``.
Filtering by ``"2fa_disabled"`` is only available for organization
owners with private repositories.
:param str role: (optional), filter m... | def members(self, filter=None, role=None, number=(-1), etag=None):
| headers = {}
params = {}
if (filter in self.members_filters):
params[u'filter'] = filter
if (role in self.members_roles):
params[u'role'] = role
headers[u'Accept'] = u'application/vnd.github.ironman-preview+json'
url = self._build_url(u'members', base_url=self._api)
retur... |
'Iterate over public members of this organization.
:param int number: (optional), number of members to return. Default:
-1 will return all available.
:param str etag: (optional), ETag from a previous request to the same
endpoint
:returns: generator of :class:`User <github3.users.User>`\ s'
| def public_members(self, number=(-1), etag=None):
| url = self._build_url(u'public_members', base_url=self._api)
return self._iter(int(number), url, users.ShortUser, etag=etag)
|
'Iterate over repos for this organization.
:param str type: (optional), accepted values:
(\'all\', \'public\', \'member\', \'private\', \'forks\', \'sources\'), API
default: \'all\'
:param int number: (optional), number of members to return. Default:
-1 will return all available.
:param str etag: (optional), ETag from ... | def repositories(self, type=u'', number=(-1), etag=None):
| url = self._build_url(u'repos', base_url=self._api)
params = {}
if (type in (u'all', u'public', u'member', u'private', u'forks', u'sources')):
params[u'type'] = type
return self._iter(int(number), url, Repository, params, etag)
|
'Iterate over teams that are part of this organization.
:param int number: (optional), number of teams to return. Default: -1
returns all available teams.
:param str etag: (optional), ETag from a previous request to the same
endpoint
:returns: generator of :class:`Team <Team>`\ s'
| @requires_auth
def teams(self, number=(-1), etag=None):
| url = self._build_url(u'teams', base_url=self._api)
return self._iter(int(number), url, Team, etag=etag)
|
'Make ``username``\'s membership in this organization public.
:param str username: the name of the user whose membership you wish to
publicize
:returns: bool'
| @requires_auth
def publicize_member(self, username):
| url = self._build_url(u'public_members', username, base_url=self._api)
return self._boolean(self._put(url), 204, 404)
|
'Remove the user named ``username`` from this organization.
:param str username: name of the user to remove from the org
:returns: bool'
| @requires_auth
def remove_member(self, username):
| url = self._build_url(u'members', username, base_url=self._api)
return self._boolean(self._delete(url), 204, 404)
|
'Remove ``repository`` from the team with ``team_id``.
:param str repository: (required), form: \'user/repo\'
:param int team_id: (required)
:returns: bool'
| @requires_auth
def remove_repository(self, repository, team_id):
| if (int(team_id) > 0):
url = self._build_url(u'teams', str(team_id), u'repos', str(repository))
return self._boolean(self._delete(url), 204, 404)
return False
|
'Return the team specified by ``team_id``.
:param int team_id: (required), unique id for the team
:returns: :class:`Team <Team>`'
| @requires_auth
def team(self, team_id):
| json = None
if (int(team_id) > 0):
url = self._build_url(u'teams', str(team_id))
json = self._json(self._get(url), 200)
return self._instance_or_null(Team, json)
|
'Edit the user\'s membership.
:param str state: (required), the state the membership should be in.
Only accepts ``"active"``.
:returns: whether the edit was successful or not
:rtype: bool'
| @requires_auth
def edit(self, state):
| if (state and (state.lower() == u'active')):
data = dumps({u'state': state.lower()})
json = self._json(self._patch(self._api, data=data))
self._update_attributes(json)
return True
return False
|
'Delete this reference.
:returns: bool'
| @requires_auth
def delete(self):
| return self._boolean(self._delete(self._api), 204, 404)
|
'Update this reference.
:param str sha: (required), sha of the reference
:param bool force: (optional), force the update or not
:returns: bool'
| @requires_auth
def update(self, sha, force=False):
| data = {u'sha': sha, u'force': force}
json = self._json(self._patch(self._api, data=dumps(data)), 200)
if json:
self._update_attributes(json)
return True
return False
|
'Recurse into the tree.
:returns: :class:`Tree <Tree>`'
| def recurse(self):
| json = self._json(self._get(self._api, params={u'recursive': u'1'}), 200)
return self._instance_or_null(Tree, json)
|
'Delete this key.'
| @requires_auth
def delete(self):
| return self._boolean(self._delete(self._api), 204, 404)
|
'Update this key.
.. warning::
As of 20 June 2014, the API considers keys to be immutable.
This will soon begin to return MethodNotAllowed errors.
:param str title: (required), title of the key
:param str key: (required), text of the key file
:returns: bool'
| @requires_auth
def update(self, title, key):
| json = None
if (title and key):
data = {u'title': title, u'key': key}
json = self._json(self._patch(self._api, data=dumps(data)), 200)
if json:
self._update_attributes(json)
return True
return False
|
'Check if this is a free plan.
:returns: bool'
| def is_free(self):
| return (self.name == u'free')
|
'Check if this user can be assigned to issues on username/repository.
:param str username: owner\'s username of the repository
:param str repository: name of the repository
:returns: True if the use can be assigned, False otherwise
:rtype: :class:`bool`'
| def is_assignee_on(self, username, repository):
| url = self._build_url(u'repos', username, repository, u'assignees', self.login)
return self._boolean(self._get(url), 204, 404)
|
'Check if this user is following ``username``.
:param str username: (required)
:returns: bool'
| def is_following(self, username):
| url = self.following_urlt.expand(other_user=username)
return self._boolean(self._get(url), 204, 404)
|
'Iterate over events performed by this user.
:param bool public: (optional), only list public events for the
authenticated user
:param int number: (optional), number of events to return. Default: -1
returns all available events.
:param str etag: (optional), ETag from a previous request to the same
endpoint
:returns: ge... | def events(self, public=False, number=(-1), etag=None):
| path = [u'events']
if public:
path.append(u'public')
url = self._build_url(base_url=self._api, *path)
return self._iter(int(number), url, Event, etag=etag)
|
'Iterate over the followers of this user.
:param int number: (optional), number of followers to return. Default:
-1 returns all available
:param str etag: (optional), ETag from a previous request to the same
endpoint
:returns: generator of :class:`User <User>`\ s'
| def followers(self, number=(-1), etag=None):
| url = self._build_url(u'followers', base_url=self._api)
return self._iter(int(number), url, ShortUser, etag=etag)
|
'Iterate over the users being followed by this user.
:param int number: (optional), number of users to return. Default: -1
returns all available users
:param str etag: (optional), ETag from a previous request to the same
endpoint
:returns: generator of :class:`User <User>`\ s'
| def following(self, number=(-1), etag=None):
| url = self._build_url(u'following', base_url=self._api)
return self._iter(int(number), url, ShortUser, etag=etag)
|
'Iterate over the public keys of this user.
.. versionadded:: 0.5
:param int number: (optional), number of keys to return. Default: -1
returns all available keys
:param str etag: (optional), ETag from a previous request to the same
endpoint
:returns: generator of :class:`Key <Key>`\ s'
| def keys(self, number=(-1), etag=None):
| url = self._build_url(u'keys', base_url=self._api)
return self._iter(int(number), url, Key, etag=etag)
|
'Iterate over events from the user\'s organization dashboard.
.. note:: You must be authenticated to view this.
:param str org: (required), name of the organization
:param int number: (optional), number of events to return. Default: -1
returns all available events
:param str etag: (optional), ETag from a previous reque... | @requires_auth
def organization_events(self, org, number=(-1), etag=None):
| url = u''
if org:
url = self._build_url(u'events', u'orgs', org, base_url=self._api)
return self._iter(int(number), url, Event, etag=etag)
|
'Iterate over events that the user has received.
If the user is the authenticated user, you will see private and public
events, otherwise you will only see public events.
:param bool public: (optional), determines if the authenticated user
sees both private and public or just public
:param int number: (optional), numbe... | def received_events(self, public=False, number=(-1), etag=None):
| path = [u'received_events']
if public:
path.append(u'public')
url = self._build_url(base_url=self._api, *path)
return self._iter(int(number), url, Event, etag=etag)
|
'Iterate over organizations the user is member of.
:param int number: (optional), number of organizations to return.
Default: -1 returns all available organization
:param str etag: (optional), ETag from a previous request to the same
endpoint
:returns: generator of :class:`Event <github3.orgs.Organization>`\ s'
| def organizations(self, number=(-1), etag=None):
| from .orgs import Organization
url = self._build_url(u'orgs', base_url=self._api)
return self._iter(int(number), url, Organization, etag=etag)
|
'Iterate over repositories starred by this user.
.. versionchanged:: 0.5
Added sort and direction parameters (optional) as per the change in
GitHub\'s API.
:param int number: (optional), number of starred repos to return.
Default: -1, returns all available repos
:param str sort: (optional), either \'created\' (when the... | def starred_repositories(self, sort=None, direction=None, number=(-1), etag=None):
| from .repos import Repository, StarredRepository
params = {u'sort': sort, u'direction': direction}
self._remove_none(params)
url = self.starred_urlt.expand(owner=None, repo=None)
return self._iter(int(number), url, StarredRepository, params, etag, headers=Repository.STAR_HEADERS)
|
'Iterate over repositories subscribed to by this user.
:param int number: (optional), number of subscriptions to return.
Default: -1, returns all available
:param str etag: (optional), ETag from a previous request to the same
endpoint
:returns: generator of :class:`Repository <github3.repos.Repository>`'
| def subscriptions(self, number=(-1), etag=None):
| from .repos import Repository
url = self._build_url(u'subscriptions', base_url=self._api)
return self._iter(int(number), url, Repository, etag=etag)
|
'Rename the user.
.. note::
This is only available for administrators of a GitHub Enterprise
instance.
:param str login: (required), new name of the user
:returns: bool'
| @requires_auth
def rename(self, login):
| url = self._build_url(u'admin', u'users', self.login)
payload = {u'login': login}
resp = self._boolean(self._patch(url, data=payload), 202, 403)
return resp
|
'Obtain an impersonation token for the user.
The retrieved token will allow impersonation of the user.
This is only available for admins of a GitHub Enterprise instance.
:param list scopes: (optional), areas you want this token to apply to,
i.e., \'gist\', \'user\'
:returns: :class:`Authorization <Authorization>`'
| @requires_auth
def impersonate(self, scopes=None):
| url = self._build_url(u'admin', u'users', self.login, u'authorizations')
data = {}
if scopes:
data[u'scopes'] = scopes
json = self._json(self._post(url, data=data), 201)
return self._instance_or_null(Authorization, json)
|
'Revoke all impersonation tokens for the current user.
This is only available for admins of a GitHub Enterprise instance.
:returns: bool -- True if successful, False otherwise'
| @requires_auth
def revoke_impersonation(self):
| url = self._build_url(u'admin', u'users', self.login, u'authorizations')
return self._boolean(self._delete(url), 204, 403)
|
'Promote a user to site administrator.
This is only available for admins of a GitHub Enterprise instance.
:returns: bool -- True if successful, False otherwise'
| @requires_auth
def promote(self):
| url = self._build_url(u'site_admin', base_url=self._api)
return self._boolean(self._put(url), 204, 403)
|
'Demote a site administrator to simple user.
You can demote any user account except your own.
This is only available for admins of a GitHub Enterprise instance.
:returns: bool -- True if successful, False otherwise'
| @requires_auth
def demote(self):
| url = self._build_url(u'site_admin', base_url=self._api)
return self._boolean(self._delete(url), 204, 403)
|
'Suspend the user.
This is only available for admins of a GitHub Enterprise instance.
This API is disabled if you use LDAP, check the GitHub API dos for more
information.
:returns: bool -- True if successful, False otherwise'
| @requires_auth
def suspend(self):
| url = self._build_url(u'suspended', base_url=self._api)
return self._boolean(self._put(url), 204, 403)
|
'Unsuspend the user.
This is only available for admins of a GitHub Enterprise instance.
This API is disabled if you use LDAP, check the GitHub API dos for more
information.
:returns: bool -- True if successful, False otherwise'
| @requires_auth
def unsuspend(self):
| url = self._build_url(u'suspended', base_url=self._api)
return self._boolean(self._delete(url), 204, 403)
|
'Delete the user.
Per GitHub API documentation, it is often preferable to suspend the
user.
.. note::
This is only available for admins of a GitHub Enterprise instance.
:returns: bool -- True if successful, False otherwise'
| @requires_auth
def delete(self):
| url = self._build_url(u'admin', u'users', self.login)
return self._boolean(self._delete(url), 204, 403)
|
'Returns a string representation for the given value.'
| def format(self, arg):
| return (("'%s'" % arg) if isinstance(arg, basestring) else str(arg))
|
'Returns key=formatted(value).'
| def pair(self, key, value):
| return ('%s=%s' % (key, self.format(value)))
|
'Emits the Python source for this node.'
| def emit(self):
| args = map(self.format, self.args)
if self.kwargs:
args += [self.pair(k, v) for (k, v) in self.kwargs]
args.append(self.pair('name', self.node.name))
args = ', '.join(args)
return ('%s(%s)' % (self.op, args))
|
'Construct the network.'
| def setup(self):
| raise NotImplementedError('Must be implemented by the subclass.')
|
'Load network weights.
data_path: The path to the numpy-serialized network weights
session: The current TensorFlow session
ignore_missing: If true, serialized weights for missing layers are ignored.'
| def load(self, data_path, session, ignore_missing=False):
| data_dict = np.load(data_path).item()
for op_name in data_dict:
with tf.variable_scope(op_name, reuse=True):
for (param_name, data) in data_dict[op_name].iteritems():
try:
var = tf.get_variable(param_name)
session.run(var.assign(data))
... |
'Set the input(s) for the next operation by replacing the terminal nodes.
The arguments can be either layer names or the actual layers.'
| def feed(self, *args):
| assert (len(args) != 0)
self.terminals = []
for fed_layer in args:
if isinstance(fed_layer, basestring):
try:
fed_layer = self.layers[fed_layer]
except KeyError:
raise KeyError(('Unknown layer name fed: %s' % fed_layer))
sel... |
'Returns the current network output.'
| def get_output(self):
| return self.terminals[(-1)]
|
'Returns an index-suffixed unique name for the given prefix.
This is used for auto-generating layer names based on the type-prefix.'
| def get_unique_name(self, prefix):
| ident = (sum((t.startswith(prefix) for (t, _) in self.layers.items())) + 1)
return ('%s_%d' % (prefix, ident))
|
'Creates a new TensorFlow variable.'
| def make_var(self, name, shape):
| return tf.get_variable(name, shape, trainable=self.trainable)
|
'Verifies that the padding is one of the supported ones.'
| def validate_padding(self, padding):
| assert (padding in ('SAME', 'VALID'))
|
'def_path: Path to the model definition (.prototxt)
data_path: Path to the model data (.caffemodel)
phase: Either \'test\' or \'train\'. Used for filtering phase-specific nodes.'
| def __init__(self, def_path, phase='test'):
| self.def_path = def_path
self.phase = phase
self.load()
|
'Load the layer definitions from the prototxt.'
| def load(self):
| self.params = get_caffe_resolver().NetParameter()
with open(self.def_path, 'rb') as def_file:
text_format.Merge(def_file.read(), self.params)
|
'Filter out layers based on the current phase.'
| def filter_layers(self, layers):
| phase_map = {0: 'train', 1: 'test'}
filtered_layer_names = set()
filtered_layers = []
for layer in layers:
phase = self.phase
if len(layer.include):
phase = phase_map[layer.include[0].phase]
if len(layer.exclude):
phase = phase_map[(1 - layer.include[0].ph... |
'Create a graph node for the given layer.'
| def make_node(self, layer):
| kind = NodeKind.map_raw_kind(layer.type)
if (kind is None):
raise KaffeError(('Unknown layer type encountered: %s' % layer.type))
return Node(layer.name, kind, layer=layer)
|
'Create data input nodes.
This method is for old-style inputs, where the input specification
was not treated as a first-class layer in the prototext.
Newer models use the "Input layer" type.'
| def make_input_nodes(self):
| nodes = [Node(name, NodeKind.Data) for name in self.params.input]
if len(nodes):
input_dim = map(int, self.params.input_dim)
if (not input_dim):
if (len(self.params.input_shape) > 0):
input_dim = map(int, self.params.input_shape[0].dim)
else:
... |
'Builds the graph from the Caffe layer definitions.'
| def build(self):
| layers = (self.params.layers or self.params.layer)
layers = self.filter_layers(layers)
nodes = self.make_input_nodes()
nodes += [self.make_node(layer) for layer in layers]
graph = Graph(nodes=nodes, name=self.params.name)
node_outputs = {}
for layer in layers:
node = graph.get_node(l... |
'Returns true if this parent/child pair is eligible for fusion.'
| def is_eligible_pair(self, parent, child):
| raise NotImplementedError('Must be implemented by subclass.')
|
'Merge the child node into the parent.'
| def merge(self, parent, child):
| raise NotImplementedError('Must be implemented by subclass')
|
'Start the processing worker threads.'
| def start(self, session, coordinator, num_concurrent=4):
| session.run(self.enqueue_paths_op)
session.run(self.close_path_queue_op)
return self.queue_runner.create_threads(session, coord=coordinator, start=True)
|
'Get a single batch of images along with their indices. If a set of labels were provided,
the corresponding labels are returned instead of the indices.'
| def get(self, session):
| (indices, images) = session.run(self.dequeue_op)
if (self.labels is not None):
labels = [self.labels[idx] for idx in indices]
return (labels, images)
return (indices, images)
|
'Yield a batch until no more images are left.'
| def batches(self, session):
| for _ in xrange(self.num_batches):
(yield self.get(session=session))
|
'Set the test up with default headers and status codes.'
| def setUp(self):
| self.headers = list()
self.status = list()
|
'TODO'
| def test_logging(self):
| Zappa()
|
'API Gateway resources have a "test bolt" button on methods.
This button sends some empty dicts as \'null\' instead of \'{}\'.'
| def test_wsgi_from_apigateway_testbutton(self):
| event = {'resource': '/', 'path': '/', 'httpMethod': 'GET', 'headers': None, 'queryStringParameters': None, 'pathParameters': None, 'stageVariables': None, 'requestContext': {'accountId': '0123456', 'resourceId': 'qwertyasdf', 'stage': 'test-invoke-stage', 'requestId': 'test-invoke-request', 'identity': {'cognitoId... |
'Make sure Zappa uses settings in the proper order: JSON, TOML, YAML.'
| def test_settings_extension(self):
| tempdir = tempfile.mkdtemp(prefix='zappa-test-settings')
shutil.copy('tests/test_one_env.json', (tempdir + '/zappa_settings.json'))
shutil.copy('tests/test_settings.yml', (tempdir + '/zappa_settings.yml'))
shutil.copy('tests/test_settings.toml', (tempdir + '/zappa_settings.toml'))
orig_cwd = os.getc... |
'Make sure \'zappa certify\':
* Writes a warning with the --no-cleanup flag.
* Errors out when a deployment hasn\'t taken place.
* Writes errors when certificate settings haven\'t been specified.
* Calls Zappa correctly for creates vs. updates.'
| def test_certify_sanity_checks(self):
| old_stdout = sys.stderr
if (sys.version_info[0] < 3):
sys.stdout = OldStringIO()
try:
zappa_cli = ZappaCLI()
zappa_cli.domain = 'test.example.com'
try:
zappa_cli.certify(no_cleanup=True)
except AttributeError:
pass
log_output = sys.stdo... |
'This checks whether Flask can write errors sanely.
https://github.com/Miserlou/Zappa/issues/283'
| def test_flask_logging_bug(self):
| event = {'body': {}, 'headers': {}, 'pathParameters': {}, 'path': '/', 'httpMethod': 'GET', 'queryStringParameters': {}, 'requestContext': {}}
old_stderr = sys.stderr
sys.stderr = BytesIO()
try:
environ = create_wsgi_request(event)
app = flask.Flask(__name__)
with app.request_con... |
'Ensure that requests to the amazonaws.com host for an API with a
domain have the correct request.url'
| def test_wsgi_script_name_on_aws_url(self):
| lh = LambdaHandler('tests.test_wsgi_script_name_settings')
event = {'body': '', 'resource': '/{proxy+}', 'requestContext': {}, 'queryStringParameters': {}, 'headers': {'Host': '1234567890.execute-api.us-east-1.amazonaws.com'}, 'pathParameters': {'proxy': 'return/request/url'}, 'httpMethod': 'GET', 'stageVariabl... |
'Ensure that requests to the amazonaws.com host for an API with a
domain have the correct request.url'
| def test_wsgi_script_name_on_domain_url(self):
| lh = LambdaHandler('tests.test_wsgi_script_name_settings')
event = {'body': '', 'resource': '/{proxy+}', 'requestContext': {}, 'queryStringParameters': {}, 'headers': {'Host': 'example.com'}, 'pathParameters': {'proxy': 'return/request/url'}, 'httpMethod': 'GET', 'stageVariables': {}, 'path': '/return/request/u... |
'Ensure that requests sent by the "Send test request" button behaves
sensibly'
| def test_wsgi_script_name_on_test_request(self):
| lh = LambdaHandler('tests.test_wsgi_script_name_settings')
event = {'body': '', 'resource': '/{proxy+}', 'requestContext': {}, 'queryStringParameters': {}, 'headers': {}, 'pathParameters': {'proxy': 'return/request/url'}, 'httpMethod': 'GET', 'stageVariables': {}, 'path': '/return/request/url'}
response = l... |
'Returns a troposphere Ref to a value cached as a parameter.'
| def cache_param(self, value):
| if (value not in self.cf_parameters):
keyname = chr((ord('A') + len(self.cf_parameters)))
param = self.cf_template.add_parameter(troposphere.Parameter(keyname, Type='String', Default=value))
self.cf_parameters[value] = param
return troposphere.Ref(self.cf_parameters[value])
|
''
| def copy_editable_packages(self, egg_links, temp_package_path):
| for egg_link in egg_links:
with open(egg_link, 'rb') as df:
egg_path = df.read().decode('utf-8').splitlines()[0].strip()
pkgs = set([x.split('.')[0] for x in find_packages(egg_path, exclude=['test', 'tests'])])
for pkg in pkgs:
copytree(os.path.join(egg_pa... |
'For a given package, returns a list of required packages. Recursive.'
| def get_deps_list(self, pkg_name, installed_distros=None):
| import pip
deps = []
if (not installed_distros):
installed_distros = pip.get_installed_distributions()
for package in installed_distros:
if (package.project_name.lower() == pkg_name.lower()):
deps = [(package.project_name, package.version)]
for req in package.requ... |
'Takes the installed zappa and brings it into a fresh virtualenv-like folder. All dependencies are then downloaded.'
| def create_handler_venv(self):
| import pip
current_venv = self.get_current_venv()
ve_path = os.path.join(os.getcwd(), 'handler_venv')
if (os.sys.platform == 'win32'):
current_site_packages_dir = os.path.join(current_venv, 'Lib', 'site-packages')
venv_site_packages_dir = os.path.join(ve_path, 'Lib', 'site-packages')
... |
'Returns the path to the current virtualenv'
| @staticmethod
def get_current_venv():
| if ('VIRTUAL_ENV' in os.environ):
venv = os.environ['VIRTUAL_ENV']
elif os.path.exists('.python-version'):
try:
subprocess.check_output('pyenv help', stderr=subprocess.STDOUT)
except OSError:
print("This directory seems to have pyenv's local ... |
'Create a Lambda-ready zip file of the current virtualenvironment and working directory.
Returns path to that file.'
| def create_lambda_zip(self, prefix='lambda_package', handler_file=None, slim_handler=False, minify=True, exclude=None, use_precompiled_packages=True, include=None, venv=None, output=None, disable_progress=False):
| import pip
if (not venv):
venv = self.get_current_venv()
cwd = os.getcwd()
if (not output):
zip_fname = (((prefix + '-') + str(int(time.time()))) + '.zip')
else:
zip_fname = output
zip_path = os.path.join(cwd, zip_fname)
if (exclude is None):
exclude = list()
... |
'Extracts the lambda package into a given path. Assumes the package exists in lambda packages.'
| def extract_lambda_package(self, package_name, path):
| lambda_package = lambda_packages[package_name][self.runtime]
shutil.rmtree(os.path.join(path, package_name), ignore_errors=True)
tar = tarfile.open(lambda_package['path'], mode='r:gz')
for member in tar.getmembers():
tar.extract(member, path)
|
'Returns a dict of installed packages that Zappa cares about.'
| @staticmethod
def get_installed_packages(site_packages, site_packages_64):
| import pip
package_to_keep = []
if os.path.isdir(site_packages):
package_to_keep += os.listdir(site_packages)
if os.path.isdir(site_packages_64):
package_to_keep += os.listdir(site_packages_64)
installed_packages = {package.project_name.lower(): package.version for package in pip.get... |
'Checks if a given package version binary should be copied over from lambda packages.
package_name should be lower-cased version of package name.'
| def have_correct_lambda_package_version(self, package_name, package_version):
| lambda_package_details = lambda_packages.get(package_name, {}).get(self.runtime)
if (lambda_package_details is None):
return False
if (package_version != lambda_package_details['version']):
return False
return True
|
'Checks if a given package has any lambda package version. We can try and use it with a warning.
package_name should be lower-cased version of package name.'
| def have_any_lambda_package_version(self, package_name):
| return (lambda_packages.get(package_name, {}).get(self.runtime) is not None)
|
'Downloads a given url in chunks and writes to the provided stream (can be any io stream).
Displays the progress bar for the download.'
| @staticmethod
def download_url_with_progress(url, stream, disable_progress):
| resp = requests.get(url, timeout=2, stream=True)
resp.raw.decode_content = True
progress = tqdm(unit='B', unit_scale=True, total=int(resp.headers.get('Content-Length', 0)), disable=disable_progress)
for chunk in resp.iter_content(chunk_size=1024):
if chunk:
progress.update(len(chunk)... |
'Gets the locally stored version of a manylinux wheel. If one does not exist, the function downloads it.'
| def get_cached_manylinux_wheel(self, package_name, package_version, disable_progress=False):
| cached_wheels_dir = os.path.join(tempfile.gettempdir(), 'cached_wheels')
if (not os.path.isdir(cached_wheels_dir)):
os.makedirs(cached_wheels_dir)
wheel_file = '{0!s}-{1!s}-{2!s}'.format(package_name, package_version, self.manylinux_wheel_file_suffix)
wheel_path = os.path.join(cached_wheels_dir,... |
'For a given package name, returns a link to the download URL,
else returns None.
Related: https://github.com/Miserlou/Zappa/issues/398
Examples here: https://gist.github.com/perrygeo/9545f94eaddec18a65fd7b56880adbae'
| def get_manylinux_wheel_url(self, package_name, package_version):
| url = 'https://pypi.python.org/pypi/{}/json'.format(package_name)
try:
res = requests.get(url, timeout=1.5)
data = res.json()
for f in data['releases'][package_version]:
if f['filename'].endswith(self.manylinux_wheel_file_suffix):
return f['url']
except Ex... |
'Given a file, upload it to S3.
Credentials should be stored in environment variables or ~/.aws/credentials (%USERPROFILE%\.aws\credentials on Windows).
Returns True on success, false on failure.'
| def upload_to_s3(self, source_path, bucket_name, disable_progress=False):
| try:
self.s3_client.head_bucket(Bucket=bucket_name)
except botocore.exceptions.ClientError:
if (self.aws_region == 'us-east-1'):
self.s3_client.create_bucket(Bucket=bucket_name)
else:
self.s3_client.create_bucket(Bucket=bucket_name, CreateBucketConfiguration={'Loc... |
'Copies src file to destination within a bucket.'
| def copy_on_s3(self, src_file_name, dst_file_name, bucket_name):
| try:
self.s3_client.head_bucket(Bucket=bucket_name)
except botocore.exceptions.ClientError as e:
error_code = int(e.response['Error']['Code'])
if (error_code == 404):
return False
copy_src = {'Bucket': bucket_name, 'Key': src_file_name}
try:
self.s3_client.cop... |
'Given a file name and a bucket, remove it from S3.
There\'s no reason to keep the file hosted on S3 once its been made into a Lambda function, so we can delete it from S3.
Returns True on success, False on failure.'
| def remove_from_s3(self, file_name, bucket_name):
| try:
self.s3_client.head_bucket(Bucket=bucket_name)
except botocore.exceptions.ClientError as e:
error_code = int(e.response['Error']['Code'])
if (error_code == 404):
return False
try:
self.s3_client.delete_object(Bucket=bucket_name, Key=file_name)
return ... |
'Given a bucket and key of a valid Lambda-zip, a function name and a handler, register that Lambda function.'
| def create_lambda_function(self, bucket, s3_key, function_name, handler, description='Zappa Deployment', timeout=30, memory_size=512, publish=True, vpc_config=None, dead_letter_config=None, runtime='python2.7', aws_environment_variables=None, aws_kms_key_arn=None):
| if (not vpc_config):
vpc_config = {}
if (not dead_letter_config):
dead_letter_config = {}
if (not self.credentials_arn):
self.get_credentials_arn()
if (not aws_environment_variables):
aws_environment_variables = {}
if (not aws_kms_key_arn):
aws_kms_key_arn = '... |
'Given a bucket and key of a valid Lambda-zip, a function name and a handler, update that Lambda function\'s code.'
| def update_lambda_function(self, bucket, s3_key, function_name, publish=True):
| print('Updating Lambda function code..')
response = self.lambda_client.update_function_code(FunctionName=function_name, S3Bucket=bucket, S3Key=s3_key, Publish=publish)
return response['FunctionArn']
|
'Given an existing function ARN, update the configuration variables.'
| def update_lambda_configuration(self, lambda_arn, function_name, handler, description='Zappa Deployment', timeout=30, memory_size=512, publish=True, vpc_config=None, runtime='python2.7', aws_environment_variables=None, aws_kms_key_arn=None):
| print('Updating Lambda function configuration..')
if (not vpc_config):
vpc_config = {}
if (not self.credentials_arn):
self.get_credentials_arn()
if (not aws_kms_key_arn):
aws_kms_key_arn = ''
if (not aws_environment_variables):
aws_environment_variables = {}
... |
'Directly invoke a named Lambda function with a payload.
Returns the response.'
| def invoke_lambda_function(self, function_name, payload, invocation_type='Event', log_type='Tail', client_context=None, qualifier=None):
| return self.lambda_client.invoke(FunctionName=function_name, InvocationType=invocation_type, LogType=log_type, Payload=payload)
|
'Rollback the lambda function code \'versions_back\' number of revisions.
Returns the Function ARN.'
| def rollback_lambda_function_version(self, function_name, versions_back=1, publish=True):
| response = self.lambda_client.list_versions_by_function(FunctionName=function_name)
if (len(response['Versions']) < (versions_back + 1)):
print('We do not have {} revisions. Aborting'.format(str(versions_back)))
return False
revisions = [int(revision['Version']) for revisio... |
'Returns the lambda function ARN, given a name
This requires the "lambda:GetFunction" role.'
| def get_lambda_function(self, function_name):
| response = self.lambda_client.get_function(FunctionName=function_name)
return response['Configuration']['FunctionArn']
|
'Simply returns the versions available for a Lambda function, given a function name.'
| def get_lambda_function_versions(self, function_name):
| try:
response = self.lambda_client.list_versions_by_function(FunctionName=function_name)
return response.get('Versions', [])
except Exception:
return []
|
'Given a function name, delete it from AWS Lambda.
Returns the response.'
| def delete_lambda_function(self, function_name):
| print('Deleting Lambda function..')
return self.lambda_client.delete_function(FunctionName=function_name)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.