code
string | signature
string | docstring
string | loss_without_docstring
float64 | loss_with_docstring
float64 | factor
float64 |
---|---|---|---|---|---|
attrs = vars(self).copy()
attrs.pop('_server_config')
attrs.pop('_fields')
attrs.pop('_meta')
if '_path_fields' in attrs:
attrs.pop('_path_fields')
return attrs | def get_values(self) | Return a copy of field values on the current object.
This method is almost identical to ``vars(self).copy()``. However,
only instance attributes that correspond to a field are included in
the returned dict.
:return: A dict mapping field names to user-provided values. | 4.916392 | 4.845102 | 1.014714 |
fields, values = self.get_fields(), self.get_values()
filtered_fields = fields.items()
if filter_fcn is not None:
filtered_fields = (
tpl for tpl in filtered_fields if filter_fcn(tpl[0], tpl[1])
)
json_dct = {}
for field_name, field in filtered_fields:
if field_name in values:
value = values[field_name]
if value is None:
json_dct[field_name] = None
# This conditions is needed because some times you get
# None on an OneToOneField what lead to an error
# on bellow condition, e.g., calling value.to_json_dict()
# when value is None
elif isinstance(field, OneToOneField):
json_dct[field_name] = value.to_json_dict()
elif isinstance(field, OneToManyField):
json_dct[field_name] = [
entity.to_json_dict() for entity in value
]
else:
json_dct[field_name] = to_json_serializable(value)
return json_dct | def to_json_dict(self, filter_fcn=None) | Create a dict with Entity properties for json encoding.
It can be overridden by subclasses for each standard serialization
doesn't work. By default it call _to_json_dict on OneToOne fields
and build a list calling the same method on each OneToMany object's
fields.
Fields can be filtered accordingly to 'filter_fcn'. This callable
receives field's name as first parameter and fields itself as second
parameter. It must return True if field's value should be included on
dict and False otherwise. If not provided field will not be filtered.
:type filter_fcn: callable
:return: dct | 3.157491 | 3.063004 | 1.030848 |
if not isinstance(other, type(self)):
return False
if filter_fcn is None:
def filter_unique(_, field):
return not field.unique
filter_fcn = filter_unique
return self.to_json_dict(filter_fcn) == other.to_json_dict(filter_fcn) | def compare(self, other, filter_fcn=None) | Returns True if properties can be compared in terms of eq.
Entity's Fields can be filtered accordingly to 'filter_fcn'.
This callable receives field's name as first parameter and field itself
as second parameter.
It must return True if field's value should be included on
comparison and False otherwise. If not provided field's marked as
unique will not be compared by default. 'id' and 'name' are examples of
unique fields commonly ignored. Check Entities fields for fields marked
with 'unique=True'
:param other: entity to compare
:param filter_fcn: callable
:return: boolean | 3.882099 | 3.205843 | 1.210945 |
return client.delete(
self.path(which='self'),
**self._server_config.get_client_kwargs()
) | def delete_raw(self) | Delete the current entity.
Make an HTTP DELETE call to ``self.path('base')``. Return the response.
:return: A ``requests.response`` object. | 18.537945 | 16.099415 | 1.151467 |
response = self.delete_raw()
response.raise_for_status()
if (synchronous is True and
response.status_code == http_client.ACCEPTED):
return _poll_task(response.json()['id'], self._server_config)
elif (response.status_code == http_client.NO_CONTENT or
(response.status_code == http_client.OK and
hasattr(response, 'content') and
not response.content.strip())):
# "The server successfully processed the request, but is not
# returning any content. Usually used as a response to a successful
# delete request."
return
return response.json() | def delete(self, synchronous=True) | Delete the current entity.
Call :meth:`delete_raw` and check for an HTTP 4XX or 5XX response.
Return either the JSON-decoded response or information about a
completed foreman task.
:param synchronous: A boolean. What should happen if the server returns
an HTTP 202 (accepted) status code? Wait for the task to complete
if ``True``. Immediately return a response otherwise.
:returns: A dict. Either the JSON-decoded response or information about
a foreman task.
:raises: ``requests.exceptions.HTTPError`` if the response has an HTTP
4XX or 5XX status code.
:raises: ``ValueError`` If an HTTP 202 response is received and the
response JSON can not be decoded.
:raises nailgun.entity_mixins.TaskTimedOutError: If an HTTP 202
response is received, ``synchronous is True`` and the task times
out. | 4.30932 | 3.884436 | 1.109381 |
path_type = self._meta.get('read_type', 'self')
return client.get(
self.path(path_type),
params=params,
**self._server_config.get_client_kwargs()
) | def read_raw(self, params=None) | Get information about the current entity.
Make an HTTP GET call to ``self.path('self')``. Return the response.
:return: A ``requests.response`` object. | 7.920486 | 7.493366 | 1.057 |
response = self.read_raw(params=params)
response.raise_for_status()
return response.json() | def read_json(self, params=None) | Get information about the current entity.
Call :meth:`read_raw`. Check the response status code, decode JSON and
return the decoded JSON as a dict.
:return: A dict. The server's response, with all JSON decoded.
:raises: ``requests.exceptions.HTTPError`` if the response has an HTTP
4XX or 5XX status code.
:raises: ``ValueError`` If the response JSON can not be decoded. | 3.938806 | 3.755682 | 1.048759 |
if entity is None:
entity = type(self)(self._server_config)
if attrs is None:
attrs = self.read_json(params=params)
if ignore is None:
ignore = set()
for field_name, field in entity.get_fields().items():
if field_name in ignore:
continue
if isinstance(field, OneToOneField):
entity_id = _get_entity_id(field_name, attrs)
if entity_id is None:
referenced_entity = None
else:
referenced_entity = field.entity(
self._server_config,
id=entity_id,
)
setattr(entity, field_name, referenced_entity)
elif isinstance(field, OneToManyField):
referenced_entities = [
field.entity(self._server_config, id=entity_id)
for entity_id
in _get_entity_ids(field_name, attrs)
]
setattr(entity, field_name, referenced_entities)
else:
setattr(entity, field_name, attrs[field_name])
return entity | def read(self, entity=None, attrs=None, ignore=None, params=None) | Get information about the current entity.
1. Create a new entity of type ``type(self)``.
2. Call :meth:`read_json` and capture the response.
3. Populate the entity with the response.
4. Return the entity.
Step one is skipped if the ``entity`` argument is specified. Step two
is skipped if the ``attrs`` argument is specified. Step three is
modified by the ``ignore`` argument.
All of an entity's one-to-one and one-to-many relationships are
populated with objects of the correct type. For example, if
``SomeEntity.other_entity`` is a one-to-one relationship, this should
return ``True``::
isinstance(
SomeEntity(id=N).read().other_entity,
nailgun.entity_mixins.Entity
)
Additionally, both of these commands should succeed::
SomeEntity(id=N).read().other_entity.id
SomeEntity(id=N).read().other_entity.read().other_attr
In the example above, ``other_entity.id`` is the **only** attribute
with a meaningful value. Calling ``other_entity.read`` populates the
remaining entity attributes.
:param nailgun.entity_mixins.Entity entity: The object to be populated
and returned. An object of type ``type(self)`` by default.
:param attrs: A dict. Data used to populate the object's attributes.
The response from
:meth:`nailgun.entity_mixins.EntityReadMixin.read_json` by default.
:param ignore: A set of attributes which should not be read from the
server. This is mainly useful for attributes like a password which
are not returned.
:return: An instance of type ``type(self)``.
:rtype: nailgun.entity_mixins.Entity | 2.129193 | 1.942143 | 1.096311 |
for field_name, field in self.get_fields().items():
if field.required and not hasattr(self, field_name):
# Most `gen_value` methods return a value such as an integer,
# string or dictionary, but OneTo{One,Many}Field.gen_value
# returns the referenced class.
if hasattr(field, 'default'):
value = field.default
elif hasattr(field, 'choices'):
value = gen_choice(field.choices)
elif isinstance(field, OneToOneField):
value = field.gen_value()(self._server_config).create(True)
elif isinstance(field, OneToManyField):
value = [
field.gen_value()(self._server_config).create(True)
]
else:
value = field.gen_value()
setattr(self, field_name, value) | def create_missing(self) | Automagically populate all required instance attributes.
Iterate through the set of all required class
:class:`nailgun.entity_fields.Field` defined on ``type(self)`` and
create a corresponding instance attribute if none exists. Subclasses
should override this method if there is some relationship between two
required fields.
:return: Nothing. This method relies on side-effects. | 4.228458 | 4.137047 | 1.022096 |
if create_missing is None:
create_missing = CREATE_MISSING
if create_missing is True:
self.create_missing()
return client.post(
self.path('base'),
self.create_payload(),
**self._server_config.get_client_kwargs()
) | def create_raw(self, create_missing=None) | Create an entity.
Possibly call :meth:`create_missing`. Then make an HTTP POST call to
``self.path('base')``. The request payload consists of whatever is
returned by :meth:`create_payload`. Return the response.
:param create_missing: Should :meth:`create_missing` be called? In
other words, should values be generated for required, empty fields?
Defaults to :data:`nailgun.entity_mixins.CREATE_MISSING`.
:return: A ``requests.response`` object. | 5.038321 | 3.426091 | 1.470574 |
response = self.create_raw(create_missing)
response.raise_for_status()
return response.json() | def create_json(self, create_missing=None) | Create an entity.
Call :meth:`create_raw`. Check the response status code, decode JSON
and return the decoded JSON as a dict.
:return: A dict. The server's response, with all JSON decoded.
:raises: ``requests.exceptions.HTTPError`` if the response has an HTTP
4XX or 5XX status code.
:raises: ``ValueError`` If the response JSON can not be decoded. | 4.612682 | 3.847665 | 1.198826 |
values = self.get_values()
if fields is not None:
values = {field: values[field] for field in fields}
return _payload(self.get_fields(), values) | def update_payload(self, fields=None) | Create a payload of values that can be sent to the server.
By default, this method behaves just like :func:`_payload`. However,
one can also specify a certain set of fields that should be returned.
For more information, see :meth:`update`. | 3.703327 | 3.525854 | 1.050335 |
return client.put(
self.path('self'),
self.update_payload(fields),
**self._server_config.get_client_kwargs()
) | def update_raw(self, fields=None) | Update the current entity.
Make an HTTP PUT call to ``self.path('base')``. The request payload
consists of whatever is returned by :meth:`update_payload`. Return the
response.
:param fields: See :meth:`update`.
:return: A ``requests.response`` object. | 9.944304 | 7.577148 | 1.312407 |
response = self.update_raw(fields)
response.raise_for_status()
return response.json() | def update_json(self, fields=None) | Update the current entity.
Call :meth:`update_raw`. Check the response status code, decode JSON
and return the decoded JSON as a dict.
:param fields: See :meth:`update`.
:return: A dict consisting of the decoded JSON in the server's
response.
:raises: ``requests.exceptions.HTTPError`` if the response has an HTTP
4XX or 5XX status code.
:raises: ``ValueError`` If the response JSON can not be decoded. | 4.462443 | 4.06062 | 1.098956 |
if fields is None:
fields = set(self.get_values().keys())
if query is None:
query = {}
payload = {}
fields_dict = self.get_fields()
for field in fields:
value = getattr(self, field)
if isinstance(fields_dict[field], OneToOneField):
payload[field + '_id'] = value.id
elif isinstance(fields_dict[field], OneToManyField):
payload[field + '_ids'] = [entity.id for entity in value]
else:
payload[field] = value
payload.update(query)
return payload | def search_payload(self, fields=None, query=None) | Create a search query.
Do the following:
1. Generate a search query. By default, all values returned by
:meth:`nailgun.entity_mixins.Entity.get_values` are used. If
``fields`` is specified, only the named values are used.
2. Merge ``query`` in to the generated search query.
3. Return the result.
The rules for generating a search query can be illustrated by example.
Let's say that we have an entity with an
:class:`nailgun.entity_fields.IntegerField`, a
:class:`nailgun.entity_fields.OneToOneField` and a
:class:`nailgun.entity_fields.OneToManyField`::
>>> some_entity = SomeEntity(id=1, one=2, many=[3, 4])
>>> fields = some_entity.get_fields()
>>> isinstance(fields['id'], IntegerField)
True
>>> isinstance(fields['one'], OneToOneField)
True
>>> isinstance(fields['many'], OneToManyField)
True
This method appends "_id" and "_ids" on to the names of each
``OneToOneField`` and ``OneToManyField``, respectively::
>>> some_entity.search_payload()
{'id': 1, 'one_id': 2, 'many_ids': [3, 4]}
By default, all fields are used. But you can specify a set of field
names to use::
>>> some_entity.search_payload({'id'})
{'id': 1}
>>> some_entity.search_payload({'one'})
{'one_id': 2}
>>> some_entity.search_payload({'id', 'one'})
{'id': 1, 'one_id': 2}
If a ``query`` is specified, it is merged in to the generated query::
>>> some_entity.search_payload(query={'id': 5})
{'id': 5, 'one_id': 2, 'many_ids': [3, 4]}
>>> some_entity.search_payload(query={'per_page': 1000})
{'id': 1, 'one_id': 2, 'many_ids': [3, 4], 'per_page': 1000}
.. WARNING:: This method currently generates an extremely naive search
query that will be wrong in many cases. In addition, Satellite
currently accepts invalid search queries without complaint. Make
sure to check the API documentation for your version of Satellite
against what this method produces.
:param fields: See :meth:`search`.
:param query: See :meth:`search`.
:returns: A dict that can be encoded as JSON and used in a search. | 2.365322 | 2.025482 | 1.167782 |
return client.get(
self.path('base'),
data=self.search_payload(fields, query),
**self._server_config.get_client_kwargs()
) | def search_raw(self, fields=None, query=None) | Search for entities.
Make an HTTP GET call to ``self.path('base')``. Return the response.
.. WARNING:: Subclasses that override this method should not alter the
``fields`` or ``query`` arguments. (However, subclasses that
override this method may still alter the server's response.) See
:meth:`search_normalize` for details.
:param fields: See :meth:`search`.
:param query: See :meth:`search`.
:return: A ``requests.response`` object. | 8.579811 | 6.915166 | 1.240724 |
response = self.search_raw(fields, query)
response.raise_for_status()
return response.json() | def search_json(self, fields=None, query=None) | Search for entities.
Call :meth:`search_raw`. Check the response status code, decode JSON
and return the decoded JSON as a dict.
.. WARNING:: Subclasses that override this method should not alter the
``fields`` or ``query`` arguments. (However, subclasses that
override this method may still alter the server's response.) See
:meth:`search_normalize` for details.
:param fields: See :meth:`search`.
:param query: See :meth:`search`.
:return: A dict. The server's response, with all JSON decoded.
:raises: ``requests.exceptions.HTTPError`` if the response has an HTTP
4XX or 5XX status code.
:raises: ``ValueError`` If the response JSON can not be decoded. | 3.570166 | 4.044515 | 0.882718 |
fields = self.get_fields()
normalized = []
for result in results:
# For each field that we know about, copy the corresponding field
# from the server's search result. If any extra attributes are
# copied over, Entity.__init__ will raise a NoSuchFieldError.
# Examples of problematic results from server:
#
# * organization_id (denormalized OneToOne. see above)
# * organizations, organization_ids (denormalized OneToMany. above)
# * updated_at, created_at (these may be handled in the future)
# * sp_subnet (Host.sp_subnet is an undocumented field)
#
attrs = {}
for field_name, field in fields.items():
if isinstance(field, OneToOneField):
try:
attrs[field_name] = _get_entity_id(field_name, result)
except MissingValueError:
pass
elif isinstance(field, OneToManyField):
try:
attrs[field_name] = _get_entity_ids(field_name, result)
except MissingValueError:
pass
else:
try:
attrs[field_name] = result[field_name]
except KeyError:
pass
normalized.append(attrs)
return normalized | def search_normalize(self, results) | Normalize search results so they can be used to create new entities.
See :meth:`search` for an example of how to use this method. Here's a
simplified example::
results = self.search_json()
results = self.search_normalize(results)
entity = SomeEntity(some_cfg, **results[0])
At this time, it is possible to parse all search results without
knowing what search query was sent to the server. However, it is
possible that certain responses can only be parsed if the search query
is known. If that is the case, this method will be given a new
``payload`` argument, where ``payload`` is the query sent to the
server.
As a precaution, the following is higly recommended:
* :meth:`search` may alter ``fields`` and ``query`` at will.
* :meth:`search_payload` may alter ``fields`` and ``query`` in an
idempotent manner.
* No other method should alter ``fields`` or ``query``.
:param results: A list of dicts, where each dict is a set of attributes
for one entity. The contents of these dicts are as is returned from
the server.
:returns: A list of dicts, where each dict is a set of attributes for
one entity. The contents of these dicts have been normalized and
can be used to instantiate entities. | 5.118618 | 5.050902 | 1.013407 |
# Goals:
#
# * Be tolerant of missing values. It's reasonable for the server to
# return an incomplete set of attributes for each search result.
# * Use as many returned values as possible. There's no point in
# letting returned data go to waste. This implies that we must…
# * …parse irregular server responses. This includes pluralized field
# names, misnamed attributes (e.g. BZ 1233245) and weirdly named
# fields (e.g. Media.path_).
#
results = self.search_json(fields, query)['results']
results = self.search_normalize(results)
entities = [
type(self)(self._server_config, **result)
for result in results
]
if filters is not None:
entities = self.search_filter(entities, filters)
return entities | def search(self, fields=None, query=None, filters=None) | Search for entities.
At its simplest, this method searches for all entities of a given kind.
For example, to ask for all
:class:`nailgun.entities.LifecycleEnvironment` entities::
LifecycleEnvironment().search()
Values on an entity are used to generate a search query, and the
``fields`` argument can be used to specify which fields should be used
when generating a search query::
lc_env = LifecycleEnvironment(name='foo', organization=1)
results = lc_env.search() # Search by name and organization.
results = lc_env.search({'name', 'organization'}) # Same.
results = lc_env.search({'name'}) # Search by name.
results = lc_env.search({'organization'}) # Search by organization
results = lc_env.search(set()) # Search for all lifecycle envs.
results = lc_env.search({'library'}) # Error!
In some cases, the simple search queries that can be generated by
NailGun are not sufficient. In this case, you can pass in a raw search
query instead. For example, to search for all lifecycle environments
with a name of 'foo'::
LifecycleEnvironment().search(query={'search': 'name="foo"'})
The example above is rather pointless: it is easier and more concise to
use a generated query. But — and this is a **very** important "but" —
the manual search query is melded in to the generated query. This can
be used to great effect::
LifecycleEnvironment(name='foo').search(query={'per_page': 50})
For examples of what the final search queries look like, see
:meth:`search_payload`. (That method also accepts the ``fields`` and
``query`` arguments.)
In some cases, the server's search facilities may be insufficient, or
it may be inordinately difficult to craft a search query. In this case,
you can filter search results locally. For example, to ask the server
for a list of all lifecycle environments and then locally search
through the results for the lifecycle environment named "foo"::
LifecycleEnvironment().search(filters={'name': 'foo'})
Be warned that filtering locally can be **very** slow. NailGun must
``read()`` every single entity returned by the server before filtering
results. This is because the values used in the filtering process may
not have been returned by the server in the initial response to the
search.
The fact that all entities are read when ``filters`` is specified can
be used to great effect. For example, this search returns a fully
populated list of every single lifecycle environment::
LifecycleEnvironment().search(filters={})
:param fields: A set naming which fields should be used when generating
a search query. If ``None``, all values on the entity are used. If
an empty set, no values are used.
:param query: A dict containing a raw search query. This is melded in
to the generated search query like so: ``{generated:
query}.update({manual: query})``.
:param filters: A dict. Used to filter search results locally.
:return: A list of entities, all of type ``type(self)``. | 10.671101 | 10.469107 | 1.019294 |
# Check to make sure all arguments are sane.
if len(entities) == 0:
return entities
fields = entities[0].get_fields() # assume all entities are identical
if not set(filters).issubset(fields):
raise NoSuchFieldError(
'Valid filters are {0}, but received {1} instead.'
.format(fields.keys(), filters.keys())
)
for field_name in filters:
if isinstance(fields[field_name], (OneToOneField, OneToManyField)):
raise NotImplementedError(
'Search results cannot (yet?) be locally filtered by '
'`OneToOneField`s and `OneToManyField`s. {0} is a {1}.'
.format(field_name, type(fields[field_name]).__name__)
)
# The arguments are sane. Filter away!
filtered = [entity.read() for entity in entities] # don't alter inputs
for field_name, field_value in filters.items():
filtered = [
entity for entity in filtered
if getattr(entity, field_name) == field_value
]
return filtered | def search_filter(entities, filters) | Read all ``entities`` and locally filter them.
This method can be used like so::
entities = EntitySearchMixin(entities, {'name': 'foo'})
In this example, only entities where ``entity.name == 'foo'`` holds
true are returned. An arbitrary number of field names and values may be
provided as filters.
.. NOTE:: This method calls :meth:`EntityReadMixin.read`. As a result,
this method only works when called on a class that also inherits
from :class:`EntityReadMixin`.
:param entities: A list of :class:`Entity` objects. All list items
should be of the same type.
:param filters: A dict in the form ``{field_name: field_value, …}``.
:raises nailgun.entity_mixins.NoSuchFieldError: If any of the fields
named in ``filters`` do not exist on the entities being filtered.
:raises: ``NotImplementedError`` If any of the fields named in
``filters`` are a :class:`nailgun.entity_fields.OneToOneField` or
:class:`nailgun.entity_fields.OneToManyField`. | 3.913562 | 3.267854 | 1.197594 |
auth = ('admin', 'changeme')
base_url = 'https://sat1.example.com'
organization_name = 'junk org'
args = {'auth': auth, 'headers': {'content-type': 'application/json'}}
response = requests.post(
base_url + '/katello/api/v2/organizations',
json.dumps({
'name': organization_name,
'organization': {'name': organization_name},
}),
**args
)
response.raise_for_status()
pprint(response.json())
response = requests.delete(
'{0}/katello/api/v2/organizations/{1}'.format(
base_url,
response.json()['id'],
),
**args
)
response.raise_for_status() | def main() | Create an organization, print out its attributes and delete it. | 3.084048 | 2.800755 | 1.101149 |
for config_dir in BaseDirectory.load_config_paths(xdg_config_dir):
path = join(config_dir, xdg_config_file)
if isfile(path):
return path
raise ConfigFileError(
'No configuration files could be located after searching for a file '
'named "{0}" in the standard XDG configuration paths, such as '
'"~/.config/{1}/".'.format(xdg_config_file, xdg_config_dir)
) | def _get_config_file_path(xdg_config_dir, xdg_config_file) | Search ``XDG_CONFIG_DIRS`` for a config file and return the first found.
Search each of the standard XDG configuration directories for a
configuration file. Return as soon as a configuration file is found. Beware
that by the time client code attempts to open the file, it may be gone or
otherwise inaccessible.
:param xdg_config_dir: A string. The name of the directory that is suffixed
to the end of each of the ``XDG_CONFIG_DIRS`` paths.
:param xdg_config_file: A string. The name of the configuration file that
is being searched for.
:returns: A ``str`` path to a configuration file.
:raises nailgun.config.ConfigFileError: When no configuration file can be
found. | 3.887163 | 3.581171 | 1.085445 |
if path is None:
path = _get_config_file_path(
cls._xdg_config_dir,
cls._xdg_config_file
)
cls._file_lock.acquire()
try:
with open(path) as config_file:
config = json.load(config_file)
del config[label]
with open(path, 'w') as config_file:
json.dump(config, config_file)
finally:
cls._file_lock.release() | def delete(cls, label='default', path=None) | Delete a server configuration.
This method is thread safe.
:param label: A string. The configuration identified by ``label`` is
deleted.
:param path: A string. The configuration file to be manipulated.
Defaults to what is returned by
:func:`nailgun.config._get_config_file_path`.
:returns: ``None`` | 2.110484 | 2.342276 | 0.90104 |
if path is None:
path = _get_config_file_path(
cls._xdg_config_dir,
cls._xdg_config_file
)
with open(path) as config_file:
return cls(**json.load(config_file)[label]) | def get(cls, label='default', path=None) | Read a server configuration from a configuration file.
:param label: A string. The configuration identified by ``label`` is
read.
:param path: A string. The configuration file to be manipulated.
Defaults to what is returned by
:func:`nailgun.config._get_config_file_path`.
:returns: A brand new :class:`nailgun.config.BaseServerConfig` object
whose attributes have been populated as appropriate.
:rtype: BaseServerConfig | 3.17577 | 3.251267 | 0.976779 |
if path is None:
path = _get_config_file_path(
cls._xdg_config_dir,
cls._xdg_config_file
)
with open(path) as config_file:
# keys() returns a list in Python 2 and a view in Python 3.
return tuple(json.load(config_file).keys()) | def get_labels(cls, path=None) | Get all server configuration labels.
:param path: A string. The configuration file to be manipulated.
Defaults to what is returned by
:func:`nailgun.config._get_config_file_path`.
:returns: Server configuration labels, where each label is a string. | 4.462307 | 4.423465 | 1.008781 |
# What will we write out?
cfg = vars(self)
if 'version' in cfg: # pragma: no cover
cfg['version'] = str(cfg['version'])
# Where is the file we're writing to?
if path is None:
path = join(
BaseDirectory.save_config_path(self._xdg_config_dir),
self._xdg_config_file
)
self._file_lock.acquire()
try:
# Either read an existing config or make an empty one. Then update
# the config and write it out.
try:
with open(path) as config_file:
config = json.load(config_file)
except IOError: # pragma: no cover
config = {}
config[label] = cfg
with open(path, 'w') as config_file:
json.dump(config, config_file)
finally:
self._file_lock.release() | def save(self, label='default', path=None) | Save the current connection configuration to a file.
This method is thread safe.
:param label: A string. An identifier for the current configuration.
This allows multiple configurations with unique labels to be saved
in a single file. If a configuration identified by ``label``
already exists in the destination configuration file, it is
replaced.
:param path: A string. The configuration file to be manipulated. By
default, an XDG-compliant configuration file is used. A
configuration file is created if one does not exist already.
:returns: ``None`` | 3.363168 | 3.45257 | 0.974106 |
config = vars(self).copy()
config.pop('url')
config.pop('version', None)
return config | def get_client_kwargs(self) | Get kwargs for use with the methods in :mod:`nailgun.client`.
This method returns a dict of attributes that can be unpacked and used
as kwargs via the ``**`` operator. For example::
cfg = ServerConfig.get()
client.get(cfg.url + '/api/v2', **cfg.get_client_kwargs())
This method is useful because client code may not know which attributes
should be passed from a ``ServerConfig`` object to one of the
``nailgun.client`` functions. Consider that the example above could
also be written like this::
cfg = ServerConfig.get()
client.get(cfg.url + '/api/v2', auth=cfg.auth, verify=cfg.verify)
But this latter approach is more fragile. It will break if ``cfg`` does
not have an ``auth`` or ``verify`` attribute. | 7.436101 | 11.356567 | 0.654784 |
config = super(ServerConfig, cls).get(label, path)
if hasattr(config, 'auth') and isinstance(config.auth, list):
config.auth = tuple(config.auth)
return config | def get(cls, label='default', path=None) | Read a server configuration from a configuration file.
This method extends :meth:`nailgun.config.BaseServerConfig.get`. Please
read up on that method before trying to understand this one.
The entity classes rely on the requests library to be a transport
mechanism. The methods provided by that library, such as ``get`` and
``post``, accept an ``auth`` argument. That argument must be a tuple:
Auth tuple to enable Basic/Digest/Custom HTTP Auth.
However, the JSON decoder does not recognize a tuple as a type, and
represents sequences of elements as a tuple. Compensate for that by
converting ``auth`` to a two element tuple if it is a two element list.
This override is done here, and not in the base class, because the base
class may be extracted out into a separate library and used in other
contexts. In those contexts, the presence of a list may not matter or
may be desirable. | 3.41249 | 2.743779 | 1.243719 |
return gen_string(
gen_choice(self.str_type),
gen_integer(self.min_len, self.max_len)
) | def gen_value(self) | Return a value suitable for a :class:`StringField`. | 5.797905 | 5.306182 | 1.09267 |
server_config = ServerConfig(
auth=('admin', 'changeme'), # Use these credentials…
url='https://sat1.example.com', # …to talk to this server.
)
org = Organization(server_config, name='junk org').create()
pprint(org.get_values()) # e.g. {'name': 'junk org', …}
org.delete() | def main() | Create an organization, print out its attributes and delete it. | 9.998639 | 7.705307 | 1.29763 |
if 'files' in kwargs:
return # requests will automatically set the content-type
headers = kwargs.pop('headers', {})
headers.setdefault('content-type', 'application/json')
kwargs['headers'] = headers | def _set_content_type(kwargs) | If the 'content-type' header is unset, set it to 'applcation/json'.
The 'content-type' will not be set if doing a file upload as requests will
automatically set it.
:param kwargs: A ``dict``. The keyword args supplied to :func:`request` or
one of the convenience functions like it.
:return: Nothing. ``kwargs`` is modified in-place. | 3.982827 | 4.035192 | 0.987023 |
logger.debug(
'Making HTTP %s request to %s with %s, %s and %s.',
method,
url,
'options {0}'.format(kwargs) if len(kwargs) > 0 else 'no options',
'params {0}'.format(params) if params else 'no params',
'data {0}'.format(data) if data is not None else 'no data',
) | def _log_request(method, url, kwargs, data=None, params=None) | Log out information about the arguments given.
The arguments provided to this function correspond to the arguments that
one can pass to ``requests.request``.
:return: Nothing is returned. | 2.786044 | 3.150456 | 0.88433 |
message = u'Received HTTP {0} response: {1}'.format(
response.status_code,
response.text
)
if response.status_code >= 400: # pragma: no cover
logger.warning(message)
else:
logger.debug(message) | def _log_response(response) | Log out information about a ``Request`` object.
After calling ``requests.request`` or one of its convenience methods, the
object returned can be passed to this method. If done, information about
the object returned is logged.
:return: Nothing is returned. | 2.794969 | 3.394449 | 0.823394 |
_set_content_type(kwargs)
if _content_type_is_json(kwargs) and kwargs.get('data') is not None:
kwargs['data'] = dumps(kwargs['data'])
_log_request(method, url, kwargs)
response = requests.request(method, url, **kwargs)
_log_response(response)
return response | def request(method, url, **kwargs) | A wrapper for ``requests.request``. | 2.402438 | 2.51248 | 0.956202 |
_set_content_type(kwargs)
if _content_type_is_json(kwargs) and kwargs.get('data') is not None:
kwargs['data'] = dumps(kwargs['data'])
_log_request('HEAD', url, kwargs)
response = requests.head(url, **kwargs)
_log_response(response)
return response | def head(url, **kwargs) | A wrapper for ``requests.head``. | 2.651797 | 2.752821 | 0.963301 |
_set_content_type(kwargs)
if _content_type_is_json(kwargs) and data is not None:
data = dumps(data)
_log_request('POST', url, kwargs, data)
response = requests.post(url, data, json, **kwargs)
_log_response(response)
return response | def post(url, data=None, json=None, **kwargs) | A wrapper for ``requests.post``. | 2.965312 | 3.084118 | 0.961478 |
_set_content_type(kwargs)
if _content_type_is_json(kwargs) and data is not None:
data = dumps(data)
_log_request('PUT', url, kwargs, data)
response = requests.put(url, data, **kwargs)
_log_response(response)
return response | def put(url, data=None, **kwargs) | A wrapper for ``requests.put``. Sends a PUT request. | 2.802239 | 2.916833 | 0.960713 |
server_configs = ServerConfig.get('sat1'), ServerConfig.get('sat2')
for server_config in server_configs:
org = Organization(server_config).search(
query={'search': 'name="Default_Organization"'}
)[0]
# The LDAP authentication source with an ID of 1 is internal. It is
# nearly guaranteed to exist and be functioning.
user = User(
server_config,
auth_source=1, # or: AuthSourceLDAP(server_config, id=1),
login='Alice',
mail='[email protected]',
organization=[org],
password='hackme',
).create()
pprint(user.get_values()) | def main() | Create an identical user account on a pair of satellites. | 10.425749 | 9.527923 | 1.094231 |
response.raise_for_status()
if synchronous is True and response.status_code == ACCEPTED:
return ForemanTask(
server_config, id=response.json()['id']).poll(timeout=timeout)
if response.status_code == NO_CONTENT:
return
if 'application/json' in response.headers.get('content-type', '').lower():
return response.json()
elif isinstance(response.content, bytes):
return response.content.decode('utf-8')
else:
return response.content | def _handle_response(response, server_config, synchronous=False, timeout=None) | Handle a server's response in a typical fashion.
Do the following:
1. Check the server's response for an HTTP status code indicating an error.
2. Poll the server for a foreman task to complete if an HTTP 202 (accepted)
status code is returned and ``synchronous is True``.
3. Immediately return if an HTTP "NO CONTENT" response is received.
4. Determine what type of the content returned from server. Depending on
the type method should return server's response, with all JSON decoded
or just response content itself.
:param response: A response object as returned by one of the functions in
:mod:`nailgun.client` or the requests library.
:param server_config: A `nailgun.config.ServerConfig` object.
:param synchronous: Should this function poll the server?
:param timeout: Maximum number of seconds to wait until timing out.
Defaults to ``nailgun.entity_mixins.TASK_TIMEOUT``. | 2.958675 | 2.723063 | 1.086525 |
organizations = Organization(server_config).search(
query={u'search': u'label={0}'.format(label)}
)
if len(organizations) != 1:
raise APIResponseError(
u'Could not find exactly one organization with label "{0}". '
u'Actual search results: {1}'.format(label, organizations)
)
return organizations[0].read() | def _get_org(server_config, label) | Find an :class:`nailgun.entities.Organization` object.
:param nailgun.config.ServerConfig server_config: The server that should be
searched.
:param label: A string. The label of the organization to find.
:raises APIResponseError: If exactly one organization is not found.
:returns: An :class:`nailgun.entities.Organization` object. | 4.742049 | 4.200658 | 1.128883 |
if which in (
'add_subscriptions',
'content_override',
'copy',
'host_collections',
'product_content',
'releases',
'remove_subscriptions',
'subscriptions'):
return '{0}/{1}'.format(
super(ActivationKey, self).path(which='self'),
which
)
return super(ActivationKey, self).path(which) | def path(self, which=None) | Extend ``nailgun.entity_mixins.Entity.path``.
The format of the returned path depends on the value of ``which``:
add_subscriptions
/activation_keys/<id>/add_subscriptions
copy
/activation_keys/<id>/copy
content_override
/activation_keys/<id>/content_override
product_content
/activation_keys/<id>/product_content
releases
/activation_keys/<id>/releases
remove_subscriptions
/activation_keys/<id>/remove_subscriptions
subscriptions
/activation_keys/<id>/subscriptions
``super`` is called otherwise. | 7.398473 | 3.139365 | 2.356678 |
if which in ('download_html',):
return '{0}/{1}'.format(
super(ArfReport, self).path(which='self'),
which
)
return super(ArfReport, self).path(which) | def path(self, which=None) | Extend ``nailgun.entity_mixins.Entity.path``.
The format of the returned path depends on the value of ``which``:
download_html
/api/compliance/arf_reports/:id/download_html
Otherwise, call ``super``. | 7.54068 | 3.748351 | 2.011733 |
super(AuthSourceLDAP, self).create_missing()
if getattr(self, 'onthefly_register', False) is True:
for field in (
'account_password',
'attr_firstname',
'attr_lastname',
'attr_login',
'attr_mail'):
if not hasattr(self, field):
setattr(self, field, self._fields[field].gen_value()) | def create_missing(self) | Possibly set several extra instance attributes.
If ``onthefly_register`` is set and is true, set the following instance
attributes:
* account_password
* account_firstname
* account_lastname
* attr_login
* attr_mail | 5.354664 | 3.34205 | 1.60221 |
if attrs is None:
attrs = self.update_json([])
if ignore is None:
ignore = set()
ignore.add('account_password')
return super(AuthSourceLDAP, self).read(entity, attrs, ignore, params) | def read(self, entity=None, attrs=None, ignore=None, params=None) | Do not read the ``account_password`` attribute. Work around a bug.
For more information, see `Bugzilla #1243036
<https://bugzilla.redhat.com/show_bug.cgi?id=1243036>`_. | 5.369835 | 4.165333 | 1.289173 |
if which and which.startswith('content_'):
return '{0}/content/{1}'.format(
super(Capsule, self).path(which='self'),
which.split('content_')[1]
)
return super(Capsule, self).path(which) | def path(self, which=None) | Extend ``nailgun.entity_mixins.Entity.path``.
The format of the returned path depends on the value of ``which``:
content_lifecycle_environments
/capsules/<id>/content/lifecycle_environments
content_sync
/capsules/<id>/content/sync
``super`` is called otherwise. | 4.842814 | 3.475649 | 1.393355 |
if which == 'facts':
return '{0}/{1}'.format(
super(DiscoveredHost, self).path(which='base'),
which
)
return super(DiscoveredHost, self).path(which) | def path(self, which=None) | Extend ``nailgun.entity_mixins.Entity.path``.
The format of the returned path depends on the value of ``which``:
facts
/discovered_hosts/facts
``super`` is called otherwise. | 6.455003 | 4.056509 | 1.591271 |
payload = super(DiscoveryRule, self).create_payload()
if 'search_' in payload:
payload['search'] = payload.pop('search_')
return {u'discovery_rule': payload} | def create_payload(self) | Wrap submitted data within an extra dict.
For more information, see `Bugzilla #1151220
<https://bugzilla.redhat.com/show_bug.cgi?id=1151220>`_.
In addition, rename the ``search_`` field to ``search``. | 6.142221 | 4.432117 | 1.385844 |
return type(self)(
self._server_config,
id=self.create_json(create_missing)['id'],
).read() | def create(self, create_missing=None) | Do extra work to fetch a complete set of attributes for this entity.
For more information, see `Bugzilla #1381129
<https://bugzilla.redhat.com/show_bug.cgi?id=1381129>`_. | 14.321836 | 12.972054 | 1.104053 |
if attrs is None:
attrs = self.read_json()
attrs['search_'] = attrs.pop('search')
# Satellite doesn't return this attribute. See BZ 1257255.
attr = 'max_count'
if ignore is None:
ignore = set()
if attr not in ignore:
# We cannot call `self.update_json([])`, as an ID might not be
# present on self. However, `attrs` is guaranteed to have an ID.
attrs[attr] = DiscoveryRule(
self._server_config,
id=attrs['id'],
).update_json([])[attr]
return super(DiscoveryRule, self).read(entity, attrs, ignore, params) | def read(self, entity=None, attrs=None, ignore=None, params=None) | Work around a bug. Rename ``search`` to ``search_``.
For more information on the bug, see `Bugzilla #1257255
<https://bugzilla.redhat.com/show_bug.cgi?id=1257255>`_. | 7.666526 | 5.802777 | 1.321182 |
payload = super(DiscoveryRule, self).update_payload(fields)
if 'search_' in payload:
payload['search'] = payload.pop('search_')
return {u'discovery_rule': payload} | def update_payload(self, fields=None) | Wrap submitted data within an extra dict. | 5.16135 | 4.907963 | 1.051628 |
return DockerComputeResource(
self._server_config,
id=self.create_json(create_missing)['id'],
).read() | def create(self, create_missing=None) | Do extra work to fetch a complete set of attributes for this entity.
For more information, see `Bugzilla #1223540
<https://bugzilla.redhat.com/show_bug.cgi?id=1223540>`_. | 19.515799 | 20.028908 | 0.974382 |
if attrs is None:
attrs = self.read_json()
if ignore is None:
ignore = set()
ignore.add('password')
if 'email' not in attrs and 'email' not in ignore:
response = client.put(
self.path('self'),
{},
**self._server_config.get_client_kwargs()
)
response.raise_for_status()
attrs['email'] = response.json().get('email')
return super(DockerComputeResource, self).read(
entity, attrs, ignore, params) | def read(self, entity=None, attrs=None, ignore=None, params=None) | Do extra work to fetch a complete set of attributes for this entity.
For more information, see `Bugzilla #1223540
<https://bugzilla.redhat.com/show_bug.cgi?id=1223540>`_.
Also, do not try to read the "password" field. No value is returned for
the field, for obvious reasons. | 4.039702 | 3.954247 | 1.021611 |
if entity is None:
entity = type(self)(
self._server_config,
usergroup=self.usergroup, # pylint:disable=no-member
)
if ignore is None:
ignore = set()
ignore.add('usergroup')
if attrs is None:
attrs = self.read_json()
attrs['auth_source'] = attrs.pop('auth_source_ldap')
return super(ExternalUserGroup, self).read(entity, attrs, ignore, params) | def read(self, entity=None, attrs=None, ignore=None, params=None) | Ignore usergroup from read and alter auth_source_ldap with auth_source | 4.367484 | 3.36751 | 1.296948 |
if which == 'refresh':
return '{0}/{1}'.format(
super(ExternalUserGroup, self).path(which='self'),
which
)
return super(ExternalUserGroup, self).path(which) | def path(self, which=None) | Extend ``nailgun.entity_mixins.Entity.path``.
The format of the returned path depends on the value of ``which``:
refresh
/api/usergroups/:usergroup_id/external_usergroups/:id/refresh | 6.093859 | 4.425171 | 1.37709 |
payload = super(ConfigTemplate, self).create_payload()
if 'template_combinations' in payload:
payload['template_combinations_attributes'] = payload.pop(
'template_combinations')
return {u'config_template': payload} | def create_payload(self) | Wrap submitted data within an extra dict.
For more information, see `Bugzilla #1151220
<https://bugzilla.redhat.com/show_bug.cgi?id=1151220>`_. | 4.809572 | 5.076892 | 0.947346 |
payload = super(ConfigTemplate, self).update_payload(fields)
if 'template_combinations' in payload:
payload['template_combinations_attributes'] = payload.pop(
'template_combinations')
return {u'config_template': payload} | def update_payload(self, fields=None) | Wrap submitted data within an extra dict. | 4.126174 | 4.074001 | 1.012806 |
if which in ('build_pxe_default', 'clone', 'revision'):
prefix = 'self' if which == 'clone' else 'base'
return '{0}/{1}'.format(
super(ConfigTemplate, self).path(prefix),
which
)
return super(ConfigTemplate, self).path(which) | def path(self, which=None) | Extend ``nailgun.entity_mixins.Entity.path``.
The format of the returned path depends on the value of ``which``:
build_pxe_default
/config_templates/build_pxe_default
clone
/config_templates/clone
revision
/config_templates/revision
``super`` is called otherwise. | 7.099232 | 3.159279 | 2.247105 |
if entity is None:
entity = TemplateInput(self._server_config, template=self.template)
if ignore is None:
ignore = set()
ignore.add('advanced')
return super(TemplateInput, self).read(entity=entity, attrs=attrs,
ignore=ignore, params=params) | def read(self, entity=None, attrs=None, ignore=None, params=None) | Create a JobTemplate object before calling read()
ignore 'advanced' | 3.970425 | 3.368095 | 1.178834 |
kwargs = kwargs.copy() # shadow the passed-in kwargs
kwargs.update(self._server_config.get_client_kwargs())
if 'data' in kwargs:
if 'job_template_id' not in kwargs['data'] and 'feature' not in kwargs['data']:
raise KeyError('Provide either job_template_id or feature value')
if 'search_query' not in kwargs['data'] and 'bookmark_id' not in kwargs['data']:
raise KeyError('Provide either search_query or bookmark_id value')
for param_name in ['targeting_type', 'inputs']:
if param_name not in kwargs['data']:
raise KeyError('Provide {} value'.format(param_name))
kwargs['data'] = {u'job_invocation': kwargs['data']}
response = client.post(self.path('base'), **kwargs)
response.raise_for_status()
if synchronous is True:
return ForemanTask(
server_config=self._server_config, id=response.json()['task']['id']).poll()
return response.json() | def run(self, synchronous=True, **kwargs) | Helper to run existing job template
:param synchronous: What should happen if the server returns an HTTP
202 (accepted) status code? Wait for the task to complete if
``True``. Immediately return the server's response otherwise.
:param kwargs: Arguments to pass to requests.
'data' supports next fields:
required:
job_template_id/feature,
targeting_type,
search_query/bookmark_id,
inputs
optional:
description_format,
concurrency_control
scheduling,
ssh,
recurrence,
execution_timeout_interval
:returns: The server's response, with all JSON decoded.
:raises: ``requests.exceptions.HTTPError`` If the server responds with
an HTTP 4XX or 5XX message. | 4.539908 | 3.184393 | 1.425675 |
payload = super(JobTemplate, self).create_payload()
effective_user = payload.pop(u'effective_user', None)
if effective_user:
payload[u'ssh'] = {u'effective_user': effective_user}
return {u'job_template': payload} | def create_payload(self) | Wrap submitted data within an extra dict. | 4.909733 | 4.20662 | 1.167145 |
payload = super(JobTemplate, self).update_payload(fields)
effective_user = payload.pop(u'effective_user', None)
if effective_user:
payload[u'ssh'] = {u'effective_user': effective_user}
return {u'job_template': payload} | def update_payload(self, fields=None) | Wrap submitted data within an extra dict. | 4.124645 | 3.920811 | 1.051988 |
if attrs is None:
attrs = self.read_json(params=params)
if ignore is None:
ignore = set()
ignore.add('template_inputs')
entity = super(JobTemplate, self).read(entity=entity, attrs=attrs,
ignore=ignore, params=params)
referenced_entities = [
TemplateInput(entity._server_config, id=entity_id,
template=JobTemplate(entity._server_config,
id=entity.id))
for entity_id
in _get_entity_ids('template_inputs', attrs)
]
setattr(entity, 'template_inputs', referenced_entities)
return entity | def read(self, entity=None, attrs=None, ignore=None, params=None) | Ignore the template inputs when initially reading the job template.
Look up each TemplateInput entity separately
and afterwords add them to the JobTemplate entity. | 3.892404 | 3.222237 | 1.207982 |
super(ProvisioningTemplate, self).create_missing()
if (getattr(self, 'snippet', None) is False and
not hasattr(self, 'template_kind')):
self.template_kind = TemplateKind(self._server_config, id=1) | def create_missing(self) | Customize the process of auto-generating instance attributes.
Populate ``template_kind`` if:
* this template is not a snippet, and
* the ``template_kind`` instance attribute is unset. | 9.511504 | 5.859356 | 1.623302 |
payload = super(ProvisioningTemplate, self).create_payload()
if 'template_combinations' in payload:
payload['template_combinations_attributes'] = payload.pop(
'template_combinations')
return {u'provisioning_template': payload} | def create_payload(self) | Wrap submitted data within an extra dict.
For more information, see `Bugzilla #1151220
<https://bugzilla.redhat.com/show_bug.cgi?id=1151220>`_. | 5.128506 | 5.344171 | 0.959645 |
payload = super(ProvisioningTemplate, self).update_payload(fields)
if 'template_combinations' in payload:
payload['template_combinations_attributes'] = payload.pop(
'template_combinations')
return {u'provisioning_template': payload} | def update_payload(self, fields=None) | Wrap submitted data within an extra dict. | 4.363263 | 4.230746 | 1.031322 |
if which in ('build_pxe_default', 'clone', 'revision'):
prefix = 'self' if which == 'clone' else 'base'
return '{0}/{1}'.format(
super(ProvisioningTemplate, self).path(prefix),
which
)
return super(ProvisioningTemplate, self).path(which) | def path(self, which=None) | Extend ``nailgun.entity_mixins.Entity.path``.
The format of the returned path depends on the value of ``which``:
build_pxe_default
/provisioning_templates/build_pxe_default
clone
/provisioning_templates/clone
revision
/provisioning_templates/revision
``super`` is called otherwise. | 7.08357 | 3.02193 | 2.344056 |
if which in ('logs', 'power'):
return '{0}/{1}'.format(
super(AbstractDockerContainer, self).path(which='self'),
which
)
return super(AbstractDockerContainer, self).path(which) | def path(self, which=None) | Extend ``nailgun.entity_mixins.Entity.path``.
The format of the returned path depends on the value of ``which``:
logs
/containers/<id>/logs
power
/containers/<id>/power
``super`` is called otherwise. | 6.327016 | 4.30304 | 1.47036 |
# read() should not change the state of the object it's called on, but
# super() alters the attributes of any entity passed in. Creating a new
# object and passing it to super() lets this one avoid changing state.
if entity is None:
entity = type(self)(
self._server_config,
repository=self.repository, # pylint:disable=no-member
)
if ignore is None:
ignore = set()
ignore.add('repository')
return super(ContentUpload, self).read(entity, attrs, ignore, params) | def read(self, entity=None, attrs=None, ignore=None, params=None) | Provide a default value for ``entity``.
By default, ``nailgun.entity_mixins.EntityReadMixin.read`` provides a
default value for ``entity`` like so::
entity = type(self)()
However, :class:`ContentUpload` requires that a ``repository`` be
provided, so this technique will not work. Do this instead::
entity = type(self)(repository=self.repository.id) | 6.905972 | 6.651003 | 1.038335 |
kwargs = kwargs.copy() # shadow the passed-in kwargs
kwargs.update(self._server_config.get_client_kwargs())
# a content upload is always multipart
headers = kwargs.pop('headers', {})
headers['content-type'] = 'multipart/form-data'
kwargs['headers'] = headers
return client.put(
self.path('self'),
fields,
**kwargs
) | def update(self, fields=None, **kwargs) | Update the current entity.
Make an HTTP PUT call to ``self.path('base')``. Return the response.
:param fields: An iterable of field names. Only the fields named in
this iterable will be updated. No fields are updated if an empty
iterable is passed in. All fields are updated if ``None`` is passed
in.
:return: A ``requests.response`` object. | 6.01168 | 5.888301 | 1.020953 |
base = urljoin(
self._server_config.url + '/',
self._meta['api_path'] # pylint:disable=no-member
)
if (which == 'self' or which is None) and hasattr(self, 'upload_id'):
# pylint:disable=E1101
return urljoin(base + '/', str(self.upload_id))
return super(ContentUpload, self).path(which) | def path(self, which=None) | Extend ``nailgun.entity_mixins.Entity.path``. | 5.194677 | 4.894157 | 1.061404 |
if not filename:
filename = os.path.basename(filepath)
content_upload = self.create()
try:
offset = 0
content_chunk_size = 2 * 1024 * 1024
with open(filepath, 'rb') as contentfile:
chunk = contentfile.read(content_chunk_size)
while len(chunk) > 0:
data = {'offset': offset,
'content': chunk}
content_upload.update(data)
offset += len(chunk)
chunk = contentfile.read(content_chunk_size)
size = 0
checksum = hashlib.sha256()
with open(filepath, 'rb') as contentfile:
contents = contentfile.read()
size = len(contents)
checksum.update(contents)
uploads = [{'id': content_upload.upload_id, 'name': filename,
'size': size, 'checksum': checksum.hexdigest()}]
# pylint:disable=no-member
json = self.repository.import_uploads(uploads)
finally:
content_upload.delete()
return json | def upload(self, filepath, filename=None) | Upload content.
:param filepath: path to the file that should be chunked and uploaded
:param filename: name of the file on the server, defaults to the
last part of the ``filepath`` if not set
:returns: The server's response, with all JSON decoded.
:raises: ``requests.exceptions.HTTPError`` If the server responds with
an HTTP 4XX or 5XX message.
:raises nailgun.entities.APIResponseError: If the response has a status
other than "success".
.. _POST a Multipart-Encoded File:
http://docs.python-requests.org/en/latest/user/quickstart/#post-a-multipart-encoded-file
.. _POST Multiple Multipart-Encoded Files:
http://docs.python-requests.org/en/latest/user/advanced/#post-multiple-multipart-encoded-files | 2.510627 | 2.638519 | 0.951529 |
if which in ('incremental_update', 'promote'):
prefix = 'base' if which == 'incremental_update' else 'self'
return '{0}/{1}'.format(
super(ContentViewVersion, self).path(prefix),
which
)
return super(ContentViewVersion, self).path(which) | def path(self, which=None) | Extend ``nailgun.entity_mixins.Entity.path``.
The format of the returned path depends on the value of ``which``:
incremental_update
/content_view_versions/incremental_update
promote
/content_view_versions/<id>/promote
``super`` is called otherwise. | 5.821222 | 3.383621 | 1.720412 |
if entity is None:
entity = type(self)(
self._server_config,
# pylint:disable=no-member
content_view_filter=self.content_view_filter,
)
if attrs is None:
attrs = self.read_json()
if ignore is None:
ignore = set()
ignore.add('content_view_filter')
ignore.update([
field_name
for field_name in entity.get_fields().keys()
if field_name not in attrs
])
return super(ContentViewFilterRule, self).read(
entity, attrs, ignore, params) | def read(self, entity=None, attrs=None, ignore=None, params=None) | Do not read certain fields.
Do not expect the server to return the ``content_view_filter``
attribute. This has no practical impact, as the attribute must be
provided when a :class:`nailgun.entities.ContentViewFilterRule` is
instantiated.
Also, ignore any field that is not returned by the server. For more
information, see `Bugzilla #1238408
<https://bugzilla.redhat.com/show_bug.cgi?id=1238408>`_. | 3.670927 | 3.015742 | 1.217255 |
payload = super(ContentViewFilterRule, self).create_payload()
if 'errata_id' in payload:
if not hasattr(self.errata, 'errata_id'):
self.errata = self.errata.read()
payload['errata_id'] = self.errata.errata_id
return payload | def create_payload(self) | Reset ``errata_id`` from DB ID to ``errata_id``. | 4.557683 | 3.209185 | 1.4202 |
payload = super(ContentViewFilterRule, self).update_payload(fields)
if 'errata_id' in payload:
if not hasattr(self.errata, 'errata_id'):
self.errata = self.errata.read()
payload['errata_id'] = self.errata.errata_id
return payload | def update_payload(self, fields=None) | Reset ``errata_id`` from DB ID to ``errata_id``. | 4.060669 | 3.094351 | 1.312285 |
payload = super(ContentViewFilterRule, self).search_payload(
fields, query)
if 'errata_id' in payload:
if not hasattr(self.errata, 'errata_id'):
self.errata = self.errata.read()
payload['errata_id'] = self.errata.errata_id
return payload | def search_payload(self, fields=None, query=None) | Reset ``errata_id`` from DB ID to ``errata_id``. | 4.427984 | 3.454959 | 1.281631 |
# read() should not change the state of the object it's called on, but
# super() alters the attributes of any entity passed in. Creating a new
# object and passing it to super() lets this one avoid changing state.
if entity is None:
entity = type(self)(
self._server_config,
content_view=self.content_view, # pylint:disable=no-member
)
if ignore is None:
ignore = set()
ignore.add('content_view')
return super(ContentViewPuppetModule, self).read(
entity, attrs, ignore, params) | def read(self, entity=None, attrs=None, ignore=None, params=None) | Provide a default value for ``entity``.
By default, ``nailgun.entity_mixins.EntityReadMixin.read provides a
default value for ``entity`` like so::
entity = type(self)()
However, :class:`ContentViewPuppetModule` requires that an
``content_view`` be provided, so this technique will not work. Do
this instead::
entity = type(self)(content_view=self.content_view.id) | 6.97928 | 5.850333 | 1.192971 |
if attrs is None:
attrs = self.read_json()
if _get_version(self._server_config) < Version('6.1'):
org = _get_org(self._server_config, attrs['organization']['label'])
attrs['organization'] = org.get_values()
if ignore is None:
ignore = set()
ignore.add('content_view_component')
result = super(ContentView, self).read(entity, attrs, ignore, params)
if 'content_view_components' in attrs and attrs['content_view_components']:
result.content_view_component = [
ContentViewComponent(
self._server_config,
composite_content_view=result.id,
id=content_view_component['id'],
)
for content_view_component in attrs['content_view_components']
]
return result | def read(self, entity=None, attrs=None, ignore=None, params=None) | Fetch an attribute missing from the server's response.
For more information, see `Bugzilla #1237257
<https://bugzilla.redhat.com/show_bug.cgi?id=1237257>`_.
Add content_view_component to the response if needed, as
:meth:`nailgun.entity_mixins.EntityReadMixin.read` can't initialize
content_view_component. | 3.636785 | 3.501421 | 1.03866 |
results = self.search_json(fields, query)['results']
results = self.search_normalize(results)
entities = []
for result in results:
content_view_components = result.get('content_view_component')
if content_view_components is not None:
del result['content_view_component']
entity = type(self)(self._server_config, **result)
if content_view_components:
entity.content_view_component = [
ContentViewComponent(
self._server_config,
composite_content_view=result['id'],
id=cvc_id,
)
for cvc_id in content_view_components
]
entities.append(entity)
if filters is not None:
entities = self.search_filter(entities, filters)
return entities | def search(self, fields=None, query=None, filters=None) | Search for entities.
:param fields: A set naming which fields should be used when generating
a search query. If ``None``, all values on the entity are used. If
an empty set, no values are used.
:param query: A dict containing a raw search query. This is melded in
to the generated search query like so: ``{generated:
query}.update({manual: query})``.
:param filters: A dict. Used to filter search results locally.
:return: A list of entities, all of type ``type(self)``. | 3.329316 | 3.239398 | 1.027758 |
if which in (
'available_puppet_module_names',
'available_puppet_modules',
'content_view_puppet_modules',
'content_view_versions',
'copy',
'publish'):
return '{0}/{1}'.format(
super(ContentView, self).path(which='self'),
which
)
return super(ContentView, self).path(which) | def path(self, which=None) | Extend ``nailgun.entity_mixins.Entity.path``.
The format of the returned path depends on the value of ``which``:
content_view_puppet_modules
/content_views/<id>/content_view_puppet_modules
content_view_versions
/content_views/<id>/content_view_versions
publish
/content_views/<id>/publish
available_puppet_module_names
/content_views/<id>/available_puppet_module_names
``super`` is called otherwise. | 6.374316 | 3.193166 | 1.996237 |
kwargs = kwargs.copy() # shadow the passed-in kwargs
if 'data' in kwargs and 'id' not in kwargs['data']:
kwargs['data']['id'] = self.id # pylint:disable=no-member
kwargs.update(self._server_config.get_client_kwargs())
response = client.post(self.path('publish'), **kwargs)
return _handle_response(response, self._server_config, synchronous) | def publish(self, synchronous=True, **kwargs) | Helper for publishing an existing content view.
:param synchronous: What should happen if the server returns an HTTP
202 (accepted) status code? Wait for the task to complete if
``True``. Immediately return the server's response otherwise.
:param kwargs: Arguments to pass to requests.
:returns: The server's response, with all JSON decoded.
:raises: ``requests.exceptions.HTTPError`` If the server responds with
an HTTP 4XX or 5XX message. | 4.719516 | 4.734607 | 0.996813 |
if isinstance(environment, Environment):
environment_id = environment.id
else:
environment_id = environment
response = client.delete(
'{0}/environments/{1}'.format(self.path(), environment_id),
**self._server_config.get_client_kwargs()
)
return _handle_response(response, self._server_config, synchronous) | def delete_from_environment(self, environment, synchronous=True) | Delete this content view version from an environment.
This method acts much like
:meth:`nailgun.entity_mixins.EntityDeleteMixin.delete`. The
documentation on that method describes how the deletion procedure works
in general. This method differs only in accepting an ``environment``
parameter.
:param environment: A :class:`nailgun.entities.Environment` object. The
environment's ``id`` parameter *must* be specified. As a
convenience, an environment ID may be passed in instead of an
``Environment`` object. | 3.322659 | 4.02003 | 0.826526 |
if attrs is None:
attrs = self.read_json()
if ignore is None:
ignore = set()
if entity is None:
entity = type(self)(
self._server_config,
composite_content_view=self.composite_content_view,
)
ignore.add('composite_content_view')
return super(ContentViewComponent, self).read(entity, attrs, ignore, params) | def read(self, entity=None, attrs=None, ignore=None, params=None) | Add composite_content_view to the response if needed, as
:meth:`nailgun.entity_mixins.EntityReadMixin.read` can't initialize
composite_content_view. | 4.448165 | 3.570683 | 1.245746 |
if which in (
'add',
'remove'):
return '{0}/{1}'.format(
super(ContentViewComponent, self).path(which='base'),
which
)
return super(ContentViewComponent, self).path(which) | def path(self, which=None) | Extend ``nailgun.entity_mixins.Entity.path``.
The format of the returned path depends on the value of ``which``:
add
/content_view_components/add
remove
/content_view_components/remove
Otherwise, call ``super``. | 6.983239 | 4.123192 | 1.693649 |
kwargs = kwargs.copy() # shadow the passed-in kwargs
if 'data' not in kwargs:
# data is required
kwargs['data'] = dict()
if 'component_ids' not in kwargs['data']:
kwargs['data']['components'] = [_payload(self.get_fields(), self.get_values())]
kwargs.update(self._server_config.get_client_kwargs())
response = client.put(self.path('add'), **kwargs)
return _handle_response(response, self._server_config, synchronous) | def add(self, synchronous=True, **kwargs) | Add provided Content View Component.
:param synchronous: What should happen if the server returns an HTTP
202 (accepted) status code? Wait for the task to complete if
``True``. Immediately return the server's response otherwise.
:param kwargs: Arguments to pass to requests.
:returns: The server's response, with all JSON decoded.
:raises: ``requests.exceptions.HTTPError`` If the server responds with
an HTTP 4XX or 5XX message. | 5.617276 | 5.830322 | 0.963459 |
if not hasattr(self, 'name'):
self.name = gen_alphanumeric().lower()
super(Domain, self).create_missing() | def create_missing(self) | Customize the process of auto-generating instance attributes.
By default, :meth:`nailgun.entity_fields.StringField.gen_value` can
produce strings in both lower and upper cases, but domain name should
be always in lower case due logical reason. | 6.776419 | 5.172375 | 1.310117 |
return Domain(
self._server_config,
id=self.create_json(create_missing)['id'],
).read() | def create(self, create_missing=None) | Manually fetch a complete set of attributes for this entity.
For more information, see `Bugzilla #1219654
<https://bugzilla.redhat.com/show_bug.cgi?id=1219654>`_. | 16.590084 | 18.847946 | 0.880206 |
if which in ('smart_class_parameters',):
return '{0}/{1}'.format(
super(Environment, self).path(which='self'),
which
)
return super(Environment, self).path(which) | def path(self, which=None) | Extend ``nailgun.entity_mixins.Entity.path``.
The format of the returned path depends on the value of ``which``:
smart_class_parameters
/api/environments/:environment_id/smart_class_parameters
Otherwise, call ``super``. | 7.98686 | 3.849059 | 2.075016 |
if which in ('compare',):
return '{0}/{1}'.format(super(Errata, self).path('base'), which)
return super(Errata, self).path(which) | def path(self, which=None) | Extend ``nailgun.entity_mixins.Entity.path``.
The format of the returned path depends on the value of ``which``:
compare
/katello/api/errata/compare
Otherwise, call ``super``. | 6.276421 | 4.419281 | 1.420236 |
if attrs is None:
attrs = self.read_json()
attrs['override'] = attrs.pop('override?')
attrs['unlimited'] = attrs.pop('unlimited?')
return super(Filter, self).read(entity, attrs, ignore, params) | def read(self, entity=None, attrs=None, ignore=None, params=None) | Deal with different named data returned from the server | 4.695604 | 4.590822 | 1.022824 |
if which in ('bulk_resume', 'bulk_search', 'summary'):
return '{0}/{1}'.format(
super(ForemanTask, self).path('base'),
which
)
return super(ForemanTask, self).path(which) | def path(self, which=None) | Extend ``nailgun.entity_mixins.Entity.path``.
The format of the returned path depends on the value of ``which``:
bulk_resume
/foreman_tasks/api/tasks/bulk_resume
bulk_search
/foreman_tasks/api/tasks/bulk_search
summary
/foreman_tasks/api/tasks/summary
Otherwise, call ``super``. | 6.457377 | 2.969137 | 2.174833 |
# See nailgun.entity_mixins._poll_task for an explanation of why a
# private method is called.
return _poll_task(
self.id, # pylint:disable=no-member
self._server_config,
poll_rate,
timeout
) | def poll(self, poll_rate=None, timeout=None) | Return the status of a task or timeout.
There are several API calls that trigger asynchronous tasks, such as
synchronizing a repository, or publishing or promoting a content view.
It is possible to check on the status of a task if you know its UUID.
This method polls a task once every ``poll_rate`` seconds and, upon
task completion, returns information about that task.
:param poll_rate: Delay between the end of one task check-up and
the start of the next check-up. Defaults to
``nailgun.entity_mixins.TASK_POLL_RATE``.
:param timeout: Maximum number of seconds to wait until timing out.
Defaults to ``nailgun.entity_mixins.TASK_TIMEOUT``.
:returns: Information about the asynchronous task.
:raises: ``nailgun.entity_mixins.TaskTimedOutError`` if the task
completes with any result other than "success".
:raises: ``nailgun.entity_mixins.TaskFailedError`` if the task finishes
with any result other than "success".
:raises: ``requests.exceptions.HTTPError`` If the API returns a message
with an HTTP 4XX or 5XX status code. | 9.529951 | 7.532175 | 1.265232 |
payload = super(HostCollection, self).create_payload()
if 'system_ids' in payload:
payload['system_uuids'] = payload.pop('system_ids')
return payload | def create_payload(self) | Rename ``system_ids`` to ``system_uuids``. | 4.905966 | 2.317676 | 2.116761 |
return HostCollection(
self._server_config,
id=self.create_json(create_missing)['id'],
).read() | def create(self, create_missing=None) | Manually fetch a complete set of attributes for this entity.
For more information, see `Bugzilla #1654383
<https://bugzilla.redhat.com/show_bug.cgi?id=1654383>`_. | 18.270117 | 20.170692 | 0.905775 |
payload = super(HostCollection, self).update_payload(fields)
if 'system_ids' in payload:
payload['system_uuids'] = payload.pop('system_ids')
return payload | def update_payload(self, fields=None) | Rename ``system_ids`` to ``system_uuids``. | 3.780191 | 2.165544 | 1.745608 |
return HostGroup(
self._server_config,
id=self.create_json(create_missing)['id'],
).read() | def create(self, create_missing=None) | Do extra work to fetch a complete set of attributes for this entity.
For more information, see `Bugzilla #1235377
<https://bugzilla.redhat.com/show_bug.cgi?id=1235377>`_. | 15.543971 | 17.352377 | 0.895783 |
if ignore is None:
ignore = set()
ignore.add('root_pass')
ignore.add('kickstart_repository')
if attrs is None:
attrs = self.read_json()
attrs['parent_id'] = attrs.pop('ancestry') # either an ID or None
version = _get_version(self._server_config)
if version >= Version('6.1') and version < Version('6.2'):
# We cannot call `self.update_json([])`, as an ID might not be
# present on self. However, `attrs` is guaranteed to have an ID.
attrs2 = HostGroup(
self._server_config,
id=attrs['id']
).update_json([])
for attr in ('content_source_id',
'content_view_id',
'lifecycle_environment_id'):
attrs[attr] = attrs2.get(attr)
return super(HostGroup, self).read(entity, attrs, ignore, params) | def read(self, entity=None, attrs=None, ignore=None, params=None) | Deal with several bugs.
For more information, see:
* `Bugzilla #1235377
<https://bugzilla.redhat.com/show_bug.cgi?id=1235377>`_
* `Bugzilla #1235379
<https://bugzilla.redhat.com/show_bug.cgi?id=1235379>`_
* `Bugzilla #1450379
<https://bugzilla.redhat.com/show_bug.cgi?id=1450379>`_ | 6.19034 | 6.03952 | 1.024972 |
if which in (
'clone',
'puppetclass_ids',
'smart_class_parameters',
'smart_variables'
):
return '{0}/{1}'.format(
super(HostGroup, self).path(which='self'),
which
)
return super(HostGroup, self).path(which) | def path(self, which=None) | Extend ``nailgun.entity_mixins.Entity.path``.
The format of the returned path depends on the value of ``which``:
clone
/api/hostgroups/:hostgroup_id/clone
puppetclass_ids
/api/hostgroups/:hostgroup_id/puppetclass_ids
smart_class_parameters
/api/hostgroups/:hostgroup_id/smart_class_parameters
smart_class_variables
/api/hostgroups/:hostgroup_id/smart_variables
Otherwise, call ``super``. | 8.031202 | 2.87337 | 2.795047 |
kwargs = kwargs.copy()
kwargs.update(self._server_config.get_client_kwargs())
path = "{0}/{1}".format(
self.path('puppetclass_ids'),
kwargs['data'].pop('puppetclass_id')
)
return _handle_response(
client.delete(path, **kwargs), self._server_config, synchronous) | def delete_puppetclass(self, synchronous=True, **kwargs) | Remove a Puppet class from host group
Here is an example of how to use this method::
hostgroup.delete_puppetclass(data={'puppetclass_id': puppet.id})
Constructs path:
/api/hostgroups/:hostgroup_id/puppetclass_ids/:id
:param synchronous: What should happen if the server returns an HTTP
202 (accepted) status code? Wait for the task to complete if
``True``. Immediately return the server's response otherwise.
:param kwargs: Arguments to pass to requests.
:returns: The server's response, with all JSON decoded.
:raises: ``requests.exceptions.HTTPError`` If the server responds with
an HTTP 4XX or 5XX message. | 5.494036 | 5.062366 | 1.08527 |
if which in (
'add_subscriptions',
'remove_subscriptions'):
return '{0}/{1}'.format(
super(HostSubscription, self).path(which='base'),
which
)
return super(HostSubscription, self).path(which) | def path(self, which=None) | Extend ``nailgun.entity_mixins.Entity.path``.
The format of the returned path depends on the value of ``which``:
add_subscriptions
/hosts/<id>/add_subscriptions
remove_subscriptions
/hosts/<id>/remove_subscriptions
``super`` is called otherwise. | 6.266344 | 4.138085 | 1.51431 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.