INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
Preserve fields in deposit. | def preserve(method=None, result=True, fields=None):
"""Preserve fields in deposit.
:param method: Function to execute. (Default: ``None``)
:param result: If `True` returns the result of method execution,
otherwise `self`. (Default: ``True``)
:param fields: List of fields to preserve (default: ... |
Return an instance of deposit PID. | def pid(self):
"""Return an instance of deposit PID."""
pid = self.deposit_fetcher(self.id, self)
return PersistentIdentifier.get(pid.pid_type,
pid.pid_value) |
Convert deposit schema to a valid record schema. | def record_schema(self):
"""Convert deposit schema to a valid record schema."""
schema_path = current_jsonschemas.url_to_path(self['$schema'])
schema_prefix = current_app.config['DEPOSIT_JSONSCHEMAS_PREFIX']
if schema_path and schema_path.startswith(schema_prefix):
return cur... |
Convert record schema to a valid deposit schema. | def build_deposit_schema(self, record):
"""Convert record schema to a valid deposit schema.
:param record: The record used to build deposit schema.
:returns: The absolute URL to the schema or `None`.
"""
schema_path = current_jsonschemas.url_to_path(record['$schema'])
sc... |
Return a tuple with PID and published record. | def fetch_published(self):
"""Return a tuple with PID and published record."""
pid_type = self['_deposit']['pid']['type']
pid_value = self['_deposit']['pid']['value']
resolver = Resolver(
pid_type=pid_type, object_type='rec',
getter=partial(self.published_record_... |
Merge changes with latest published version. | def merge_with_published(self):
"""Merge changes with latest published version."""
pid, first = self.fetch_published()
lca = first.revisions[self['_deposit']['pid']['revision_id']]
# ignore _deposit and $schema field
args = [lca.dumps(), first.dumps(), self.dumps()]
for a... |
Store changes on current instance in database and index it. | def commit(self, *args, **kwargs):
"""Store changes on current instance in database and index it."""
return super(Deposit, self).commit(*args, **kwargs) |
Create a deposit. | def create(cls, data, id_=None):
"""Create a deposit.
Initialize the follow information inside the deposit:
.. code-block:: python
deposit['_deposit'] = {
'id': pid_value,
'status': 'draft',
'owners': [user_id],
'crea... |
Snapshot bucket and add files in record during first publishing. | def _process_files(self, record_id, data):
"""Snapshot bucket and add files in record during first publishing."""
if self.files:
assert not self.files.bucket.locked
self.files.bucket.locked = True
snapshot = self.files.bucket.snapshot(lock=True)
data['_fil... |
Publish new deposit. | def _publish_new(self, id_=None):
"""Publish new deposit.
:param id_: The forced record UUID.
"""
minter = current_pidstore.minters[
current_app.config['DEPOSIT_PID_MINTER']
]
id_ = id_ or uuid.uuid4()
record_pid = minter(id_, self)
self['_de... |
Publish the deposit after for editing. | def _publish_edited(self):
"""Publish the deposit after for editing."""
record_pid, record = self.fetch_published()
if record.revision_id == self['_deposit']['pid']['revision_id']:
data = dict(self.dumps())
else:
data = self.merge_with_published()
data['$... |
Publish a deposit. | def publish(self, pid=None, id_=None):
"""Publish a deposit.
If it's the first time:
* it calls the minter and set the following meta information inside
the deposit:
.. code-block:: python
deposit['_deposit'] = {
'type': pid_type,
... |
Update selected keys. | def _prepare_edit(self, record):
"""Update selected keys.
:param record: The record to prepare.
"""
data = record.dumps()
# Keep current record revision for merging.
data['_deposit']['pid']['revision_id'] = record.revision_id
data['_deposit']['status'] = 'draft'
... |
Edit deposit. | def edit(self, pid=None):
"""Edit deposit.
#. The signal :data:`invenio_records.signals.before_record_update`
is sent before the edit execution.
#. The following meta information are saved inside the deposit:
.. code-block:: python
deposit['_deposit']['pid'] = ... |
Discard deposit changes. | def discard(self, pid=None):
"""Discard deposit changes.
#. The signal :data:`invenio_records.signals.before_record_update` is
sent before the edit execution.
#. It restores the last published version.
#. The following meta information are saved inside the deposit:
... |
Delete deposit. | def delete(self, force=True, pid=None):
"""Delete deposit.
Status required: ``'draft'``.
:param force: Force deposit delete. (Default: ``True``)
:param pid: Force pid object. (Default: ``None``)
:returns: A new Deposit object.
"""
pid = pid or self.pid
... |
Clear only drafts. | def clear(self, *args, **kwargs):
"""Clear only drafts.
Status required: ``'draft'``.
Meta information inside `_deposit` are preserved.
"""
super(Deposit, self).clear(*args, **kwargs) |
Update only drafts. | def update(self, *args, **kwargs):
"""Update only drafts.
Status required: ``'draft'``.
Meta information inside `_deposit` are preserved.
"""
super(Deposit, self).update(*args, **kwargs) |
Patch only drafts. | def patch(self, *args, **kwargs):
"""Patch only drafts.
Status required: ``'draft'``.
Meta information inside `_deposit` are preserved.
"""
return super(Deposit, self).patch(*args, **kwargs) |
List of Files inside the deposit. | def files(self):
"""List of Files inside the deposit.
Add validation on ``sort_by`` method: if, at the time of files access,
the record is not a ``'draft'`` then a
:exc:`invenio_pidstore.errors.PIDInvalidAction` is rised.
"""
files_ = super(Deposit, self).files
... |
Converts a reStructuredText into its node | def rst2node(doc_name, data):
"""Converts a reStructuredText into its node
"""
if not data:
return
parser = docutils.parsers.rst.Parser()
document = docutils.utils.new_document('<%s>' % doc_name)
document.settings = docutils.frontend.OptionParser().get_default_values()
document.setti... |
Hook the directives when Sphinx ask for it. | def setup(app):
"""Hook the directives when Sphinx ask for it."""
if 'http' not in app.domains:
httpdomain.setup(app)
app.add_directive('autopyramid', RouteDirective) |
Parses the API response and raises appropriate errors if raise_errors was set to True | def _parse_response(self, response):
"""Parses the API response and raises appropriate errors if
raise_errors was set to True
"""
if not self._raise_errors:
return response
is_4xx_error = str(response.status_code)[0] == '4'
is_5xx_error = str(response.status_... |
Private method for api requests | def _api_request(self, endpoint, http_method, *args, **kwargs):
"""Private method for api requests"""
logger.debug(' > Sending API request to endpoint: %s' % endpoint)
auth = self._build_http_auth()
headers = self._build_request_headers(kwargs.get('headers'))
logger.debug('\the... |
API call to get a specific log entry | def get_log(self, log_id, timeout=None):
""" API call to get a specific log entry """
return self._api_request(
self.GET_LOG_ENDPOINT % log_id,
self.HTTP_GET,
timeout=timeout
) |
API call to get a specific log entry | def get_log_events(self, log_id, timeout=None):
""" API call to get a specific log entry """
return self._api_request(
self.GET_LOG_EVENTS_ENDPOINT % log_id,
self.HTTP_GET,
timeout=timeout
) |
API call to get a list of templates | def templates(self, timeout=None):
""" API call to get a list of templates """
return self._api_request(
self.TEMPLATES_ENDPOINT,
self.HTTP_GET,
timeout=timeout
) |
API call to get a specific template | def get_template(self, template_id, version=None, timeout=None):
""" API call to get a specific template """
if (version):
return self._api_request(
self.TEMPLATES_VERSION_ENDPOINT % (template_id, version),
self.HTTP_GET,
timeout=timeout
... |
[ DECPRECATED ] API call to create an email | def create_email(self, name, subject, html, text=''):
""" [DECPRECATED] API call to create an email """
return self.create_template(name, subject, html, text) |
API call to create a template | def create_template(
self,
name,
subject,
html,
text='',
timeout=None
):
""" API call to create a template """
payload = {
'name': name,
'subject': subject,
'html': html,
'text': text
}
r... |
API call to create a new locale and version of a template | def create_new_locale(
self,
template_id,
locale,
version_name,
subject,
text='',
html='',
timeout=None
):
""" API call to create a new locale and version of a template """
payload = {
'locale': locale,
'name': v... |
API call to create a new version of a template | def create_new_version(
self,
name,
subject,
text='',
template_id=None,
html=None,
locale=None,
timeout=None
):
""" API call to create a new version of a template """
if(html):
payload = {
'name': name,
... |
API call to update a template version | def update_template_version(
self,
name,
subject,
template_id,
version_id,
text='',
html=None,
timeout=None
):
""" API call to update a template version """
if(html):
payload = {
'name': name,
... |
API call to get list of snippets | def snippets(self, timeout=None):
""" API call to get list of snippets """
return self._api_request(
self.SNIPPETS_ENDPOINT,
self.HTTP_GET,
timeout=timeout
) |
API call to get a specific Snippet | def get_snippet(self, snippet_id, timeout=None):
""" API call to get a specific Snippet """
return self._api_request(
self.SNIPPET_ENDPOINT % (snippet_id),
self.HTTP_GET,
timeout=timeout
) |
API call to create a Snippet | def create_snippet(self, name, body, timeout=None):
""" API call to create a Snippet """
payload = {
'name': name,
'body': body
}
return self._api_request(
self.SNIPPETS_ENDPOINT,
self.HTTP_POST,
payload=payload,
tim... |
Make a dictionary with filename and base64 file data | def _make_file_dict(self, f):
"""Make a dictionary with filename and base64 file data"""
if isinstance(f, dict):
file_obj = f['file']
if 'filename' in f:
file_name = f['filename']
else:
file_name = file_obj.name
else:
... |
API call to send an email | def send(
self,
email_id,
recipient,
email_data=None,
sender=None,
cc=None,
bcc=None,
tags=[],
headers={},
esp_account=None,
locale=None,
email_version_name=None,
inline=None,
files=[],
timeout=None
... |
Private method for api requests | def _api_request(self, endpoint, http_method, *args, **kwargs):
"""Private method for api requests"""
logger.debug(' > Queing batch api request for endpoint: %s' % endpoint)
path = self._build_request_path(endpoint, absolute=False)
logger.debug('\tpath: %s' % path)
data = None
... |
Execute all currently queued batch commands | def execute(self, timeout=None):
"""Execute all currently queued batch commands"""
logger.debug(' > Batch API request (length %s)' % len(self._commands))
auth = self._build_http_auth()
headers = self._build_request_headers()
logger.debug('\tbatch headers: %s' % headers)
... |
Return instances of all other tabs that are members of the tab s tab group. | def get_group_tabs(self):
"""
Return instances of all other tabs that are members of the tab's
tab group.
"""
if self.tab_group is None:
raise ImproperlyConfigured(
"%s requires a definition of 'tab_group'" %
self.__class__.__name__)
... |
Process and prepare tabs. | def _process_tabs(self, tabs, current_tab, group_current_tab):
"""
Process and prepare tabs.
This includes steps like updating references to the current tab,
filtering out hidden tabs, sorting tabs etc...
Args:
tabs:
The list of tabs to process.
... |
Adds tab information to context. | def get_context_data(self, **kwargs):
"""
Adds tab information to context.
To retrieve a list of all group tab instances, use
``{{ tabs }}`` in your template.
The id of the current tab is added as ``current_tab_id`` to the
template context.
If the current tab h... |
Convert a string into a valid python attribute name. This function is called to convert ASCII strings to something that can pass as python attribute name to be used with namedtuples. | def normalize_name(s):
"""Convert a string into a valid python attribute name.
This function is called to convert ASCII strings to something that can pass as
python attribute name, to be used with namedtuples.
>>> str(normalize_name('class'))
'class_'
>>> str(normalize_name('a-name'))
'a_na... |
Convert the table and column descriptions of a TableGroup into specifications for the DB schema. | def schema(tg):
"""
Convert the table and column descriptions of a `TableGroup` into specifications for the
DB schema.
:param ds:
:return: A pair (tables, reference_tables).
"""
tables = {}
for tname, table in tg.tabledict.items():
t = TableSpec.from_table_metadata(table)
... |
Creates a db file with the core schema. | def write(self, _force=False, _exists_ok=False, **items):
"""
Creates a db file with the core schema.
:param force: If `True` an existing db file will be overwritten.
"""
if self.fname and self.fname.exists():
raise ValueError('db file already exists, use force=True ... |
Convenience factory function for csv reader. | def iterrows(lines_or_file, namedtuples=False, dicts=False, encoding='utf-8', **kw):
"""Convenience factory function for csv reader.
:param lines_or_file: Content to be read. Either a file handle, a file path or a list\
of strings.
:param namedtuples: Yield namedtuples.
:param dicts: Yield dicts.
... |
Utility function to rewrite rows in tsv files. | def rewrite(fname, visitor, **kw):
"""Utility function to rewrite rows in tsv files.
:param fname: Path of the dsv file to operate on.
:param visitor: A callable that takes a line-number and a row as input and returns a \
(modified) row or None to filter out the row.
:param kw: Keyword parameters a... |
Rewrite a dsv file filtering the rows. | def filter_rows_as_dict(fname, filter_, **kw):
"""Rewrite a dsv file, filtering the rows.
:param fname: Path to dsv file
:param filter_: callable which accepts a `dict` with a row's data as single argument\
returning a `Boolean` indicating whether to keep the row (`True`) or to discard it \
`False`... |
Dump a single grid to its ZINC representation. | def dump_grid(grid):
"""
Dump a single grid to its ZINC representation.
"""
header = 'ver:%s' % dump_str(str(grid._version), version=grid._version)
if bool(grid.metadata):
header += ' ' + dump_meta(grid.metadata, version=grid._version)
columns = dump_columns(grid.column, version=grid._ve... |
Parse the given Zinc text and return the equivalent data. | def parse(grid_str, mode=MODE_ZINC, charset='utf-8'):
'''
Parse the given Zinc text and return the equivalent data.
'''
# Decode incoming text (or python3 will whine!)
if isinstance(grid_str, six.binary_type):
grid_str = grid_str.decode(encoding=charset)
# Split the separate grids up, t... |
Append the item to the metadata. | def append(self, key, value=MARKER, replace=True):
'''
Append the item to the metadata.
'''
return self.add_item(key, value, replace=replace) |
Append the items to the metadata. | def extend(self, items, replace=True):
'''
Append the items to the metadata.
'''
if isinstance(items, dict) or isinstance(items, SortableDict):
items = list(items.items())
for (key, value) in items:
self.append(key, value, replace=replace) |
Construct a regular polygon. | def regular_polygon(cls, center, radius, n_vertices, start_angle=0, **kwargs):
"""Construct a regular polygon.
Parameters
----------
center : array-like
radius : float
n_vertices : int
start_angle : float, optional
Where to put the first point, relati... |
Construct a circle. | def circle(cls, center, radius, n_vertices=50, **kwargs):
"""Construct a circle.
Parameters
----------
center : array-like
radius : float
n_vertices : int, optional
Number of points to draw.
Decrease for performance, increase for appearance.
... |
Shortcut for creating a rectangle aligned with the screen axes from only two corners. | def rectangle(cls, vertices, **kwargs):
"""Shortcut for creating a rectangle aligned with the screen axes from only two corners.
Parameters
----------
vertices : array-like
An array containing the ``[x, y]`` positions of two corners.
kwargs
Other keyword ... |
Create a |Shape| from a dictionary specification. | def from_dict(cls, spec):
"""Create a |Shape| from a dictionary specification.
Parameters
----------
spec : dict
A dictionary with either the fields ``'center'`` and ``'radius'`` (for a circle),
``'center'``, ``'radius'``, and ``'n_vertices'`` (for a regular poly... |
Keyword arguments for recreating the Shape from the vertices. | def _kwargs(self):
"""Keyword arguments for recreating the Shape from the vertices.
"""
return dict(color=self.color, velocity=self.velocity, colors=self.colors) |
Resize the shape by a proportion ( e. g. 1 is unchanged ) in - place. | def scale(self, factor, center=None):
"""Resize the shape by a proportion (e.g., 1 is unchanged), in-place.
Parameters
----------
factor : float or array-like
If a scalar, the same factor will be applied in the x and y dimensions.
center : array-like, optional
... |
Rotate the shape in - place. | def rotate(self, angle, center=None):
"""Rotate the shape, in-place.
Parameters
----------
angle : float
Angle to rotate, in radians counter-clockwise.
center : array-like, optional
Point about which to rotate.
If not passed, the center of the... |
Flip the shape in the x direction in - place. | def flip_x(self, center=None):
"""Flip the shape in the x direction, in-place.
Parameters
----------
center : array-like, optional
Point about which to flip.
If not passed, the center of the shape will be used.
"""
if center is None:
... |
Flip the shape in the y direction in - place. | def flip_y(self, center=None):
"""Flip the shape in the y direction, in-place.
Parameters
----------
center : array-like, optional
Point about which to flip.
If not passed, the center of the shape will be used.
"""
if center is None:
... |
Flip the shape in an arbitrary direction. | def flip(self, angle, center=None):
""" Flip the shape in an arbitrary direction.
Parameters
----------
angle : array-like
The angle, in radians counter-clockwise from the horizontal axis,
defining the angle about which to flip the shape (of a line through `cente... |
Draw the shape in the current OpenGL context. | def draw(self):
"""Draw the shape in the current OpenGL context.
"""
if self.enabled:
self._vertex_list.colors = self._gl_colors
self._vertex_list.vertices = self._gl_vertices
self._vertex_list.draw(pyglet.gl.GL_TRIANGLES) |
Update the shape s position by moving it forward according to its velocity. | def update(self, dt):
"""Update the shape's position by moving it forward according to its velocity.
Parameters
----------
dt : float
"""
self.translate(dt * self.velocity)
self.rotate(dt * self.angular_velocity) |
Map the official Haystack timezone list to those recognised by pytz. | def _map_timezones():
"""
Map the official Haystack timezone list to those recognised by pytz.
"""
tz_map = {}
todo = HAYSTACK_TIMEZONES_SET.copy()
for full_tz in pytz.all_timezones:
# Finished case:
if not bool(todo): # pragma: no cover
# This is nearly impossible fo... |
Retrieve the Haystack timezone | def timezone(haystack_tz, version=LATEST_VER):
"""
Retrieve the Haystack timezone
"""
tz_map = get_tz_map(version=version)
try:
tz_name = tz_map[haystack_tz]
except KeyError:
raise ValueError('%s is not a recognised timezone on this host' \
% haystack_tz)
retu... |
Determine an appropriate timezone for the given date/ time object | def timezone_name(dt, version=LATEST_VER):
"""
Determine an appropriate timezone for the given date/time object
"""
tz_rmap = get_tz_rmap(version=version)
if dt.tzinfo is None:
raise ValueError('%r has no timezone' % dt)
# Easy case: pytz timezone.
try:
tz_name = dt.tzinfo.z... |
Iterative parser for string escapes. | def _unescape(s, uri=False):
"""
Iterative parser for string escapes.
"""
out = ''
while len(s) > 0:
c = s[0]
if c == '\\':
# Backslash escape
esc_c = s[1]
if esc_c in ('u', 'U'):
# Unicode escape
out += six.unichr(... |
Parse the incoming grid. | def parse_grid(grid_data):
"""
Parse the incoming grid.
"""
try:
# Split the grid up.
grid_parts = NEWLINE_RE.split(grid_data)
if len(grid_parts) < 2:
raise ZincParseException('Malformed grid received',
grid_data, 1, 1)
# Grid and column m... |
Parse a Project Haystack scalar in ZINC format. | def parse_scalar(scalar_data, version):
"""
Parse a Project Haystack scalar in ZINC format.
"""
try:
return hs_scalar[version].parseString(scalar_data, parseAll=True)[0]
except pp.ParseException as pe:
# Raise a new exception with the appropriate line number.
raise ZincParseE... |
Add an item at a specific location possibly replacing the existing item. | def add_item(self, key, value, after=False, index=None, pos_key=None,
replace=True):
"""
Add an item at a specific location, possibly replacing the
existing item.
If after is True, we insert *after* the given index, otherwise we
insert before.
The position i... |
Dump the given grids in the specified over - the - wire format. | def dump(grids, mode=MODE_ZINC):
"""
Dump the given grids in the specified over-the-wire format.
"""
if isinstance(grids, Grid):
return dump_grid(grids, mode=mode)
_dump = functools.partial(dump_grid, mode=mode)
if mode == MODE_ZINC:
return '\n'.join(map(_dump, grids))
elif m... |
Some parsing tweaks to fit pint units/ handling of edge cases. | def to_haystack(unit):
"""
Some parsing tweaks to fit pint units / handling of edge cases.
"""
unit = str(unit)
global HAYSTACK_CONVERSION
global PINT_CONVERSION
if unit == 'per_minute' or \
unit == '/min' or \
unit == 'per_second' or \
unit == '/s' or \
unit ... |
Some parsing tweaks to fit pint units/ handling of edge cases. | def to_pint(unit):
"""
Some parsing tweaks to fit pint units / handling of edge cases.
"""
global HAYSTACK_CONVERSION
if unit == 'per_minute' or \
unit == '/min' or \
unit == 'per_second' or \
unit == '/s' or \
unit == 'per_hour' or \
unit == '/h' or \
... |
Missing units found in project - haystack Added to the registry | def define_haystack_units():
"""
Missing units found in project-haystack
Added to the registry
"""
ureg = UnitRegistry()
ureg.define('% = [] = percent')
ureg.define('pixel = [] = px = dot = picture_element = pel')
ureg.define('decibel = [] = dB')
ureg.define('ppu = [] = parts_per_uni... |
Detect the version used from the row content or validate against the version if given. | def _detect_or_validate(self, val):
'''
Detect the version used from the row content, or validate against
the version if given.
'''
if isinstance(val, list) \
or isinstance(val, dict) \
or isinstance(val, SortableDict) \
or isinstan... |
Assert that the grid version is equal to or above the given value. If no version is set set the version. | def _assert_version(self, version):
'''
Assert that the grid version is equal to or above the given value.
If no version is set, set the version.
'''
if self.nearest_version < version:
if self._version_given:
raise ValueError(
'... |
Compare two Project Haystack version strings then return - 1 if self < other 0 if self == other or 1 if self > other. | def _cmp(self, other):
"""
Compare two Project Haystack version strings, then return
-1 if self < other,
0 if self == other
or 1 if self > other.
"""
if not isinstance(other, Version):
other = Version(other)
num1 = self.version_num... |
Retrieve the official version nearest the one given. | def nearest(self, ver):
"""
Retrieve the official version nearest the one given.
"""
if not isinstance(ver, Version):
ver = Version(ver)
if ver in OFFICIAL_VERSIONS:
return ver
# We might not have an exact match for that.
# See if we have... |
Encrypts file with gpg and random generated password | def encrypt_files(selected_host, only_link, file_name):
"""
Encrypts file with gpg and random generated password
"""
if ENCRYPTION_DISABLED:
print('For encryption please install gpg')
exit()
passphrase = '%030x' % random.randrange(16**30)
source_filename = file_name
cmd = 'gp... |
Checks file sizes for host | def check_max_filesize(chosen_file, max_size):
"""
Checks file sizes for host
"""
if os.path.getsize(chosen_file) > max_size:
return False
else:
return True |
Makes parsing arguments a function. | def parse_arguments(args, clone_list):
"""
Makes parsing arguments a function.
"""
returned_string=""
host_number = args.host
if args.show_list:
print(generate_host_string(clone_list, "Available hosts: "))
exit()
if args.decrypt:
for i in args.files:
print... |
Uploads selected file to the host thanks to the fact that every pomf. se based site has pretty much the same architecture. | def upload_files(selected_file, selected_host, only_link, file_name):
"""
Uploads selected file to the host, thanks to the fact that
every pomf.se based site has pretty much the same architecture.
"""
try:
answer = requests.post(
url=selected_host[0]+"upload.php",
fil... |
Serves Swagger UI page default Swagger UI config is used but you can override the callable that generates the <script > tag by setting cornice_swagger. swagger_ui_script_generator in pyramid config it defaults to cornice_swagger. views: swagger_ui_script_template | def swagger_ui_template_view(request):
"""
Serves Swagger UI page, default Swagger UI config is used but you can
override the callable that generates the `<script>` tag by setting
`cornice_swagger.swagger_ui_script_generator` in pyramid config, it defaults
to 'cornice_swagger.views:swagger_ui_script... |
: param request:: return: | def open_api_json_view(request):
"""
:param request:
:return:
Generates JSON representation of Swagger spec
"""
doc = cornice_swagger.CorniceSwagger(
cornice.service.get_services(), pyramid_registry=request.registry)
kwargs = request.registry.settings['cornice_swagger.spec_kwargs']
... |
: param request:: return: | def swagger_ui_script_template(request, **kwargs):
"""
:param request:
:return:
Generates the <script> code that bootstraps Swagger UI, it will be injected
into index template
"""
swagger_spec_url = request.route_url('cornice_swagger.open_api_path')
template = pkg_resources.resource_str... |
Decrypts file from entered links | def decrypt_files(file_link):
"""
Decrypts file from entered links
"""
if ENCRYPTION_DISABLED:
print('For decryption please install gpg')
exit()
try:
parsed_link = re.findall(r'(.*/(.*))#(.{30})', file_link)[0]
req = urllib.request.Request(
parsed_link[0],... |
Set the value and returns * True * or * False *. | def set_value(request):
"""Set the value and returns *True* or *False*."""
key = request.matchdict['key']
_VALUES[key] = request.json_body
return _VALUES.get(key) |
Creates a Swagger definition from a colander schema. | def from_schema(self, schema_node, base_name=None):
"""
Creates a Swagger definition from a colander schema.
:param schema_node:
Colander schema to be transformed into a Swagger definition.
:param base_name:
Schema alternative title.
:rtype: dict
... |
Dismantle nested swagger schemas into several definitions using JSON pointers. Note: This can be dangerous since definition titles must be unique. | def _ref_recursive(self, schema, depth, base_name=None):
"""
Dismantle nested swagger schemas into several definitions using JSON pointers.
Note: This can be dangerous since definition titles must be unique.
:param schema:
Base swagger schema.
:param depth:
... |
Creates a list of Swagger params from a colander request schema. | def from_schema(self, schema_node):
"""
Creates a list of Swagger params from a colander request schema.
:param schema_node:
Request schema to be transformed into Swagger.
:param validators:
Validators used in colander with the schema.
:rtype: list
... |
Create a list of Swagger path params from a cornice service path. | def from_path(self, path):
"""
Create a list of Swagger path params from a cornice service path.
:type path: string
:rtype: list
"""
path_components = path.split('/')
param_names = [comp[1:-1] for comp in path_components
if comp.startswith(... |
Store a parameter schema and return a reference to it. | def _ref(self, param, base_name=None):
"""
Store a parameter schema and return a reference to it.
:param schema:
Swagger parameter definition.
:param base_name:
Name that should be used for the reference.
:rtype: dict
:returns: JSON pointer to th... |
Creates a Swagger response object from a dict of response schemas. | def from_schema_mapping(self, schema_mapping):
"""
Creates a Swagger response object from a dict of response schemas.
:param schema_mapping:
Dict with entries matching ``{status_code: response_schema}``.
:rtype: dict
:returns: Response schema.
"""
re... |
Store a response schema and return a reference to it. | def _ref(self, resp, base_name=None):
"""
Store a response schema and return a reference to it.
:param schema:
Swagger response definition.
:param base_name:
Name that should be used for the reference.
:rtype: dict
:returns: JSON pointer to the o... |
Generate a Swagger 2. 0 documentation. Keyword arguments may be used to provide additional information to build methods as such ignores. | def generate(self, title=None, version=None, base_path=None,
info=None, swagger=None, **kwargs):
"""Generate a Swagger 2.0 documentation. Keyword arguments may be used
to provide additional information to build methods as such ignores.
:param title:
The name present... |
Build the Swagger paths and tags attributes from cornice service definitions. | def _build_paths(self):
"""
Build the Swagger "paths" and "tags" attributes from cornice service
definitions.
"""
paths = {}
tags = []
for service in self.services:
path, path_obj = self._extract_path_from_service(service)
service_tags = ... |
Extract path object and its parameters from service definitions. | def _extract_path_from_service(self, service):
"""
Extract path object and its parameters from service definitions.
:param service:
Cornice service to extract information from.
:rtype: dict
:returns: Path definition.
"""
path_obj = {}
path =... |
Extract swagger operation details from colander view definitions. | def _extract_operation_from_view(self, view, args):
"""
Extract swagger operation details from colander view definitions.
:param view:
View to extract information from.
:param args:
Arguments from the view decorator.
:rtype: dict
:returns: Operat... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.