INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
Setup this resource so that is ready to be used in a test. If the resource has already been created this call does nothing. | def setup(self, helper=None, **create_kwargs):
"""
Setup this resource so that is ready to be used in a test. If the
resource has already been created, this call does nothing.
For most resources, this just involves creating the resource in Docker.
:param helper:
The... |
.. todo:: | def set_helper(self, helper):
"""
.. todo::
Document this.
"""
# We don't want to "unset" in this method.
if helper is None:
return
# Get the right kind of helper if given a DockerHelper
if isinstance(helper, DockerHelper):
he... |
A decorator to inject this container into a function as a test fixture. | def as_fixture(self, name=None):
"""
A decorator to inject this container into a function as a test fixture.
"""
if name is None:
name = self.name
def deco(f):
@functools.wraps(f)
def wrapper(*args, **kw):
with self:
... |
: returns: the underlying Docker model object | def inner(self):
"""
:returns: the underlying Docker model object
"""
if not self.created:
raise RuntimeError(
'{} not created yet.'.format(self.__model_type__.__name__))
return self._inner |
Creates the container starts it and waits for it to completely start. | def setup(self, helper=None, **run_kwargs):
"""
Creates the container, starts it, and waits for it to completely start.
:param helper:
The resource helper to use, if one was not provided when this
container definition was created.
:param **run_kwargs: Keyword arg... |
Stop and remove the container if it exists. | def teardown(self):
"""
Stop and remove the container if it exists.
"""
while self._http_clients:
self._http_clients.pop().close()
if self.created:
self.halt() |
Get the container s current status from Docker. | def status(self):
"""
Get the container's current status from Docker.
If the container does not exist (before creation and after removal),
the status is ``None``.
"""
if not self.created:
return None
self.inner().reload()
return self.inner().s... |
Stop the container. The container must have been created. | def stop(self, timeout=5):
"""
Stop the container. The container must have been created.
:param timeout:
Timeout in seconds to wait for the container to stop before sending
a ``SIGKILL``. Default: 5 (half the Docker default)
"""
self.inner().stop(timeout=... |
Create the container and start it. Similar to docker run. | def run(self, fetch_image=True, **kwargs):
"""
Create the container and start it. Similar to ``docker run``.
:param fetch_image:
Whether to try pull the image if it's not found. The behaviour here
is similar to ``docker run`` and this parameter defaults to
``... |
Wait for the container to start. | def wait_for_start(self):
"""
Wait for the container to start.
By default this will wait for the log lines matching the patterns
passed in the ``wait_patterns`` parameter of the constructor using an
UnorderedMatcher. For more advanced checks for container startup, this
m... |
: param container_port: The container port.: param proto: The protocol ( tcp or udp ).: param index: The index of the mapping entry to return.: returns: A tuple of the interface IP and port on the host. | def get_host_port(self, container_port, proto='tcp', index=0):
"""
:param container_port: The container port.
:param proto: The protocol ('tcp' or 'udp').
:param index: The index of the mapping entry to return.
:returns: A tuple of the interface IP and port on the host.
"... |
Get the first mapping of the first ( lowest ) container port that has a mapping. Useful when a container publishes only one port. | def get_first_host_port(self):
"""
Get the first mapping of the first (lowest) container port that has a
mapping. Useful when a container publishes only one port.
Note that unlike the Docker API, which sorts ports lexicographically
(e.g. ``90/tcp`` > ``8000/tcp``), we sort ports... |
Get container logs. | def get_logs(self, stdout=True, stderr=True, timestamps=False, tail='all',
since=None):
"""
Get container logs.
This method does not support streaming, use :meth:`stream_logs` for
that.
"""
return self.inner().logs(
stdout=stdout, stderr=stde... |
Stream container output. | def stream_logs(self, stdout=True, stderr=True, tail='all', timeout=10.0):
"""
Stream container output.
"""
return stream_logs(
self.inner(), stdout=stdout, stderr=stderr, tail=tail,
timeout=timeout) |
Wait for logs matching the given matcher. | def wait_for_logs_matching(self, matcher, timeout=10, encoding='utf-8',
**logs_kwargs):
"""
Wait for logs matching the given matcher.
"""
wait_for_logs_matching(
self.inner(), matcher, timeout=timeout, encoding=encoding,
**logs_kwarg... |
Construct an HTTP client for this container. | def http_client(self, port=None):
"""
Construct an HTTP client for this container.
"""
# Local import to avoid potential circularity.
from seaworthy.client import ContainerHttpClient
client = ContainerHttpClient.for_container(self, container_port=port)
self._http_... |
Войти в приложение с помощью SMS. | def cmd_register(phone):
"""
Войти в приложение с помощью SMS.
"""
if phone is None:
phone = click.prompt("Номер телефона")
r = rocket.devices.register.post(data={"phone": phone})
r = handle_error(r)
id = r.json()["sms_verification"]["id"]
code = click.prompt("Введите код из SM... |
Create the module s index. | def create_autosummary_file(modules, opts):
# type: (List[unicode], Any, unicode) -> None
"""Create the module's index."""
lines = [
'API Reference',
'=============',
'',
'.. autosummary::',
' :template: api_module.rst',
' :toctree: {}'.format(opts.destdir... |
Look for every file in the directory tree and create the corresponding ReST files. | def recurse_tree(rootpath, excludes, opts):
# type: (unicode, List[unicode], Any) -> List[unicode]
"""
Look for every file in the directory tree and create the corresponding
ReST files.
"""
if INITPY in os.listdir(rootpath):
path_prefix = path.sep.join(rootpath.split(path.sep)[:-1])
... |
Parse and check the command line arguments. | def main(argv=sys.argv):
# type: (List[str]) -> int
"""Parse and check the command line arguments."""
parser = optparse.OptionParser(
usage="""\
usage: %prog [options] -o <output_path> <module_path> [exclude_pattern, ...]
Look recursively in <module_path> for Python modules and packages and create
... |
Запускает интерпретатор Python с подключенной обёрткой API Рокетбанка. | def cmd_repl():
"""
Запускает интерпретатор Python с подключенной обёрткой API Рокетбанка.
"""
import code
import rlcompleter # noqa
import readline
import sys
readline.parse_and_bind("tab: complete")
shell = code.InteractiveConsole({
"rocket": rocket,
})
shell.inte... |
Get the authorization URL to redirect the user | def get_authorization_url(self):
"""Get the authorization URL to redirect the user"""
url = self._get_oauth_url('authenticate')
query = {
'client_id': self._client_id,
'response_type': 'code',
'redirect_uri': self.callback
}
query_str = self.ur... |
After user has authorized the request token get access token with user supplied verifier. | def get_access_token(self, verifier=None):
"""
After user has authorized the request token, get access token
with user supplied verifier.
"""
try:
url = self._get_oauth_url('access_token')
#build request
query = {
'client_id': ... |
Prepare and dispatch a trait change event to a listener. | def _dispatch_change_event(self, object, trait_name, old, new, handler):
""" Prepare and dispatch a trait change event to a listener. """
# Extract the arguments needed from the handler.
args = self.argument_transform(object, trait_name, old, new)
# Send a description of the event to the change event ... |
Split value into value and exponent - of - 10 where exponent - of - 10 is a multiple of 3. This corresponds to SI prefixes. | def split(value, precision=1):
'''
Split `value` into value and "exponent-of-10", where "exponent-of-10" is a
multiple of 3. This corresponds to SI prefixes.
Returns tuple, where the second value is the "exponent-of-10" and the first
value is `value` divided by the "exponent-of-10".
Args
... |
Args: | def prefix(expof10):
'''
Args:
expof10 : Exponent of a power of 10 associated with a SI unit
character.
Returns:
str : One of the characters in "yzafpnum kMGTPEZY".
'''
prefix_levels = (len(SI_PREFIX_UNITS) - 1) // 2
si_level = expof10 // 3
if abs(si_level) > ... |
Format value to string with SI prefix using the specified precision. | def si_format(value, precision=1, format_str=u'{value} {prefix}',
exp_format_str=u'{value}e{expof10}'):
'''
Format value to string with SI prefix, using the specified precision.
Parameters
----------
value : int, float
Input value.
precision : int
Number of digits ... |
Parse a value expressed using SI prefix units to a floating point number. | def si_parse(value):
'''
Parse a value expressed using SI prefix units to a floating point number.
Parameters
----------
value : str or unicode
Value expressed using SI prefix units (as returned by :func:`si_format`
function).
.. versionchanged:: 1.0
Use unicode string... |
Set sensor name status to status. | def set_status(self, name, status):
"""
Set sensor ``name`` status to ``status``.
"""
getattr(self.system, name).status = status
return True |
Set statuses from a dictionary of format { name: status } | def set_object_status(self, statusdict):
"""
Set statuses from a dictionary of format ``{name: status}``
"""
for name, value in statusdict.items():
getattr(self.system, name).status = value
return True |
Toggle boolean - valued sensor status between True and False. | def toggle_object_status(self, objname):
"""
Toggle boolean-valued sensor status between ``True`` and ``False``.
"""
o = getattr(self.system, objname)
o.status = not o.status
self.system.flush()
return o.status |
Get sensors as a dictionary of format { name: status } | def get_sensors(self):
"""
Get sensors as a dictionary of format ``{name: status}``
"""
return {i.name: i.status for i in self.system.sensors} |
Get sensors with defined tag as a dictionary of format { name: status } | def get_websensors(self):
"""
Get sensors with defined tag as a dictionary of format ``{name: status}``
"""
return {i.name: i.status for i in self.system.sensors if self.tag & i.tags} |
Get actuators as a dictionary of format { name: status } | def get_actuators(self):
"""
Get actuators as a dictionary of format ``{name: status}``
"""
return {i.name: i.status for i in self.system.actuators} |
Return recent log entries as a string. | def log(self):
"""
Return recent log entries as a string.
"""
logserv = self.system.request_service('LogStoreService')
return logserv.lastlog(html=False) |
Посмотреть список тарифов. | def cmd_tariffs():
"""
Посмотреть список тарифов.
"""
r = rocket.tariffs.get()
r = handle_error(r)
for tariff in r.json():
click.echo("- {name} <{url}>".format(
name=click.style(tariff["name"], fg="green", bold=True),
url=tariff["url"])) |
Load system from a dump if dump file exists or create a new system if it does not exist. | def load_or_create(cls, filename=None, no_input=False, create_new=False, **kwargs):
"""
Load system from a dump, if dump file exists, or create a new system if it does not exist.
"""
parser = argparse.ArgumentParser()
parser.add_argument('--no_input', action='store_true')
... |
Save state of the system to a dump file: attr: System. filename | def save_state(self):
"""
Save state of the system to a dump file :attr:`System.filename`
"""
if not self.filename:
self.logger.error('Filename not specified. Could not save state')
return
self.logger.debug('Saving system state to %s', self.filename)
... |
A read - only property that gives the namespace of the system for evaluating commands. | def cmd_namespace(self):
"""
A read-only property that gives the namespace of the system for evaluating commands.
"""
import automate
ns = dict(list(automate.__dict__.items()) + list(self.namespace.items()))
return ns |
Give unique name for an Sensor/ Program/ Actuator object | def get_unique_name(self, obj, name='', name_from_system=''):
"""
Give unique name for an Sensor/Program/Actuator object
"""
ns = self.namespace
newname = name
if not newname:
newname = name_from_system
if not newname:
newname = u"Name... |
A property that gives a dictionary that contains services as values and their names as keys. | def services_by_name(self):
"""
A property that gives a dictionary that contains services as values and their names as keys.
"""
srvs = defaultdict(list)
for i in self.services:
srvs[i.__class__.__name__].append(i)
return srvs |
Give SystemObject instance corresponding to the name | def name_to_system_object(self, name):
"""
Give SystemObject instance corresponding to the name
"""
if isinstance(name, str):
if self.allow_name_referencing:
name = name
else:
raise NameError('System.allow_name_referencing is se... |
Get Callable for specified string ( for GUI - based editing ) | def eval_in_system_namespace(self, exec_str):
"""
Get Callable for specified string (for GUI-based editing)
"""
ns = self.cmd_namespace
try:
return eval(exec_str, ns)
except Exception as e:
self.logger.warning('Could not execute %s, gave error ... |
Register function in the system namespace. Called by Services. | def register_service_functions(self, *funcs):
"""
Register function in the system namespace. Called by Services.
"""
for func in funcs:
self.namespace[func.__name__] = func |
Register service into the system. Called by Services. | def register_service(self, service):
"""
Register service into the system. Called by Services.
"""
if service not in self.services:
self.services.append(service) |
Used by Sensors/ Actuators/ other services that need to use other services for their operations. | def request_service(self, type, id=0):
"""
Used by Sensors/Actuators/other services that need to use other services for their
operations.
"""
srvs = self.services_by_name.get(type)
if not srvs:
return
ser = srvs[id]
if not ser.system:... |
Clean up before quitting | def cleanup(self):
"""
Clean up before quitting
"""
self.pre_exit_trigger = True
self.logger.info("Shutting down %s, please wait a moment.", self.name)
for t in threading.enumerate():
if isinstance(t, TimerClass):
t.cancel()
self.... |
Execute commands in automate namespace | def cmd_exec(self, cmd):
"""
Execute commands in automate namespace
"""
if not cmd:
return
ns = self.cmd_namespace
import copy
rval = True
nscopy = copy.copy(ns)
try:
r = eval(cmd, ns)
if isinstance(r, Syste... |
This function parses in values from command line allowing for user control from the system terminal. | def handle_parser():
"""
This function parses in values from command line, allowing for user control from the system terminal.
"""
parser = argparse.ArgumentParser(description="Runs the pymoresane deconvolution algorithm with the specified "
"arguments. I... |
Writes PUML from the system. If filename is given stores result in the file. Otherwise returns result as a string. | def write_puml(self, filename=''):
"""
Writes PUML from the system. If filename is given, stores result in the file.
Otherwise returns result as a string.
"""
def get_type(o):
type = 'program'
if isinstance(o, AbstractSensor):
type ... |
Returns PUML from the system as a SVG image. Requires plantuml library. | def write_svg(self):
"""
Returns PUML from the system as a SVG image. Requires plantuml library.
"""
import plantuml
puml = self.write_puml()
server = plantuml.PlantUML(url=self.url)
svg = server.processes(puml)
return svg |
Calculate the median kneighbor distance. | def median_kneighbour_distance(X, k=5):
"""
Calculate the median kneighbor distance.
Find the distance between a set of random datapoints and
their kth nearest neighbours. This is a heuristic for setting the
kernel length scale.
"""
N_all = X.shape[0]
k = min(k, N_all)
N_subset = mi... |
Calculate centiles of distances between random pairs in a dataset. | def pair_distance_centile(X, centile, max_pairs=5000):
"""
Calculate centiles of distances between random pairs in a dataset.
This an alternative to the median kNN distance for setting the kernel
length scale.
"""
N = X.shape[0]
n_pairs = min(max_pairs, N**2)
# randorder1 = np.random.pe... |
Fit the inlier model given training data. | def fit(self, X, y=None):
"""
Fit the inlier model given training data.
This function attempts to choose reasonable defaults for parameters
sigma and rho if none are specified, which could then be adjusted
to improve performance.
Parameters
----------
X ... |
Assign classes to test data. | def predict(self, X):
"""
Assign classes to test data.
Parameters
----------
X : array
Test data, of dimension N times d (rows are examples, columns
are data dimensions)
Returns
-------
y_predicted : array
A vector of ... |
Calculate posterior probabilities of test data. | def predict_proba(self, X):
"""
Calculate posterior probabilities of test data.
Parameters
----------
X : array
Test data, of dimension N times d (rows are examples, columns
are data dimensions)
Returns:
-------
y_prob : array
... |
Generate an inlier score for each test data example. | def decision_function(self, X):
"""
Generate an inlier score for each test data example.
Parameters
----------
X : array
Test data, of dimension N times d (rows are examples, columns
are data dimensions)
Returns:
-------
scores : ... |
Calculate accuracy score. | def score(self, X, y):
"""
Calculate accuracy score.
Needed because of bug in metrics.accuracy_score when comparing
list with numpy array.
"""
predictions = self.predict(X)
true = 0.0
total = 0.0
for i in range(len(predictions)):
total... |
Calculate class probabilities for a sequence of data. | def predict_sequence(self, X, A, pi, inference='smoothing'):
"""
Calculate class probabilities for a sequence of data.
Parameters
----------
X : array
Test data, of dimension N times d (rows are time frames, columns
are data dimensions)
A : class ... |
This is used only if websocket fails | def toggle_sensor(request, sensorname):
"""
This is used only if websocket fails
"""
if service.read_only:
service.logger.warning("Could not perform operation: read only mode enabled")
raise Http404
source = request.GET.get('source', 'main')
sensor = service.system.namespace[sens... |
For manual shortcut links to perform toggle actions | def toggle_value(request, name):
"""
For manual shortcut links to perform toggle actions
"""
obj = service.system.namespace.get(name, None)
if not obj or service.read_only:
raise Http404
new_status = obj.status = not obj.status
if service.redirect_from_setters:
return HttpRes... |
For manual shortcut links to perform set value actions | def set_value(request, name, value):
"""
For manual shortcut links to perform set value actions
"""
obj = service.system.namespace.get(name, None)
if not obj or service.read_only:
raise Http404
obj.status = value
if service.redirect_from_setters:
return HttpResponseRedirect(r... |
A read - only property that gives the object type as string ; sensor actuator program other. Used by WEB interface templates. | def object_type(self):
"""
A read-only property that gives the object type as string; sensor, actuator, program, other.
Used by WEB interface templates.
"""
from .statusobject import AbstractSensor, AbstractActuator
from .program import Program
if isinsta... |
Get information about this object as a dictionary. Used by WebSocket interface to pass some relevant information to client applications. | def get_as_datadict(self):
"""
Get information about this object as a dictionary. Used by WebSocket interface to pass some
relevant information to client applications.
"""
return dict(type=self.__class__.__name__, tags=list(self.tags)) |
Set system attribute and do some initialization. Used by System. | def setup_system(self, system, name_from_system='', **kwargs):
"""
Set system attribute and do some initialization. Used by System.
"""
if not self.system:
self.system = system
name, traits = self._passed_arguments
new_name = self.system.get_unique_name(s... |
Setup Callable attributes that belong to this object. | def setup_callables(self):
"""
Setup Callable attributes that belong to this object.
"""
defaults = self.get_default_callables()
for key, value in list(defaults.items()):
self._postponed_callables.setdefault(key, value)
for key in self.callables:
... |
Function to acqure the keyfile | def grab_keyfile(cert_url):
"""
Function to acqure the keyfile
SNS keys expire and Amazon does not promise they will use the same key
for all SNS requests. So we need to keep a copy of the cert in our
cache
"""
key_cache = caches[getattr(settings, 'BOUNCY_KEY_CACHE', 'default')]
pemfil... |
Function to verify notification came from a trusted source | def verify_notification(data):
"""
Function to verify notification came from a trusted source
Returns True if verfied, False if not verified
"""
pemfile = grab_keyfile(data['SigningCertURL'])
cert = crypto.load_certificate(crypto.FILETYPE_PEM, pemfile)
signature = base64.decodestring(six.b(... |
Function to approve a SNS subscription with Amazon | def approve_subscription(data):
"""
Function to approve a SNS subscription with Amazon
We don't do a ton of verification here, past making sure that the endpoint
we're told to go to to verify the subscription is on the correct host
"""
url = data['SubscribeURL']
domain = urlparse(url).netl... |
Return a datetime from the Amazon - provided datetime string | def clean_time(time_string):
"""Return a datetime from the Amazon-provided datetime string"""
# Get a timezone-aware datetime object from the string
time = dateutil.parser.parse(time_string)
if not settings.USE_TZ:
# If timezone support is not active, convert the time to UTC and
# remove... |
Validates fields are valid and maps pseudo - fields to actual fields for a given model class. | def parse_selectors(model, fields=None, exclude=None, key_map=None, **options):
"""Validates fields are valid and maps pseudo-fields to actual fields
for a given model class.
"""
fields = fields or DEFAULT_SELECTORS
exclude = exclude or ()
key_map = key_map or {}
validated = []
for alia... |
Return the names of all locally defined fields on the model class. | def _get_local_fields(self, model):
"Return the names of all locally defined fields on the model class."
local = [f for f in model._meta.fields]
m2m = [f for f in model._meta.many_to_many]
fields = local + m2m
names = tuple([x.name for x in fields])
return {
... |
Returns the names of all related fields for model class. | def _get_related_fields(self, model):
"Returns the names of all related fields for model class."
reverse_fk = self._get_all_related_objects(model)
reverse_m2m = self._get_all_related_many_to_many_objects(model)
fields = tuple(reverse_fk + reverse_m2m)
names = tuple([x.get_access... |
Return HTML version of the table | def to_html(self, index=False, escape=False, header=True,
collapse_table=True, class_outer="table_outer", **kargs):
"""Return HTML version of the table
This is a wrapper of the to_html method of the pandas dataframe.
:param bool index: do not include the index
:param bool e... |
Change column content into HTML paragraph with background color | def add_bgcolor(self, colname, cmap='copper', mode='absmax',
threshold=2):
"""Change column content into HTML paragraph with background color
:param colname:
:param cmap: a colormap (matplotlib) or created using
colormap package (from pypi).
:param mode: type of ... |
Get object currently tracked and add a button to get back to it | def changelist_view(self, request, extra_context=None):
""" Get object currently tracked and add a button to get back to it """
extra_context = extra_context or {}
if 'object' in request.GET.keys():
value = request.GET['object'].split(':')
content_type = get_object_or_404... |
Get a list of configs. | def list(self, filter=None, type=None, sort=None, limit=None, page=None): # pylint: disable=redefined-builtin
"""Get a list of configs.
:param filter: (optional) Filters to apply as a string list.
:param type: (optional) `union` or `inter` as string.
:param sort: (optional) Sort fields ... |
Get a list of configs. Whereas list fetches a single page of configs according to its limit and page arguments iter_list returns all configs by internally making successive calls to list. | def iter_list(self, *args, **kwargs):
"""Get a list of configs. Whereas ``list`` fetches a single page of
configs according to its ``limit`` and ``page`` arguments,
``iter_list`` returns all configs by internally making
successive calls to ``list``.
:param args: Arguments that ... |
Get a config as plaintext. | def get_plaintext(self, id): # pylint: disable=invalid-name,redefined-builtin
"""Get a config as plaintext.
:param id: Config ID as an int.
:rtype: string
"""
return self.service.get_id(self.base, id, params={'format': 'text'}).text |
Create a new config. | def create(self, resource):
"""Create a new config.
:param resource: :class:`configs.Config <configs.Config>` object
:return: :class:`configs.Config <configs.Config>` object
:rtype: configs.Config
"""
schema = self.CREATE_SCHEMA
json = self.service.encode(schema,... |
Edit a config. | def edit(self, resource):
"""Edit a config.
:param resource: :class:`configs.Config <configs.Config>` object
:return: :class:`configs.Config <configs.Config>` object
:rtype: configs.Config
"""
schema = self.EDIT_SCHEMA
json = self.service.encode(schema, resource)... |
Edit shares for a config. | def edit_shares(self, id, user_ids): # pylint: disable=invalid-name,redefined-builtin
"""Edit shares for a config.
:param id: Config ID as an int.
:param user_ids: User IDs as int list.
:return: :class:`cdrouter.Share <cdrouter.Share>` list
"""
return self.service.edit_s... |
Process config contents with cdrouter - cli - check - config. | def check_config(self, contents):
"""Process config contents with cdrouter-cli -check-config.
:param contents: Config contents as string.
:return: :class:`configs.CheckConfig <configs.CheckConfig>` object
:rtype: configs.CheckConfig
"""
schema = CheckConfigSchema()
... |
Process config contents with cdrouter - cli - upgrade - config. | def upgrade_config(self, contents):
"""Process config contents with cdrouter-cli -upgrade-config.
:param contents: Config contents as string.
:return: :class:`configs.UpgradeConfig <configs.UpgradeConfig>` object
:rtype: configs.UpgradeConfig
"""
schema = UpgradeConfigSc... |
Process config contents with cdrouter - cli - print - networks - json. | def get_networks(self, contents):
"""Process config contents with cdrouter-cli -print-networks-json.
:param contents: Config contents as string.
:return: :class:`configs.Networks <configs.Networks>` object
:rtype: configs.Networks
"""
schema = NetworksSchema()
re... |
Bulk copy a set of configs. | def bulk_copy(self, ids):
"""Bulk copy a set of configs.
:param ids: Int list of config IDs.
:return: :class:`configs.Config <configs.Config>` list
"""
schema = self.GET_SCHEMA
return self.service.bulk_copy(self.base, self.RESOURCE, ids, schema) |
Bulk edit a set of configs. | def bulk_edit(self, _fields, ids=None, filter=None, type=None, all=False, testvars=None): # pylint: disable=redefined-builtin
"""Bulk edit a set of configs.
:param _fields: :class:`configs.Config <configs.Config>` object
:param ids: (optional) Int list of config IDs.
:param filter: (opt... |
Bulk delete a set of configs. | def bulk_delete(self, ids=None, filter=None, type=None, all=False): # pylint: disable=redefined-builtin
"""Bulk delete a set of configs.
:param ids: (optional) Int list of config IDs.
:param filter: (optional) String list of filters.
:param type: (optional) `union` or `inter` as string.... |
Extract token from response and set it for the user. | def response_token_setter(remote, resp):
"""Extract token from response and set it for the user.
:param remote: The remote application.
:param resp: The response.
:raises invenio_oauthclient.errors.OAuthClientError: If authorization with
remote service failed.
:raises invenio_oauthclient.er... |
Set an OAuth1 token. | def oauth1_token_setter(remote, resp, token_type='', extra_data=None):
"""Set an OAuth1 token.
:param remote: The remote application.
:param resp: The response.
:param token_type: The token type. (Default: ``''``)
:param extra_data: Extra information. (Default: ``None``)
:returns: A :class:`inv... |
Set an OAuth2 token. | def oauth2_token_setter(remote, resp, token_type='', extra_data=None):
"""Set an OAuth2 token.
The refresh_token can be used to obtain a new access_token after
the old one is expired. It is saved in the database for long term use.
A refresh_token will be present only if `access_type=offline` is include... |
Set token for user. | def token_setter(remote, token, secret='', token_type='', extra_data=None,
user=None):
"""Set token for user.
:param remote: The remote application.
:param token: The token to set.
:param token_type: The token type. (Default: ``''``)
:param extra_data: Extra information. (Default: ... |
Retrieve OAuth access token. | def token_getter(remote, token=''):
"""Retrieve OAuth access token.
Used by flask-oauthlib to get the access token when making requests.
:param remote: The remote application.
:param token: Type of token to get. Data passed from ``oauth.request()`` to
identify which token to retrieve. (Default... |
Remove OAuth access tokens from session. | def token_delete(remote, token=''):
"""Remove OAuth access tokens from session.
:param remote: The remote application.
:param token: Type of token to get. Data passed from ``oauth.request()`` to
identify which token to retrieve. (Default: ``''``)
:returns: The token.
"""
session_key = t... |
Decorator to handle exceptions. | def oauth_error_handler(f):
"""Decorator to handle exceptions."""
@wraps(f)
def inner(*args, **kwargs):
# OAuthErrors should not happen, so they are not caught here. Hence
# they will result in a 500 Internal Server Error which is what we
# are interested in.
try:
... |
Store access token in session. | def authorized_default_handler(resp, remote, *args, **kwargs):
"""Store access token in session.
Default authorized handler.
:param remote: The remote application.
:param resp: The response.
:returns: Redirect response.
"""
response_token_setter(remote, resp)
db.session.commit()
re... |
Handle sign - in/ up functionality. | def authorized_signup_handler(resp, remote, *args, **kwargs):
"""Handle sign-in/up functionality.
:param remote: The remote application.
:param resp: The response.
:returns: Redirect response.
"""
# Remove any previously stored auto register session key
session.pop(token_session_key(remote.... |
Handle unlinking of remote account. | def disconnect_handler(remote, *args, **kwargs):
"""Handle unlinking of remote account.
This default handler will just delete the remote account link. You may
wish to extend this module to perform clean-up in the remote service
before removing the link (e.g. removing install webhooks).
:param remo... |
Handle extra signup information. | def signup_handler(remote, *args, **kwargs):
"""Handle extra signup information.
:param remote: The remote application.
:returns: Redirect response or the template rendered.
"""
# User already authenticated so move on
if current_user.is_authenticated:
return redirect('/')
# Retriev... |
Remove all access tokens from session on logout. | def oauth_logout_handler(sender_app, user=None):
"""Remove all access tokens from session on logout."""
oauth = current_app.extensions['oauthlib.client']
for remote in oauth.remote_apps.values():
token_delete(remote)
db.session.commit() |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.