repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1
value | code stringlengths 75 19.8k | code_tokens listlengths 20 707 | docstring stringlengths 3 17.3k | docstring_tokens listlengths 3 222 | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1
value | idx int64 0 252k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
juju-solutions/charms.reactive | charms/reactive/bus.py | Handler.get | def get(cls, action, suffix=None):
"""
Get or register a handler for the given action.
:param func action: Callback that is called when invoking the Handler
:param func suffix: Optional suffix for the handler's ID
"""
action_id = _action_id(action, suffix)
if action_id not in cls._HANDLERS:
if LOG_OPTS['register']:
hookenv.log('Registering reactive handler for %s' % _short_action_id(action, suffix),
level=hookenv.DEBUG)
cls._HANDLERS[action_id] = cls(action, suffix)
return cls._HANDLERS[action_id] | python | def get(cls, action, suffix=None):
"""
Get or register a handler for the given action.
:param func action: Callback that is called when invoking the Handler
:param func suffix: Optional suffix for the handler's ID
"""
action_id = _action_id(action, suffix)
if action_id not in cls._HANDLERS:
if LOG_OPTS['register']:
hookenv.log('Registering reactive handler for %s' % _short_action_id(action, suffix),
level=hookenv.DEBUG)
cls._HANDLERS[action_id] = cls(action, suffix)
return cls._HANDLERS[action_id] | [
"def",
"get",
"(",
"cls",
",",
"action",
",",
"suffix",
"=",
"None",
")",
":",
"action_id",
"=",
"_action_id",
"(",
"action",
",",
"suffix",
")",
"if",
"action_id",
"not",
"in",
"cls",
".",
"_HANDLERS",
":",
"if",
"LOG_OPTS",
"[",
"'register'",
"]",
... | Get or register a handler for the given action.
:param func action: Callback that is called when invoking the Handler
:param func suffix: Optional suffix for the handler's ID | [
"Get",
"or",
"register",
"a",
"handler",
"for",
"the",
"given",
"action",
"."
] | e37e781432e77c12b63d2c739bd6cd70d3230c3a | https://github.com/juju-solutions/charms.reactive/blob/e37e781432e77c12b63d2c739bd6cd70d3230c3a/charms/reactive/bus.py#L79-L92 | train | 40,800 |
juju-solutions/charms.reactive | charms/reactive/bus.py | Handler.add_predicate | def add_predicate(self, predicate):
"""
Add a new predicate callback to this handler.
"""
_predicate = predicate
if isinstance(predicate, partial):
_predicate = 'partial(%s, %s, %s)' % (predicate.func, predicate.args, predicate.keywords)
if LOG_OPTS['register']:
hookenv.log(' Adding predicate for %s: %s' % (self.id(), _predicate), level=hookenv.DEBUG)
self._predicates.append(predicate) | python | def add_predicate(self, predicate):
"""
Add a new predicate callback to this handler.
"""
_predicate = predicate
if isinstance(predicate, partial):
_predicate = 'partial(%s, %s, %s)' % (predicate.func, predicate.args, predicate.keywords)
if LOG_OPTS['register']:
hookenv.log(' Adding predicate for %s: %s' % (self.id(), _predicate), level=hookenv.DEBUG)
self._predicates.append(predicate) | [
"def",
"add_predicate",
"(",
"self",
",",
"predicate",
")",
":",
"_predicate",
"=",
"predicate",
"if",
"isinstance",
"(",
"predicate",
",",
"partial",
")",
":",
"_predicate",
"=",
"'partial(%s, %s, %s)'",
"%",
"(",
"predicate",
".",
"func",
",",
"predicate",
... | Add a new predicate callback to this handler. | [
"Add",
"a",
"new",
"predicate",
"callback",
"to",
"this",
"handler",
"."
] | e37e781432e77c12b63d2c739bd6cd70d3230c3a | https://github.com/juju-solutions/charms.reactive/blob/e37e781432e77c12b63d2c739bd6cd70d3230c3a/charms/reactive/bus.py#L142-L151 | train | 40,801 |
juju-solutions/charms.reactive | charms/reactive/bus.py | Handler._get_args | def _get_args(self):
"""
Lazily evaluate the args.
"""
if not hasattr(self, '_args_evaled'):
# cache the args in case handler is re-invoked due to flags change
self._args_evaled = list(chain.from_iterable(self._args))
return self._args_evaled | python | def _get_args(self):
"""
Lazily evaluate the args.
"""
if not hasattr(self, '_args_evaled'):
# cache the args in case handler is re-invoked due to flags change
self._args_evaled = list(chain.from_iterable(self._args))
return self._args_evaled | [
"def",
"_get_args",
"(",
"self",
")",
":",
"if",
"not",
"hasattr",
"(",
"self",
",",
"'_args_evaled'",
")",
":",
"# cache the args in case handler is re-invoked due to flags change",
"self",
".",
"_args_evaled",
"=",
"list",
"(",
"chain",
".",
"from_iterable",
"(",
... | Lazily evaluate the args. | [
"Lazily",
"evaluate",
"the",
"args",
"."
] | e37e781432e77c12b63d2c739bd6cd70d3230c3a | https://github.com/juju-solutions/charms.reactive/blob/e37e781432e77c12b63d2c739bd6cd70d3230c3a/charms/reactive/bus.py#L167-L174 | train | 40,802 |
juju-solutions/charms.reactive | charms/reactive/bus.py | Handler.invoke | def invoke(self):
"""
Invoke this handler.
"""
args = self._get_args()
self._action(*args)
for callback in self._post_callbacks:
callback() | python | def invoke(self):
"""
Invoke this handler.
"""
args = self._get_args()
self._action(*args)
for callback in self._post_callbacks:
callback() | [
"def",
"invoke",
"(",
"self",
")",
":",
"args",
"=",
"self",
".",
"_get_args",
"(",
")",
"self",
".",
"_action",
"(",
"*",
"args",
")",
"for",
"callback",
"in",
"self",
".",
"_post_callbacks",
":",
"callback",
"(",
")"
] | Invoke this handler. | [
"Invoke",
"this",
"handler",
"."
] | e37e781432e77c12b63d2c739bd6cd70d3230c3a | https://github.com/juju-solutions/charms.reactive/blob/e37e781432e77c12b63d2c739bd6cd70d3230c3a/charms/reactive/bus.py#L176-L183 | train | 40,803 |
juju-solutions/charms.reactive | charms/reactive/bus.py | Handler.register_flags | def register_flags(self, flags):
"""
Register flags as being relevant to this handler.
Relevant flags will be used to determine if the handler should
be re-invoked due to changes in the set of active flags. If this
handler has already been invoked during this :func:`dispatch` run
and none of its relevant flags have been set or removed since then,
then the handler will be skipped.
This is also used for linting and composition purposes, to determine
if a layer has unhandled flags.
"""
self._CONSUMED_FLAGS.update(flags)
self._flags.update(flags) | python | def register_flags(self, flags):
"""
Register flags as being relevant to this handler.
Relevant flags will be used to determine if the handler should
be re-invoked due to changes in the set of active flags. If this
handler has already been invoked during this :func:`dispatch` run
and none of its relevant flags have been set or removed since then,
then the handler will be skipped.
This is also used for linting and composition purposes, to determine
if a layer has unhandled flags.
"""
self._CONSUMED_FLAGS.update(flags)
self._flags.update(flags) | [
"def",
"register_flags",
"(",
"self",
",",
"flags",
")",
":",
"self",
".",
"_CONSUMED_FLAGS",
".",
"update",
"(",
"flags",
")",
"self",
".",
"_flags",
".",
"update",
"(",
"flags",
")"
] | Register flags as being relevant to this handler.
Relevant flags will be used to determine if the handler should
be re-invoked due to changes in the set of active flags. If this
handler has already been invoked during this :func:`dispatch` run
and none of its relevant flags have been set or removed since then,
then the handler will be skipped.
This is also used for linting and composition purposes, to determine
if a layer has unhandled flags. | [
"Register",
"flags",
"as",
"being",
"relevant",
"to",
"this",
"handler",
"."
] | e37e781432e77c12b63d2c739bd6cd70d3230c3a | https://github.com/juju-solutions/charms.reactive/blob/e37e781432e77c12b63d2c739bd6cd70d3230c3a/charms/reactive/bus.py#L185-L199 | train | 40,804 |
juju-solutions/charms.reactive | charms/reactive/bus.py | ExternalHandler.invoke | def invoke(self):
"""
Call the external handler to be invoked.
"""
# flush to ensure external process can see flags as they currently
# are, and write flags (flush releases lock)
unitdata.kv().flush()
subprocess.check_call([self._filepath, '--invoke', self._test_output], env=os.environ) | python | def invoke(self):
"""
Call the external handler to be invoked.
"""
# flush to ensure external process can see flags as they currently
# are, and write flags (flush releases lock)
unitdata.kv().flush()
subprocess.check_call([self._filepath, '--invoke', self._test_output], env=os.environ) | [
"def",
"invoke",
"(",
"self",
")",
":",
"# flush to ensure external process can see flags as they currently",
"# are, and write flags (flush releases lock)",
"unitdata",
".",
"kv",
"(",
")",
".",
"flush",
"(",
")",
"subprocess",
".",
"check_call",
"(",
"[",
"self",
".",... | Call the external handler to be invoked. | [
"Call",
"the",
"external",
"handler",
"to",
"be",
"invoked",
"."
] | e37e781432e77c12b63d2c739bd6cd70d3230c3a | https://github.com/juju-solutions/charms.reactive/blob/e37e781432e77c12b63d2c739bd6cd70d3230c3a/charms/reactive/bus.py#L254-L261 | train | 40,805 |
juju-solutions/charms.reactive | charms/reactive/decorators.py | hook | def hook(*hook_patterns):
"""
Register the decorated function to run when the current hook matches any of
the ``hook_patterns``.
This decorator is generally deprecated and should only be used when
absolutely necessary.
The hook patterns can use the ``{interface:...}`` and ``{A,B,...}`` syntax
supported by :func:`~charms.reactive.bus.any_hook`.
Note that hook decorators **cannot** be combined with :func:`when` or
:func:`when_not` decorators.
"""
def _register(action):
def arg_gen():
# use a generator to defer calling of hookenv.relation_type, for tests
rel = endpoint_from_name(hookenv.relation_type())
if rel:
yield rel
handler = Handler.get(action)
handler.add_predicate(partial(_hook, hook_patterns))
handler.add_args(arg_gen())
return action
return _register | python | def hook(*hook_patterns):
"""
Register the decorated function to run when the current hook matches any of
the ``hook_patterns``.
This decorator is generally deprecated and should only be used when
absolutely necessary.
The hook patterns can use the ``{interface:...}`` and ``{A,B,...}`` syntax
supported by :func:`~charms.reactive.bus.any_hook`.
Note that hook decorators **cannot** be combined with :func:`when` or
:func:`when_not` decorators.
"""
def _register(action):
def arg_gen():
# use a generator to defer calling of hookenv.relation_type, for tests
rel = endpoint_from_name(hookenv.relation_type())
if rel:
yield rel
handler = Handler.get(action)
handler.add_predicate(partial(_hook, hook_patterns))
handler.add_args(arg_gen())
return action
return _register | [
"def",
"hook",
"(",
"*",
"hook_patterns",
")",
":",
"def",
"_register",
"(",
"action",
")",
":",
"def",
"arg_gen",
"(",
")",
":",
"# use a generator to defer calling of hookenv.relation_type, for tests",
"rel",
"=",
"endpoint_from_name",
"(",
"hookenv",
".",
"relati... | Register the decorated function to run when the current hook matches any of
the ``hook_patterns``.
This decorator is generally deprecated and should only be used when
absolutely necessary.
The hook patterns can use the ``{interface:...}`` and ``{A,B,...}`` syntax
supported by :func:`~charms.reactive.bus.any_hook`.
Note that hook decorators **cannot** be combined with :func:`when` or
:func:`when_not` decorators. | [
"Register",
"the",
"decorated",
"function",
"to",
"run",
"when",
"the",
"current",
"hook",
"matches",
"any",
"of",
"the",
"hook_patterns",
"."
] | e37e781432e77c12b63d2c739bd6cd70d3230c3a | https://github.com/juju-solutions/charms.reactive/blob/e37e781432e77c12b63d2c739bd6cd70d3230c3a/charms/reactive/decorators.py#L56-L81 | train | 40,806 |
juju-solutions/charms.reactive | charms/reactive/decorators.py | when_file_changed | def when_file_changed(*filenames, **kwargs):
"""
Register the decorated function to run when one or more files have changed.
:param list filenames: The names of one or more files to check for changes
(a callable returning the name is also accepted).
:param str hash_type: The type of hash to use for determining if a file has
changed. Defaults to 'md5'. Must be given as a kwarg.
"""
def _register(action):
handler = Handler.get(action)
handler.add_predicate(partial(any_file_changed, filenames, **kwargs))
return action
return _register | python | def when_file_changed(*filenames, **kwargs):
"""
Register the decorated function to run when one or more files have changed.
:param list filenames: The names of one or more files to check for changes
(a callable returning the name is also accepted).
:param str hash_type: The type of hash to use for determining if a file has
changed. Defaults to 'md5'. Must be given as a kwarg.
"""
def _register(action):
handler = Handler.get(action)
handler.add_predicate(partial(any_file_changed, filenames, **kwargs))
return action
return _register | [
"def",
"when_file_changed",
"(",
"*",
"filenames",
",",
"*",
"*",
"kwargs",
")",
":",
"def",
"_register",
"(",
"action",
")",
":",
"handler",
"=",
"Handler",
".",
"get",
"(",
"action",
")",
"handler",
".",
"add_predicate",
"(",
"partial",
"(",
"any_file_... | Register the decorated function to run when one or more files have changed.
:param list filenames: The names of one or more files to check for changes
(a callable returning the name is also accepted).
:param str hash_type: The type of hash to use for determining if a file has
changed. Defaults to 'md5'. Must be given as a kwarg. | [
"Register",
"the",
"decorated",
"function",
"to",
"run",
"when",
"one",
"or",
"more",
"files",
"have",
"changed",
"."
] | e37e781432e77c12b63d2c739bd6cd70d3230c3a | https://github.com/juju-solutions/charms.reactive/blob/e37e781432e77c12b63d2c739bd6cd70d3230c3a/charms/reactive/decorators.py#L179-L192 | train | 40,807 |
juju-solutions/charms.reactive | charms/reactive/decorators.py | not_unless | def not_unless(*desired_flags):
"""
Assert that the decorated function can only be called if the desired_flags
are active.
Note that, unlike :func:`when`, this does **not** trigger the decorated
function if the flags match. It **only** raises an exception if the
function is called when the flags do not match.
This is primarily for informational purposes and as a guard clause.
"""
def _decorator(func):
action_id = _action_id(func)
short_action_id = _short_action_id(func)
@wraps(func)
def _wrapped(*args, **kwargs):
active_flags = get_flags()
missing_flags = [flag for flag in desired_flags if flag not in active_flags]
if missing_flags:
hookenv.log('%s called before flag%s: %s' % (
short_action_id,
's' if len(missing_flags) > 1 else '',
', '.join(missing_flags)), hookenv.WARNING)
return func(*args, **kwargs)
_wrapped._action_id = action_id
_wrapped._short_action_id = short_action_id
return _wrapped
return _decorator | python | def not_unless(*desired_flags):
"""
Assert that the decorated function can only be called if the desired_flags
are active.
Note that, unlike :func:`when`, this does **not** trigger the decorated
function if the flags match. It **only** raises an exception if the
function is called when the flags do not match.
This is primarily for informational purposes and as a guard clause.
"""
def _decorator(func):
action_id = _action_id(func)
short_action_id = _short_action_id(func)
@wraps(func)
def _wrapped(*args, **kwargs):
active_flags = get_flags()
missing_flags = [flag for flag in desired_flags if flag not in active_flags]
if missing_flags:
hookenv.log('%s called before flag%s: %s' % (
short_action_id,
's' if len(missing_flags) > 1 else '',
', '.join(missing_flags)), hookenv.WARNING)
return func(*args, **kwargs)
_wrapped._action_id = action_id
_wrapped._short_action_id = short_action_id
return _wrapped
return _decorator | [
"def",
"not_unless",
"(",
"*",
"desired_flags",
")",
":",
"def",
"_decorator",
"(",
"func",
")",
":",
"action_id",
"=",
"_action_id",
"(",
"func",
")",
"short_action_id",
"=",
"_short_action_id",
"(",
"func",
")",
"@",
"wraps",
"(",
"func",
")",
"def",
"... | Assert that the decorated function can only be called if the desired_flags
are active.
Note that, unlike :func:`when`, this does **not** trigger the decorated
function if the flags match. It **only** raises an exception if the
function is called when the flags do not match.
This is primarily for informational purposes and as a guard clause. | [
"Assert",
"that",
"the",
"decorated",
"function",
"can",
"only",
"be",
"called",
"if",
"the",
"desired_flags",
"are",
"active",
"."
] | e37e781432e77c12b63d2c739bd6cd70d3230c3a | https://github.com/juju-solutions/charms.reactive/blob/e37e781432e77c12b63d2c739bd6cd70d3230c3a/charms/reactive/decorators.py#L195-L223 | train | 40,808 |
juju-solutions/charms.reactive | charms/reactive/decorators.py | collect_metrics | def collect_metrics():
"""
Register the decorated function to run for the collect_metrics hook.
"""
def _register(action):
handler = Handler.get(action)
handler.add_predicate(partial(_restricted_hook, 'collect-metrics'))
return action
return _register | python | def collect_metrics():
"""
Register the decorated function to run for the collect_metrics hook.
"""
def _register(action):
handler = Handler.get(action)
handler.add_predicate(partial(_restricted_hook, 'collect-metrics'))
return action
return _register | [
"def",
"collect_metrics",
"(",
")",
":",
"def",
"_register",
"(",
"action",
")",
":",
"handler",
"=",
"Handler",
".",
"get",
"(",
"action",
")",
"handler",
".",
"add_predicate",
"(",
"partial",
"(",
"_restricted_hook",
",",
"'collect-metrics'",
")",
")",
"... | Register the decorated function to run for the collect_metrics hook. | [
"Register",
"the",
"decorated",
"function",
"to",
"run",
"for",
"the",
"collect_metrics",
"hook",
"."
] | e37e781432e77c12b63d2c739bd6cd70d3230c3a | https://github.com/juju-solutions/charms.reactive/blob/e37e781432e77c12b63d2c739bd6cd70d3230c3a/charms/reactive/decorators.py#L248-L256 | train | 40,809 |
juju-solutions/charms.reactive | charms/reactive/decorators.py | _is_endpoint_method | def _is_endpoint_method(handler):
"""
from the context. Unfortunately, we can't directly detect whether
a handler is an Endpoint method, because at the time of decoration,
the class doesn't actually exist yet so it's impossible to get a
reference to it. So, we use the heuristic of seeing if the handler
takes only a single ``self`` param and there is an Endpoint class in
the handler's globals.
"""
params = signature(handler).parameters
has_self = len(params) == 1 and list(params.keys())[0] == 'self'
has_endpoint_class = any(isclass(g) and issubclass(g, Endpoint)
for g in handler.__globals__.values())
return has_self and has_endpoint_class | python | def _is_endpoint_method(handler):
"""
from the context. Unfortunately, we can't directly detect whether
a handler is an Endpoint method, because at the time of decoration,
the class doesn't actually exist yet so it's impossible to get a
reference to it. So, we use the heuristic of seeing if the handler
takes only a single ``self`` param and there is an Endpoint class in
the handler's globals.
"""
params = signature(handler).parameters
has_self = len(params) == 1 and list(params.keys())[0] == 'self'
has_endpoint_class = any(isclass(g) and issubclass(g, Endpoint)
for g in handler.__globals__.values())
return has_self and has_endpoint_class | [
"def",
"_is_endpoint_method",
"(",
"handler",
")",
":",
"params",
"=",
"signature",
"(",
"handler",
")",
".",
"parameters",
"has_self",
"=",
"len",
"(",
"params",
")",
"==",
"1",
"and",
"list",
"(",
"params",
".",
"keys",
"(",
")",
")",
"[",
"0",
"]"... | from the context. Unfortunately, we can't directly detect whether
a handler is an Endpoint method, because at the time of decoration,
the class doesn't actually exist yet so it's impossible to get a
reference to it. So, we use the heuristic of seeing if the handler
takes only a single ``self`` param and there is an Endpoint class in
the handler's globals. | [
"from",
"the",
"context",
".",
"Unfortunately",
"we",
"can",
"t",
"directly",
"detect",
"whether",
"a",
"handler",
"is",
"an",
"Endpoint",
"method",
"because",
"at",
"the",
"time",
"of",
"decoration",
"the",
"class",
"doesn",
"t",
"actually",
"exist",
"yet",... | e37e781432e77c12b63d2c739bd6cd70d3230c3a | https://github.com/juju-solutions/charms.reactive/blob/e37e781432e77c12b63d2c739bd6cd70d3230c3a/charms/reactive/decorators.py#L297-L310 | train | 40,810 |
juju-solutions/charms.reactive | charms/reactive/helpers.py | any_hook | def any_hook(*hook_patterns):
"""
Assert that the currently executing hook matches one of the given patterns.
Each pattern will match one or more hooks, and can use the following
special syntax:
* ``db-relation-{joined,changed}`` can be used to match multiple hooks
(in this case, ``db-relation-joined`` and ``db-relation-changed``).
* ``{provides:mysql}-relation-joined`` can be used to match a relation
hook by the role and interface instead of the relation name. The role
must be one of ``provides``, ``requires``, or ``peer``.
* The previous two can be combined, of course: ``{provides:mysql}-relation-{joined,changed}``
"""
current_hook = hookenv.hook_name()
# expand {role:interface} patterns
i_pat = re.compile(r'{([^:}]+):([^}]+)}')
hook_patterns = _expand_replacements(i_pat, hookenv.role_and_interface_to_relations, hook_patterns)
# expand {A,B,C,...} patterns
c_pat = re.compile(r'{((?:[^:,}]+,?)+)}')
hook_patterns = _expand_replacements(c_pat, lambda v: v.split(','), hook_patterns)
return current_hook in hook_patterns | python | def any_hook(*hook_patterns):
"""
Assert that the currently executing hook matches one of the given patterns.
Each pattern will match one or more hooks, and can use the following
special syntax:
* ``db-relation-{joined,changed}`` can be used to match multiple hooks
(in this case, ``db-relation-joined`` and ``db-relation-changed``).
* ``{provides:mysql}-relation-joined`` can be used to match a relation
hook by the role and interface instead of the relation name. The role
must be one of ``provides``, ``requires``, or ``peer``.
* The previous two can be combined, of course: ``{provides:mysql}-relation-{joined,changed}``
"""
current_hook = hookenv.hook_name()
# expand {role:interface} patterns
i_pat = re.compile(r'{([^:}]+):([^}]+)}')
hook_patterns = _expand_replacements(i_pat, hookenv.role_and_interface_to_relations, hook_patterns)
# expand {A,B,C,...} patterns
c_pat = re.compile(r'{((?:[^:,}]+,?)+)}')
hook_patterns = _expand_replacements(c_pat, lambda v: v.split(','), hook_patterns)
return current_hook in hook_patterns | [
"def",
"any_hook",
"(",
"*",
"hook_patterns",
")",
":",
"current_hook",
"=",
"hookenv",
".",
"hook_name",
"(",
")",
"# expand {role:interface} patterns",
"i_pat",
"=",
"re",
".",
"compile",
"(",
"r'{([^:}]+):([^}]+)}'",
")",
"hook_patterns",
"=",
"_expand_replacemen... | Assert that the currently executing hook matches one of the given patterns.
Each pattern will match one or more hooks, and can use the following
special syntax:
* ``db-relation-{joined,changed}`` can be used to match multiple hooks
(in this case, ``db-relation-joined`` and ``db-relation-changed``).
* ``{provides:mysql}-relation-joined`` can be used to match a relation
hook by the role and interface instead of the relation name. The role
must be one of ``provides``, ``requires``, or ``peer``.
* The previous two can be combined, of course: ``{provides:mysql}-relation-{joined,changed}`` | [
"Assert",
"that",
"the",
"currently",
"executing",
"hook",
"matches",
"one",
"of",
"the",
"given",
"patterns",
"."
] | e37e781432e77c12b63d2c739bd6cd70d3230c3a | https://github.com/juju-solutions/charms.reactive/blob/e37e781432e77c12b63d2c739bd6cd70d3230c3a/charms/reactive/helpers.py#L58-L82 | train | 40,811 |
juju-solutions/charms.reactive | charms/reactive/helpers.py | any_file_changed | def any_file_changed(filenames, hash_type='md5'):
"""
Check if any of the given files have changed since the last time this
was called.
:param list filenames: Names of files to check. Accepts callables returning
the filename.
:param str hash_type: Algorithm to use to check the files.
"""
changed = False
for filename in filenames:
if callable(filename):
filename = str(filename())
else:
filename = str(filename)
old_hash = unitdata.kv().get('reactive.files_changed.%s' % filename)
new_hash = host.file_hash(filename, hash_type=hash_type)
if old_hash != new_hash:
unitdata.kv().set('reactive.files_changed.%s' % filename, new_hash)
changed = True # mark as changed, but keep updating hashes
return changed | python | def any_file_changed(filenames, hash_type='md5'):
"""
Check if any of the given files have changed since the last time this
was called.
:param list filenames: Names of files to check. Accepts callables returning
the filename.
:param str hash_type: Algorithm to use to check the files.
"""
changed = False
for filename in filenames:
if callable(filename):
filename = str(filename())
else:
filename = str(filename)
old_hash = unitdata.kv().get('reactive.files_changed.%s' % filename)
new_hash = host.file_hash(filename, hash_type=hash_type)
if old_hash != new_hash:
unitdata.kv().set('reactive.files_changed.%s' % filename, new_hash)
changed = True # mark as changed, but keep updating hashes
return changed | [
"def",
"any_file_changed",
"(",
"filenames",
",",
"hash_type",
"=",
"'md5'",
")",
":",
"changed",
"=",
"False",
"for",
"filename",
"in",
"filenames",
":",
"if",
"callable",
"(",
"filename",
")",
":",
"filename",
"=",
"str",
"(",
"filename",
"(",
")",
")"... | Check if any of the given files have changed since the last time this
was called.
:param list filenames: Names of files to check. Accepts callables returning
the filename.
:param str hash_type: Algorithm to use to check the files. | [
"Check",
"if",
"any",
"of",
"the",
"given",
"files",
"have",
"changed",
"since",
"the",
"last",
"time",
"this",
"was",
"called",
"."
] | e37e781432e77c12b63d2c739bd6cd70d3230c3a | https://github.com/juju-solutions/charms.reactive/blob/e37e781432e77c12b63d2c739bd6cd70d3230c3a/charms/reactive/helpers.py#L85-L105 | train | 40,812 |
apiaryio/dredd-hooks-python | dredd_hooks/dredd.py | load_hook_files | def load_hook_files(pathname):
"""
Loads files either defined as a glob or a single file path
sorted by filenames.
"""
global hooks
if sys.version_info[0] > 2 and sys.version_info[1] > 4:
fsglob = sorted(glob.iglob(pathname, recursive=True))
else:
fsglob = sorted(glob.iglob(pathname))
for path in fsglob:
real_path = os.path.realpath(path)
# Append hooks file directory to the sys.path so submodules can be
# loaded too.
if os.path.dirname(real_path) not in sys.path:
sys.path.append(os.path.dirname(real_path))
module = imp.load_source(os.path.basename(path), real_path)
for name in dir(module):
obj = getattr(module, name)
if hasattr(obj, 'dredd_hooks') and callable(obj):
func_hooks = getattr(obj, 'dredd_hooks')
for hook, name in func_hooks:
if hook == BEFORE_ALL:
hooks._before_all.append(obj)
if hook == AFTER_ALL:
hooks._after_all.append(obj)
if hook == BEFORE_EACH:
hooks._before_each.append(obj)
if hook == AFTER_EACH:
hooks._after_each.append(obj)
if hook == BEFORE_EACH_VALIDATION:
hooks._before_each_validation.append(obj)
if hook == BEFORE_VALIDATION:
add_named_hook(hooks._before_validation, obj, name)
if hook == BEFORE:
add_named_hook(hooks._before, obj, name)
if hook == AFTER:
add_named_hook(hooks._after, obj, name) | python | def load_hook_files(pathname):
"""
Loads files either defined as a glob or a single file path
sorted by filenames.
"""
global hooks
if sys.version_info[0] > 2 and sys.version_info[1] > 4:
fsglob = sorted(glob.iglob(pathname, recursive=True))
else:
fsglob = sorted(glob.iglob(pathname))
for path in fsglob:
real_path = os.path.realpath(path)
# Append hooks file directory to the sys.path so submodules can be
# loaded too.
if os.path.dirname(real_path) not in sys.path:
sys.path.append(os.path.dirname(real_path))
module = imp.load_source(os.path.basename(path), real_path)
for name in dir(module):
obj = getattr(module, name)
if hasattr(obj, 'dredd_hooks') and callable(obj):
func_hooks = getattr(obj, 'dredd_hooks')
for hook, name in func_hooks:
if hook == BEFORE_ALL:
hooks._before_all.append(obj)
if hook == AFTER_ALL:
hooks._after_all.append(obj)
if hook == BEFORE_EACH:
hooks._before_each.append(obj)
if hook == AFTER_EACH:
hooks._after_each.append(obj)
if hook == BEFORE_EACH_VALIDATION:
hooks._before_each_validation.append(obj)
if hook == BEFORE_VALIDATION:
add_named_hook(hooks._before_validation, obj, name)
if hook == BEFORE:
add_named_hook(hooks._before, obj, name)
if hook == AFTER:
add_named_hook(hooks._after, obj, name) | [
"def",
"load_hook_files",
"(",
"pathname",
")",
":",
"global",
"hooks",
"if",
"sys",
".",
"version_info",
"[",
"0",
"]",
">",
"2",
"and",
"sys",
".",
"version_info",
"[",
"1",
"]",
">",
"4",
":",
"fsglob",
"=",
"sorted",
"(",
"glob",
".",
"iglob",
... | Loads files either defined as a glob or a single file path
sorted by filenames. | [
"Loads",
"files",
"either",
"defined",
"as",
"a",
"glob",
"or",
"a",
"single",
"file",
"path",
"sorted",
"by",
"filenames",
"."
] | 0a1b6d799572d3b738097ae88a7f2e571a16e7ff | https://github.com/apiaryio/dredd-hooks-python/blob/0a1b6d799572d3b738097ae88a7f2e571a16e7ff/dredd_hooks/dredd.py#L131-L170 | train | 40,813 |
juju-solutions/charms.reactive | charms/reactive/endpoints.py | Endpoint.from_flag | def from_flag(cls, flag):
"""
Return an Endpoint subclass instance based on the given flag.
The instance that is returned depends on the endpoint name embedded
in the flag. Flags should be of the form ``endpoint.{name}.extra...``,
though for legacy purposes, the ``endpoint.`` prefix can be omitted.
The ``{name}}`` portion will be passed to
:meth:`~charms.reactive.endpoints.Endpoint.from_name`.
If the flag is not set, an appropriate Endpoint subclass cannot be
found, or the flag name can't be parsed, ``None`` will be returned.
"""
if not is_flag_set(flag) or '.' not in flag:
return None
parts = flag.split('.')
if parts[0] == 'endpoint':
return cls.from_name(parts[1])
else:
# some older handlers might not use the 'endpoint' prefix
return cls.from_name(parts[0]) | python | def from_flag(cls, flag):
"""
Return an Endpoint subclass instance based on the given flag.
The instance that is returned depends on the endpoint name embedded
in the flag. Flags should be of the form ``endpoint.{name}.extra...``,
though for legacy purposes, the ``endpoint.`` prefix can be omitted.
The ``{name}}`` portion will be passed to
:meth:`~charms.reactive.endpoints.Endpoint.from_name`.
If the flag is not set, an appropriate Endpoint subclass cannot be
found, or the flag name can't be parsed, ``None`` will be returned.
"""
if not is_flag_set(flag) or '.' not in flag:
return None
parts = flag.split('.')
if parts[0] == 'endpoint':
return cls.from_name(parts[1])
else:
# some older handlers might not use the 'endpoint' prefix
return cls.from_name(parts[0]) | [
"def",
"from_flag",
"(",
"cls",
",",
"flag",
")",
":",
"if",
"not",
"is_flag_set",
"(",
"flag",
")",
"or",
"'.'",
"not",
"in",
"flag",
":",
"return",
"None",
"parts",
"=",
"flag",
".",
"split",
"(",
"'.'",
")",
"if",
"parts",
"[",
"0",
"]",
"==",... | Return an Endpoint subclass instance based on the given flag.
The instance that is returned depends on the endpoint name embedded
in the flag. Flags should be of the form ``endpoint.{name}.extra...``,
though for legacy purposes, the ``endpoint.`` prefix can be omitted.
The ``{name}}`` portion will be passed to
:meth:`~charms.reactive.endpoints.Endpoint.from_name`.
If the flag is not set, an appropriate Endpoint subclass cannot be
found, or the flag name can't be parsed, ``None`` will be returned. | [
"Return",
"an",
"Endpoint",
"subclass",
"instance",
"based",
"on",
"the",
"given",
"flag",
"."
] | e37e781432e77c12b63d2c739bd6cd70d3230c3a | https://github.com/juju-solutions/charms.reactive/blob/e37e781432e77c12b63d2c739bd6cd70d3230c3a/charms/reactive/endpoints.py#L90-L110 | train | 40,814 |
juju-solutions/charms.reactive | charms/reactive/endpoints.py | Endpoint._startup | def _startup(cls):
"""
Create Endpoint instances and manage automatic flags.
"""
for endpoint_name in sorted(hookenv.relation_types()):
# populate context based on attached relations
relf = relation_factory(endpoint_name)
if not relf or not issubclass(relf, cls):
continue
rids = sorted(hookenv.relation_ids(endpoint_name))
# ensure that relation IDs have the endpoint name prefix, in case
# juju decides to drop it at some point
rids = ['{}:{}'.format(endpoint_name, rid) if ':' not in rid
else rid for rid in rids]
endpoint = relf(endpoint_name, rids)
cls._endpoints[endpoint_name] = endpoint
endpoint.register_triggers()
endpoint._manage_departed()
endpoint._manage_flags()
for relation in endpoint.relations:
hookenv.atexit(relation._flush_data) | python | def _startup(cls):
"""
Create Endpoint instances and manage automatic flags.
"""
for endpoint_name in sorted(hookenv.relation_types()):
# populate context based on attached relations
relf = relation_factory(endpoint_name)
if not relf or not issubclass(relf, cls):
continue
rids = sorted(hookenv.relation_ids(endpoint_name))
# ensure that relation IDs have the endpoint name prefix, in case
# juju decides to drop it at some point
rids = ['{}:{}'.format(endpoint_name, rid) if ':' not in rid
else rid for rid in rids]
endpoint = relf(endpoint_name, rids)
cls._endpoints[endpoint_name] = endpoint
endpoint.register_triggers()
endpoint._manage_departed()
endpoint._manage_flags()
for relation in endpoint.relations:
hookenv.atexit(relation._flush_data) | [
"def",
"_startup",
"(",
"cls",
")",
":",
"for",
"endpoint_name",
"in",
"sorted",
"(",
"hookenv",
".",
"relation_types",
"(",
")",
")",
":",
"# populate context based on attached relations",
"relf",
"=",
"relation_factory",
"(",
"endpoint_name",
")",
"if",
"not",
... | Create Endpoint instances and manage automatic flags. | [
"Create",
"Endpoint",
"instances",
"and",
"manage",
"automatic",
"flags",
"."
] | e37e781432e77c12b63d2c739bd6cd70d3230c3a | https://github.com/juju-solutions/charms.reactive/blob/e37e781432e77c12b63d2c739bd6cd70d3230c3a/charms/reactive/endpoints.py#L113-L134 | train | 40,815 |
juju-solutions/charms.reactive | charms/reactive/endpoints.py | Endpoint.expand_name | def expand_name(self, flag):
"""
Complete a flag for this endpoint by expanding the endpoint name.
If the flag does not already contain ``{endpoint_name}``, it will be
prefixed with ``endpoint.{endpoint_name}.``. Then, any occurance of
``{endpoint_name}`` will be replaced with ``self.endpoint_name``.
"""
if '{endpoint_name}' not in flag:
flag = 'endpoint.{endpoint_name}.' + flag
# use replace rather than format to prevent any other braces or braced
# strings from being touched
return flag.replace('{endpoint_name}', self.endpoint_name) | python | def expand_name(self, flag):
"""
Complete a flag for this endpoint by expanding the endpoint name.
If the flag does not already contain ``{endpoint_name}``, it will be
prefixed with ``endpoint.{endpoint_name}.``. Then, any occurance of
``{endpoint_name}`` will be replaced with ``self.endpoint_name``.
"""
if '{endpoint_name}' not in flag:
flag = 'endpoint.{endpoint_name}.' + flag
# use replace rather than format to prevent any other braces or braced
# strings from being touched
return flag.replace('{endpoint_name}', self.endpoint_name) | [
"def",
"expand_name",
"(",
"self",
",",
"flag",
")",
":",
"if",
"'{endpoint_name}'",
"not",
"in",
"flag",
":",
"flag",
"=",
"'endpoint.{endpoint_name}.'",
"+",
"flag",
"# use replace rather than format to prevent any other braces or braced",
"# strings from being touched",
... | Complete a flag for this endpoint by expanding the endpoint name.
If the flag does not already contain ``{endpoint_name}``, it will be
prefixed with ``endpoint.{endpoint_name}.``. Then, any occurance of
``{endpoint_name}`` will be replaced with ``self.endpoint_name``. | [
"Complete",
"a",
"flag",
"for",
"this",
"endpoint",
"by",
"expanding",
"the",
"endpoint",
"name",
"."
] | e37e781432e77c12b63d2c739bd6cd70d3230c3a | https://github.com/juju-solutions/charms.reactive/blob/e37e781432e77c12b63d2c739bd6cd70d3230c3a/charms/reactive/endpoints.py#L192-L204 | train | 40,816 |
juju-solutions/charms.reactive | charms/reactive/endpoints.py | Endpoint._manage_flags | def _manage_flags(self):
"""
Manage automatic relation flags.
"""
already_joined = is_flag_set(self.expand_name('joined'))
hook_name = hookenv.hook_name()
rel_hook = hook_name.startswith(self.endpoint_name + '-relation-')
departed_hook = rel_hook and hook_name.endswith('-departed')
toggle_flag(self.expand_name('joined'), self.is_joined)
if departed_hook:
set_flag(self.expand_name('departed'))
elif self.is_joined:
clear_flag(self.expand_name('departed'))
if already_joined and not rel_hook:
# skip checking relation data outside hooks for this relation
# to save on API calls to the controller (unless we didn't have
# the joined flag before, since then we might migrating to Endpoints)
return
for unit in self.all_units:
for key, value in unit.received.items():
data_key = 'endpoint.{}.{}.{}.{}'.format(self.endpoint_name,
unit.relation.relation_id,
unit.unit_name,
key)
if data_changed(data_key, value):
set_flag(self.expand_name('changed'))
set_flag(self.expand_name('changed.{}'.format(key))) | python | def _manage_flags(self):
"""
Manage automatic relation flags.
"""
already_joined = is_flag_set(self.expand_name('joined'))
hook_name = hookenv.hook_name()
rel_hook = hook_name.startswith(self.endpoint_name + '-relation-')
departed_hook = rel_hook and hook_name.endswith('-departed')
toggle_flag(self.expand_name('joined'), self.is_joined)
if departed_hook:
set_flag(self.expand_name('departed'))
elif self.is_joined:
clear_flag(self.expand_name('departed'))
if already_joined and not rel_hook:
# skip checking relation data outside hooks for this relation
# to save on API calls to the controller (unless we didn't have
# the joined flag before, since then we might migrating to Endpoints)
return
for unit in self.all_units:
for key, value in unit.received.items():
data_key = 'endpoint.{}.{}.{}.{}'.format(self.endpoint_name,
unit.relation.relation_id,
unit.unit_name,
key)
if data_changed(data_key, value):
set_flag(self.expand_name('changed'))
set_flag(self.expand_name('changed.{}'.format(key))) | [
"def",
"_manage_flags",
"(",
"self",
")",
":",
"already_joined",
"=",
"is_flag_set",
"(",
"self",
".",
"expand_name",
"(",
"'joined'",
")",
")",
"hook_name",
"=",
"hookenv",
".",
"hook_name",
"(",
")",
"rel_hook",
"=",
"hook_name",
".",
"startswith",
"(",
... | Manage automatic relation flags. | [
"Manage",
"automatic",
"relation",
"flags",
"."
] | e37e781432e77c12b63d2c739bd6cd70d3230c3a | https://github.com/juju-solutions/charms.reactive/blob/e37e781432e77c12b63d2c739bd6cd70d3230c3a/charms/reactive/endpoints.py#L218-L248 | train | 40,817 |
juju-solutions/charms.reactive | charms/reactive/endpoints.py | Endpoint.all_departed_units | def all_departed_units(self):
"""
Collection of all units that were previously part of any relation on
this endpoint but which have since departed.
This collection is persistent and mutable. The departed units will
be kept until they are explicitly removed, to allow for reasonable
cleanup of units that have left.
Example: You need to run a command each time a unit departs the relation.
.. code-block:: python
@when('endpoint.{endpoint_name}.departed')
def handle_departed_unit(self):
for name, unit in self.all_departed_units.items():
# run the command to remove `unit` from the cluster
# ..
self.all_departed_units.clear()
clear_flag(self.expand_name('departed'))
Once a unit is departed, it will no longer show up in
:attr:`all_joined_units`. Note that units are considered departed as
soon as the departed hook is entered, which differs slightly from how
the Juju primitives behave (departing units are still returned from
``related-units`` until after the departed hook is complete).
This collection is a :class:`KeyList`, so can be used as a mapping to
look up units by their unit name, or iterated or accessed by index.
"""
if self._all_departed_units is None:
self._all_departed_units = CachedKeyList.load(
'reactive.endpoints.departed.{}'.format(self.endpoint_name),
RelatedUnit._deserialize,
'unit_name')
return self._all_departed_units | python | def all_departed_units(self):
"""
Collection of all units that were previously part of any relation on
this endpoint but which have since departed.
This collection is persistent and mutable. The departed units will
be kept until they are explicitly removed, to allow for reasonable
cleanup of units that have left.
Example: You need to run a command each time a unit departs the relation.
.. code-block:: python
@when('endpoint.{endpoint_name}.departed')
def handle_departed_unit(self):
for name, unit in self.all_departed_units.items():
# run the command to remove `unit` from the cluster
# ..
self.all_departed_units.clear()
clear_flag(self.expand_name('departed'))
Once a unit is departed, it will no longer show up in
:attr:`all_joined_units`. Note that units are considered departed as
soon as the departed hook is entered, which differs slightly from how
the Juju primitives behave (departing units are still returned from
``related-units`` until after the departed hook is complete).
This collection is a :class:`KeyList`, so can be used as a mapping to
look up units by their unit name, or iterated or accessed by index.
"""
if self._all_departed_units is None:
self._all_departed_units = CachedKeyList.load(
'reactive.endpoints.departed.{}'.format(self.endpoint_name),
RelatedUnit._deserialize,
'unit_name')
return self._all_departed_units | [
"def",
"all_departed_units",
"(",
"self",
")",
":",
"if",
"self",
".",
"_all_departed_units",
"is",
"None",
":",
"self",
".",
"_all_departed_units",
"=",
"CachedKeyList",
".",
"load",
"(",
"'reactive.endpoints.departed.{}'",
".",
"format",
"(",
"self",
".",
"end... | Collection of all units that were previously part of any relation on
this endpoint but which have since departed.
This collection is persistent and mutable. The departed units will
be kept until they are explicitly removed, to allow for reasonable
cleanup of units that have left.
Example: You need to run a command each time a unit departs the relation.
.. code-block:: python
@when('endpoint.{endpoint_name}.departed')
def handle_departed_unit(self):
for name, unit in self.all_departed_units.items():
# run the command to remove `unit` from the cluster
# ..
self.all_departed_units.clear()
clear_flag(self.expand_name('departed'))
Once a unit is departed, it will no longer show up in
:attr:`all_joined_units`. Note that units are considered departed as
soon as the departed hook is entered, which differs slightly from how
the Juju primitives behave (departing units are still returned from
``related-units`` until after the departed hook is complete).
This collection is a :class:`KeyList`, so can be used as a mapping to
look up units by their unit name, or iterated or accessed by index. | [
"Collection",
"of",
"all",
"units",
"that",
"were",
"previously",
"part",
"of",
"any",
"relation",
"on",
"this",
"endpoint",
"but",
"which",
"have",
"since",
"departed",
"."
] | e37e781432e77c12b63d2c739bd6cd70d3230c3a | https://github.com/juju-solutions/charms.reactive/blob/e37e781432e77c12b63d2c739bd6cd70d3230c3a/charms/reactive/endpoints.py#L285-L320 | train | 40,818 |
juju-solutions/charms.reactive | charms/reactive/endpoints.py | Relation.application_name | def application_name(self):
"""
The name of the remote application for this relation, or ``None``.
This is equivalent to::
relation.units[0].unit_name.split('/')[0]
"""
if self._application_name is None and self.units:
self._application_name = self.units[0].unit_name.split('/')[0]
return self._application_name | python | def application_name(self):
"""
The name of the remote application for this relation, or ``None``.
This is equivalent to::
relation.units[0].unit_name.split('/')[0]
"""
if self._application_name is None and self.units:
self._application_name = self.units[0].unit_name.split('/')[0]
return self._application_name | [
"def",
"application_name",
"(",
"self",
")",
":",
"if",
"self",
".",
"_application_name",
"is",
"None",
"and",
"self",
".",
"units",
":",
"self",
".",
"_application_name",
"=",
"self",
".",
"units",
"[",
"0",
"]",
".",
"unit_name",
".",
"split",
"(",
"... | The name of the remote application for this relation, or ``None``.
This is equivalent to::
relation.units[0].unit_name.split('/')[0] | [
"The",
"name",
"of",
"the",
"remote",
"application",
"for",
"this",
"relation",
"or",
"None",
"."
] | e37e781432e77c12b63d2c739bd6cd70d3230c3a | https://github.com/juju-solutions/charms.reactive/blob/e37e781432e77c12b63d2c739bd6cd70d3230c3a/charms/reactive/endpoints.py#L357-L367 | train | 40,819 |
juju-solutions/charms.reactive | charms/reactive/endpoints.py | Relation.joined_units | def joined_units(self):
"""
A list view of all the units joined on this relation.
This is actually a
:class:`~charms.reactive.endpoints.CombinedUnitsView`, so the units
will be in order by unit name, and you can access a merged view of all
of the units' data with ``self.units.received`` and
``self.units.received``. You should be very careful when using the
merged data collections, however, and consider carefully what will
happen when there are multiple remote units. It is probabaly better to
iterate over each unit and handle its data individually. See
:class:`~charms.reactive.endpoints.CombinedUnitsView` for an
explanation of how the merged data collections work.
The view can be iterated and indexed as a list, or you can look up units
by their unit name. For example::
by_index = relation.units[0]
by_name = relation.units['unit/0']
assert by_index is by_name
assert all(unit is relation.units[unit.unit_name]
for unit in relation.units)
print(', '.join(relation.units.keys()))
"""
if self._units is None:
self._units = CombinedUnitsView([
RelatedUnit(self, unit_name) for unit_name in
sorted(hookenv.related_units(self.relation_id))
])
return self._units | python | def joined_units(self):
"""
A list view of all the units joined on this relation.
This is actually a
:class:`~charms.reactive.endpoints.CombinedUnitsView`, so the units
will be in order by unit name, and you can access a merged view of all
of the units' data with ``self.units.received`` and
``self.units.received``. You should be very careful when using the
merged data collections, however, and consider carefully what will
happen when there are multiple remote units. It is probabaly better to
iterate over each unit and handle its data individually. See
:class:`~charms.reactive.endpoints.CombinedUnitsView` for an
explanation of how the merged data collections work.
The view can be iterated and indexed as a list, or you can look up units
by their unit name. For example::
by_index = relation.units[0]
by_name = relation.units['unit/0']
assert by_index is by_name
assert all(unit is relation.units[unit.unit_name]
for unit in relation.units)
print(', '.join(relation.units.keys()))
"""
if self._units is None:
self._units = CombinedUnitsView([
RelatedUnit(self, unit_name) for unit_name in
sorted(hookenv.related_units(self.relation_id))
])
return self._units | [
"def",
"joined_units",
"(",
"self",
")",
":",
"if",
"self",
".",
"_units",
"is",
"None",
":",
"self",
".",
"_units",
"=",
"CombinedUnitsView",
"(",
"[",
"RelatedUnit",
"(",
"self",
",",
"unit_name",
")",
"for",
"unit_name",
"in",
"sorted",
"(",
"hookenv"... | A list view of all the units joined on this relation.
This is actually a
:class:`~charms.reactive.endpoints.CombinedUnitsView`, so the units
will be in order by unit name, and you can access a merged view of all
of the units' data with ``self.units.received`` and
``self.units.received``. You should be very careful when using the
merged data collections, however, and consider carefully what will
happen when there are multiple remote units. It is probabaly better to
iterate over each unit and handle its data individually. See
:class:`~charms.reactive.endpoints.CombinedUnitsView` for an
explanation of how the merged data collections work.
The view can be iterated and indexed as a list, or you can look up units
by their unit name. For example::
by_index = relation.units[0]
by_name = relation.units['unit/0']
assert by_index is by_name
assert all(unit is relation.units[unit.unit_name]
for unit in relation.units)
print(', '.join(relation.units.keys())) | [
"A",
"list",
"view",
"of",
"all",
"the",
"units",
"joined",
"on",
"this",
"relation",
"."
] | e37e781432e77c12b63d2c739bd6cd70d3230c3a | https://github.com/juju-solutions/charms.reactive/blob/e37e781432e77c12b63d2c739bd6cd70d3230c3a/charms/reactive/endpoints.py#L378-L408 | train | 40,820 |
juju-solutions/charms.reactive | charms/reactive/endpoints.py | Relation._flush_data | def _flush_data(self):
"""
If this relation's local unit data has been modified, publish it on the
relation. This should be automatically called.
"""
if self._data and self._data.modified:
hookenv.relation_set(self.relation_id, dict(self.to_publish.data)) | python | def _flush_data(self):
"""
If this relation's local unit data has been modified, publish it on the
relation. This should be automatically called.
"""
if self._data and self._data.modified:
hookenv.relation_set(self.relation_id, dict(self.to_publish.data)) | [
"def",
"_flush_data",
"(",
"self",
")",
":",
"if",
"self",
".",
"_data",
"and",
"self",
".",
"_data",
".",
"modified",
":",
"hookenv",
".",
"relation_set",
"(",
"self",
".",
"relation_id",
",",
"dict",
"(",
"self",
".",
"to_publish",
".",
"data",
")",
... | If this relation's local unit data has been modified, publish it on the
relation. This should be automatically called. | [
"If",
"this",
"relation",
"s",
"local",
"unit",
"data",
"has",
"been",
"modified",
"publish",
"it",
"on",
"the",
"relation",
".",
"This",
"should",
"be",
"automatically",
"called",
"."
] | e37e781432e77c12b63d2c739bd6cd70d3230c3a | https://github.com/juju-solutions/charms.reactive/blob/e37e781432e77c12b63d2c739bd6cd70d3230c3a/charms/reactive/endpoints.py#L449-L455 | train | 40,821 |
juju-solutions/charms.reactive | charms/reactive/endpoints.py | CachedKeyList.load | def load(cls, cache_key, deserializer, key_attr):
"""
Load the persisted cache and return a new instance of this class.
"""
items = unitdata.kv().get(cache_key) or []
return cls(cache_key,
[deserializer(item) for item in items],
key_attr) | python | def load(cls, cache_key, deserializer, key_attr):
"""
Load the persisted cache and return a new instance of this class.
"""
items = unitdata.kv().get(cache_key) or []
return cls(cache_key,
[deserializer(item) for item in items],
key_attr) | [
"def",
"load",
"(",
"cls",
",",
"cache_key",
",",
"deserializer",
",",
"key_attr",
")",
":",
"items",
"=",
"unitdata",
".",
"kv",
"(",
")",
".",
"get",
"(",
"cache_key",
")",
"or",
"[",
"]",
"return",
"cls",
"(",
"cache_key",
",",
"[",
"deserializer"... | Load the persisted cache and return a new instance of this class. | [
"Load",
"the",
"persisted",
"cache",
"and",
"return",
"a",
"new",
"instance",
"of",
"this",
"class",
"."
] | e37e781432e77c12b63d2c739bd6cd70d3230c3a | https://github.com/juju-solutions/charms.reactive/blob/e37e781432e77c12b63d2c739bd6cd70d3230c3a/charms/reactive/endpoints.py#L613-L620 | train | 40,822 |
podio/podio-py | pypodio2/api.py | AuthorizingClient | def AuthorizingClient(domain, auth, user_agent=None):
"""Creates a Podio client using an auth object."""
http_transport = transport.HttpTransport(domain, build_headers(auth, user_agent))
return client.Client(http_transport) | python | def AuthorizingClient(domain, auth, user_agent=None):
"""Creates a Podio client using an auth object."""
http_transport = transport.HttpTransport(domain, build_headers(auth, user_agent))
return client.Client(http_transport) | [
"def",
"AuthorizingClient",
"(",
"domain",
",",
"auth",
",",
"user_agent",
"=",
"None",
")",
":",
"http_transport",
"=",
"transport",
".",
"HttpTransport",
"(",
"domain",
",",
"build_headers",
"(",
"auth",
",",
"user_agent",
")",
")",
"return",
"client",
"."... | Creates a Podio client using an auth object. | [
"Creates",
"a",
"Podio",
"client",
"using",
"an",
"auth",
"object",
"."
] | 5ce956034a06c98b0ef18fcd940b36da0908ad6c | https://github.com/podio/podio-py/blob/5ce956034a06c98b0ef18fcd940b36da0908ad6c/pypodio2/api.py#L28-L31 | train | 40,823 |
benoitguigal/python-epson-printer | epson_printer/epsonprinter.py | EpsonPrinter.write_this | def write_this(func):
"""
Decorator that writes the bytes to the wire
"""
@wraps(func)
def wrapper(self, *args, **kwargs):
byte_array = func(self, *args, **kwargs)
self.write_bytes(byte_array)
return wrapper | python | def write_this(func):
"""
Decorator that writes the bytes to the wire
"""
@wraps(func)
def wrapper(self, *args, **kwargs):
byte_array = func(self, *args, **kwargs)
self.write_bytes(byte_array)
return wrapper | [
"def",
"write_this",
"(",
"func",
")",
":",
"@",
"wraps",
"(",
"func",
")",
"def",
"wrapper",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"byte_array",
"=",
"func",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
"... | Decorator that writes the bytes to the wire | [
"Decorator",
"that",
"writes",
"the",
"bytes",
"to",
"the",
"wire"
] | 7d89b2f21bc76d2cc4d5ad548e19a356ca92fbc5 | https://github.com/benoitguigal/python-epson-printer/blob/7d89b2f21bc76d2cc4d5ad548e19a356ca92fbc5/epson_printer/epsonprinter.py#L199-L207 | train | 40,824 |
benoitguigal/python-epson-printer | epson_printer/epsonprinter.py | EpsonPrinter.print_images | def print_images(self, *printable_images):
"""
This method allows printing several images in one shot. This is useful if the client code does not want the
printer to make pause during printing
"""
printable_image = reduce(lambda x, y: x.append(y), list(printable_images))
self.print_image(printable_image) | python | def print_images(self, *printable_images):
"""
This method allows printing several images in one shot. This is useful if the client code does not want the
printer to make pause during printing
"""
printable_image = reduce(lambda x, y: x.append(y), list(printable_images))
self.print_image(printable_image) | [
"def",
"print_images",
"(",
"self",
",",
"*",
"printable_images",
")",
":",
"printable_image",
"=",
"reduce",
"(",
"lambda",
"x",
",",
"y",
":",
"x",
".",
"append",
"(",
"y",
")",
",",
"list",
"(",
"printable_images",
")",
")",
"self",
".",
"print_imag... | This method allows printing several images in one shot. This is useful if the client code does not want the
printer to make pause during printing | [
"This",
"method",
"allows",
"printing",
"several",
"images",
"in",
"one",
"shot",
".",
"This",
"is",
"useful",
"if",
"the",
"client",
"code",
"does",
"not",
"want",
"the",
"printer",
"to",
"make",
"pause",
"during",
"printing"
] | 7d89b2f21bc76d2cc4d5ad548e19a356ca92fbc5 | https://github.com/benoitguigal/python-epson-printer/blob/7d89b2f21bc76d2cc4d5ad548e19a356ca92fbc5/epson_printer/epsonprinter.py#L258-L264 | train | 40,825 |
podio/podio-py | pypodio2/encode.py | MultipartParam.from_file | def from_file(cls, paramname, filename):
"""Returns a new MultipartParam object constructed from the local
file at ``filename``.
``filesize`` is determined by os.path.getsize(``filename``)
``filetype`` is determined by mimetypes.guess_type(``filename``)[0]
``filename`` is set to os.path.basename(``filename``)
"""
return cls(paramname, filename=os.path.basename(filename),
filetype=mimetypes.guess_type(filename)[0],
filesize=os.path.getsize(filename),
fileobj=open(filename, "rb")) | python | def from_file(cls, paramname, filename):
"""Returns a new MultipartParam object constructed from the local
file at ``filename``.
``filesize`` is determined by os.path.getsize(``filename``)
``filetype`` is determined by mimetypes.guess_type(``filename``)[0]
``filename`` is set to os.path.basename(``filename``)
"""
return cls(paramname, filename=os.path.basename(filename),
filetype=mimetypes.guess_type(filename)[0],
filesize=os.path.getsize(filename),
fileobj=open(filename, "rb")) | [
"def",
"from_file",
"(",
"cls",
",",
"paramname",
",",
"filename",
")",
":",
"return",
"cls",
"(",
"paramname",
",",
"filename",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"filename",
")",
",",
"filetype",
"=",
"mimetypes",
".",
"guess_type",
"(",
"... | Returns a new MultipartParam object constructed from the local
file at ``filename``.
``filesize`` is determined by os.path.getsize(``filename``)
``filetype`` is determined by mimetypes.guess_type(``filename``)[0]
``filename`` is set to os.path.basename(``filename``) | [
"Returns",
"a",
"new",
"MultipartParam",
"object",
"constructed",
"from",
"the",
"local",
"file",
"at",
"filename",
"."
] | 5ce956034a06c98b0ef18fcd940b36da0908ad6c | https://github.com/podio/podio-py/blob/5ce956034a06c98b0ef18fcd940b36da0908ad6c/pypodio2/encode.py#L143-L157 | train | 40,826 |
podio/podio-py | pypodio2/encode.py | MultipartParam.from_params | def from_params(cls, params):
"""Returns a list of MultipartParam objects from a sequence of
name, value pairs, MultipartParam instances,
or from a mapping of names to values
The values may be strings or file objects, or MultipartParam objects.
MultipartParam object names must match the given names in the
name,value pairs or mapping, if applicable."""
if hasattr(params, 'items'):
params = params.items()
retval = []
for item in params:
if isinstance(item, cls):
retval.append(item)
continue
name, value = item
if isinstance(value, cls):
assert value.name == name
retval.append(value)
continue
if hasattr(value, 'read'):
# Looks like a file object
filename = getattr(value, 'name', None)
if filename is not None:
filetype = mimetypes.guess_type(filename)[0]
else:
filetype = None
retval.append(cls(name=name, filename=filename,
filetype=filetype, fileobj=value))
else:
retval.append(cls(name, value))
return retval | python | def from_params(cls, params):
"""Returns a list of MultipartParam objects from a sequence of
name, value pairs, MultipartParam instances,
or from a mapping of names to values
The values may be strings or file objects, or MultipartParam objects.
MultipartParam object names must match the given names in the
name,value pairs or mapping, if applicable."""
if hasattr(params, 'items'):
params = params.items()
retval = []
for item in params:
if isinstance(item, cls):
retval.append(item)
continue
name, value = item
if isinstance(value, cls):
assert value.name == name
retval.append(value)
continue
if hasattr(value, 'read'):
# Looks like a file object
filename = getattr(value, 'name', None)
if filename is not None:
filetype = mimetypes.guess_type(filename)[0]
else:
filetype = None
retval.append(cls(name=name, filename=filename,
filetype=filetype, fileobj=value))
else:
retval.append(cls(name, value))
return retval | [
"def",
"from_params",
"(",
"cls",
",",
"params",
")",
":",
"if",
"hasattr",
"(",
"params",
",",
"'items'",
")",
":",
"params",
"=",
"params",
".",
"items",
"(",
")",
"retval",
"=",
"[",
"]",
"for",
"item",
"in",
"params",
":",
"if",
"isinstance",
"... | Returns a list of MultipartParam objects from a sequence of
name, value pairs, MultipartParam instances,
or from a mapping of names to values
The values may be strings or file objects, or MultipartParam objects.
MultipartParam object names must match the given names in the
name,value pairs or mapping, if applicable. | [
"Returns",
"a",
"list",
"of",
"MultipartParam",
"objects",
"from",
"a",
"sequence",
"of",
"name",
"value",
"pairs",
"MultipartParam",
"instances",
"or",
"from",
"a",
"mapping",
"of",
"names",
"to",
"values"
] | 5ce956034a06c98b0ef18fcd940b36da0908ad6c | https://github.com/podio/podio-py/blob/5ce956034a06c98b0ef18fcd940b36da0908ad6c/pypodio2/encode.py#L160-L193 | train | 40,827 |
podio/podio-py | pypodio2/encode.py | MultipartParam.encode_hdr | def encode_hdr(self, boundary):
"""Returns the header of the encoding of this parameter"""
boundary = encode_and_quote(boundary)
headers = ["--%s" % boundary]
if self.filename:
disposition = 'form-data; name="%s"; filename="%s"' % (self.name,
self.filename)
else:
disposition = 'form-data; name="%s"' % self.name
headers.append("Content-Disposition: %s" % disposition)
if self.filetype:
filetype = self.filetype
else:
filetype = "text/plain; charset=utf-8"
headers.append("Content-Type: %s" % filetype)
headers.append("")
headers.append("")
return "\r\n".join(headers) | python | def encode_hdr(self, boundary):
"""Returns the header of the encoding of this parameter"""
boundary = encode_and_quote(boundary)
headers = ["--%s" % boundary]
if self.filename:
disposition = 'form-data; name="%s"; filename="%s"' % (self.name,
self.filename)
else:
disposition = 'form-data; name="%s"' % self.name
headers.append("Content-Disposition: %s" % disposition)
if self.filetype:
filetype = self.filetype
else:
filetype = "text/plain; charset=utf-8"
headers.append("Content-Type: %s" % filetype)
headers.append("")
headers.append("")
return "\r\n".join(headers) | [
"def",
"encode_hdr",
"(",
"self",
",",
"boundary",
")",
":",
"boundary",
"=",
"encode_and_quote",
"(",
"boundary",
")",
"headers",
"=",
"[",
"\"--%s\"",
"%",
"boundary",
"]",
"if",
"self",
".",
"filename",
":",
"disposition",
"=",
"'form-data; name=\"%s\"; fil... | Returns the header of the encoding of this parameter | [
"Returns",
"the",
"header",
"of",
"the",
"encoding",
"of",
"this",
"parameter"
] | 5ce956034a06c98b0ef18fcd940b36da0908ad6c | https://github.com/podio/podio-py/blob/5ce956034a06c98b0ef18fcd940b36da0908ad6c/pypodio2/encode.py#L195-L219 | train | 40,828 |
podio/podio-py | pypodio2/encode.py | MultipartParam.encode | def encode(self, boundary):
"""Returns the string encoding of this parameter"""
if self.value is None:
value = self.fileobj.read()
else:
value = self.value
if re.search("^--%s$" % re.escape(boundary), value, re.M):
raise ValueError("boundary found in encoded string")
return "%s%s\r\n" % (self.encode_hdr(boundary), value) | python | def encode(self, boundary):
"""Returns the string encoding of this parameter"""
if self.value is None:
value = self.fileobj.read()
else:
value = self.value
if re.search("^--%s$" % re.escape(boundary), value, re.M):
raise ValueError("boundary found in encoded string")
return "%s%s\r\n" % (self.encode_hdr(boundary), value) | [
"def",
"encode",
"(",
"self",
",",
"boundary",
")",
":",
"if",
"self",
".",
"value",
"is",
"None",
":",
"value",
"=",
"self",
".",
"fileobj",
".",
"read",
"(",
")",
"else",
":",
"value",
"=",
"self",
".",
"value",
"if",
"re",
".",
"search",
"(",
... | Returns the string encoding of this parameter | [
"Returns",
"the",
"string",
"encoding",
"of",
"this",
"parameter"
] | 5ce956034a06c98b0ef18fcd940b36da0908ad6c | https://github.com/podio/podio-py/blob/5ce956034a06c98b0ef18fcd940b36da0908ad6c/pypodio2/encode.py#L221-L231 | train | 40,829 |
podio/podio-py | pypodio2/encode.py | MultipartParam.iter_encode | def iter_encode(self, boundary, blocksize=4096):
"""Yields the encoding of this parameter
If self.fileobj is set, then blocks of ``blocksize`` bytes are read and
yielded."""
total = self.get_size(boundary)
current = 0
if self.value is not None:
block = self.encode(boundary)
current += len(block)
yield block
if self.cb:
self.cb(self, current, total)
else:
block = self.encode_hdr(boundary)
current += len(block)
yield block
if self.cb:
self.cb(self, current, total)
last_block = ""
encoded_boundary = "--%s" % encode_and_quote(boundary)
boundary_exp = re.compile("^%s$" % re.escape(encoded_boundary),
re.M)
while True:
block = self.fileobj.read(blocksize)
if not block:
current += 2
yield "\r\n"
if self.cb:
self.cb(self, current, total)
break
last_block += block
if boundary_exp.search(last_block):
raise ValueError("boundary found in file data")
last_block = last_block[-len(encoded_boundary) - 2:]
current += len(block)
yield block
if self.cb:
self.cb(self, current, total) | python | def iter_encode(self, boundary, blocksize=4096):
"""Yields the encoding of this parameter
If self.fileobj is set, then blocks of ``blocksize`` bytes are read and
yielded."""
total = self.get_size(boundary)
current = 0
if self.value is not None:
block = self.encode(boundary)
current += len(block)
yield block
if self.cb:
self.cb(self, current, total)
else:
block = self.encode_hdr(boundary)
current += len(block)
yield block
if self.cb:
self.cb(self, current, total)
last_block = ""
encoded_boundary = "--%s" % encode_and_quote(boundary)
boundary_exp = re.compile("^%s$" % re.escape(encoded_boundary),
re.M)
while True:
block = self.fileobj.read(blocksize)
if not block:
current += 2
yield "\r\n"
if self.cb:
self.cb(self, current, total)
break
last_block += block
if boundary_exp.search(last_block):
raise ValueError("boundary found in file data")
last_block = last_block[-len(encoded_boundary) - 2:]
current += len(block)
yield block
if self.cb:
self.cb(self, current, total) | [
"def",
"iter_encode",
"(",
"self",
",",
"boundary",
",",
"blocksize",
"=",
"4096",
")",
":",
"total",
"=",
"self",
".",
"get_size",
"(",
"boundary",
")",
"current",
"=",
"0",
"if",
"self",
".",
"value",
"is",
"not",
"None",
":",
"block",
"=",
"self",... | Yields the encoding of this parameter
If self.fileobj is set, then blocks of ``blocksize`` bytes are read and
yielded. | [
"Yields",
"the",
"encoding",
"of",
"this",
"parameter",
"If",
"self",
".",
"fileobj",
"is",
"set",
"then",
"blocks",
"of",
"blocksize",
"bytes",
"are",
"read",
"and",
"yielded",
"."
] | 5ce956034a06c98b0ef18fcd940b36da0908ad6c | https://github.com/podio/podio-py/blob/5ce956034a06c98b0ef18fcd940b36da0908ad6c/pypodio2/encode.py#L233-L270 | train | 40,830 |
podio/podio-py | pypodio2/encode.py | MultipartParam.get_size | def get_size(self, boundary):
"""Returns the size in bytes that this param will be when encoded
with the given boundary."""
if self.filesize is not None:
valuesize = self.filesize
else:
valuesize = len(self.value)
return len(self.encode_hdr(boundary)) + 2 + valuesize | python | def get_size(self, boundary):
"""Returns the size in bytes that this param will be when encoded
with the given boundary."""
if self.filesize is not None:
valuesize = self.filesize
else:
valuesize = len(self.value)
return len(self.encode_hdr(boundary)) + 2 + valuesize | [
"def",
"get_size",
"(",
"self",
",",
"boundary",
")",
":",
"if",
"self",
".",
"filesize",
"is",
"not",
"None",
":",
"valuesize",
"=",
"self",
".",
"filesize",
"else",
":",
"valuesize",
"=",
"len",
"(",
"self",
".",
"value",
")",
"return",
"len",
"(",... | Returns the size in bytes that this param will be when encoded
with the given boundary. | [
"Returns",
"the",
"size",
"in",
"bytes",
"that",
"this",
"param",
"will",
"be",
"when",
"encoded",
"with",
"the",
"given",
"boundary",
"."
] | 5ce956034a06c98b0ef18fcd940b36da0908ad6c | https://github.com/podio/podio-py/blob/5ce956034a06c98b0ef18fcd940b36da0908ad6c/pypodio2/encode.py#L272-L280 | train | 40,831 |
podio/podio-py | pypodio2/areas.py | Area.get_options | def get_options(silent=False, hook=True):
"""
Generate a query string with the appropriate options.
:param silent: If set to true, the object will not be bumped up in the stream and
notifications will not be generated.
:type silent: bool
:param hook: True if hooks should be executed for the change, false otherwise.
:type hook: bool
:return: The generated query string
:rtype: str
"""
options_ = {}
if silent:
options_['silent'] = silent
if not hook:
options_['hook'] = hook
if options_:
return '?' + urlencode(options_).lower()
else:
return '' | python | def get_options(silent=False, hook=True):
"""
Generate a query string with the appropriate options.
:param silent: If set to true, the object will not be bumped up in the stream and
notifications will not be generated.
:type silent: bool
:param hook: True if hooks should be executed for the change, false otherwise.
:type hook: bool
:return: The generated query string
:rtype: str
"""
options_ = {}
if silent:
options_['silent'] = silent
if not hook:
options_['hook'] = hook
if options_:
return '?' + urlencode(options_).lower()
else:
return '' | [
"def",
"get_options",
"(",
"silent",
"=",
"False",
",",
"hook",
"=",
"True",
")",
":",
"options_",
"=",
"{",
"}",
"if",
"silent",
":",
"options_",
"[",
"'silent'",
"]",
"=",
"silent",
"if",
"not",
"hook",
":",
"options_",
"[",
"'hook'",
"]",
"=",
"... | Generate a query string with the appropriate options.
:param silent: If set to true, the object will not be bumped up in the stream and
notifications will not be generated.
:type silent: bool
:param hook: True if hooks should be executed for the change, false otherwise.
:type hook: bool
:return: The generated query string
:rtype: str | [
"Generate",
"a",
"query",
"string",
"with",
"the",
"appropriate",
"options",
"."
] | 5ce956034a06c98b0ef18fcd940b36da0908ad6c | https://github.com/podio/podio-py/blob/5ce956034a06c98b0ef18fcd940b36da0908ad6c/pypodio2/areas.py#L22-L42 | train | 40,832 |
podio/podio-py | pypodio2/areas.py | Space.find_by_url | def find_by_url(self, space_url, id_only=True):
"""
Returns a space ID given the URL of the space.
:param space_url: URL of the Space
:param id_only: ?
:return: space_id: Space url
:rtype: str
"""
resp = self.transport.GET(url='/space/url?%s' % urlencode({'url': space_url}))
if id_only:
return resp['space_id']
return resp | python | def find_by_url(self, space_url, id_only=True):
"""
Returns a space ID given the URL of the space.
:param space_url: URL of the Space
:param id_only: ?
:return: space_id: Space url
:rtype: str
"""
resp = self.transport.GET(url='/space/url?%s' % urlencode({'url': space_url}))
if id_only:
return resp['space_id']
return resp | [
"def",
"find_by_url",
"(",
"self",
",",
"space_url",
",",
"id_only",
"=",
"True",
")",
":",
"resp",
"=",
"self",
".",
"transport",
".",
"GET",
"(",
"url",
"=",
"'/space/url?%s'",
"%",
"urlencode",
"(",
"{",
"'url'",
":",
"space_url",
"}",
")",
")",
"... | Returns a space ID given the URL of the space.
:param space_url: URL of the Space
:param id_only: ?
:return: space_id: Space url
:rtype: str | [
"Returns",
"a",
"space",
"ID",
"given",
"the",
"URL",
"of",
"the",
"space",
"."
] | 5ce956034a06c98b0ef18fcd940b36da0908ad6c | https://github.com/podio/podio-py/blob/5ce956034a06c98b0ef18fcd940b36da0908ad6c/pypodio2/areas.py#L323-L335 | train | 40,833 |
podio/podio-py | pypodio2/areas.py | Stream.find_by_ref | def find_by_ref(self, ref_type, ref_id):
"""
Returns an object of type "item", "status" or "task" as a
stream object. This is useful when a new status has been
posted and should be rendered directly in the stream without
reloading the entire stream.
For details, see: https://developers.podio.com/doc/stream/get-stream-object-80054
"""
return self.transport.GET(url='/stream/%s/%s' % (ref_type, ref_id)) | python | def find_by_ref(self, ref_type, ref_id):
"""
Returns an object of type "item", "status" or "task" as a
stream object. This is useful when a new status has been
posted and should be rendered directly in the stream without
reloading the entire stream.
For details, see: https://developers.podio.com/doc/stream/get-stream-object-80054
"""
return self.transport.GET(url='/stream/%s/%s' % (ref_type, ref_id)) | [
"def",
"find_by_ref",
"(",
"self",
",",
"ref_type",
",",
"ref_id",
")",
":",
"return",
"self",
".",
"transport",
".",
"GET",
"(",
"url",
"=",
"'/stream/%s/%s'",
"%",
"(",
"ref_type",
",",
"ref_id",
")",
")"
] | Returns an object of type "item", "status" or "task" as a
stream object. This is useful when a new status has been
posted and should be rendered directly in the stream without
reloading the entire stream.
For details, see: https://developers.podio.com/doc/stream/get-stream-object-80054 | [
"Returns",
"an",
"object",
"of",
"type",
"item",
"status",
"or",
"task",
"as",
"a",
"stream",
"object",
".",
"This",
"is",
"useful",
"when",
"a",
"new",
"status",
"has",
"been",
"posted",
"and",
"should",
"be",
"rendered",
"directly",
"in",
"the",
"strea... | 5ce956034a06c98b0ef18fcd940b36da0908ad6c | https://github.com/podio/podio-py/blob/5ce956034a06c98b0ef18fcd940b36da0908ad6c/pypodio2/areas.py#L415-L424 | train | 40,834 |
podio/podio-py | pypodio2/areas.py | Files.find_raw | def find_raw(self, file_id):
"""Returns raw file as string. Pass to a file object"""
raw_handler = lambda resp, data: data
return self.transport.GET(url='/file/%d/raw' % file_id, handler=raw_handler) | python | def find_raw(self, file_id):
"""Returns raw file as string. Pass to a file object"""
raw_handler = lambda resp, data: data
return self.transport.GET(url='/file/%d/raw' % file_id, handler=raw_handler) | [
"def",
"find_raw",
"(",
"self",
",",
"file_id",
")",
":",
"raw_handler",
"=",
"lambda",
"resp",
",",
"data",
":",
"data",
"return",
"self",
".",
"transport",
".",
"GET",
"(",
"url",
"=",
"'/file/%d/raw'",
"%",
"file_id",
",",
"handler",
"=",
"raw_handler... | Returns raw file as string. Pass to a file object | [
"Returns",
"raw",
"file",
"as",
"string",
".",
"Pass",
"to",
"a",
"file",
"object"
] | 5ce956034a06c98b0ef18fcd940b36da0908ad6c | https://github.com/podio/podio-py/blob/5ce956034a06c98b0ef18fcd940b36da0908ad6c/pypodio2/areas.py#L509-L512 | train | 40,835 |
podio/podio-py | pypodio2/areas.py | Files.create | def create(self, filename, filedata):
"""Create a file from raw data"""
attributes = {'filename': filename,
'source': filedata}
return self.transport.POST(url='/file/v2/', body=attributes, type='multipart/form-data') | python | def create(self, filename, filedata):
"""Create a file from raw data"""
attributes = {'filename': filename,
'source': filedata}
return self.transport.POST(url='/file/v2/', body=attributes, type='multipart/form-data') | [
"def",
"create",
"(",
"self",
",",
"filename",
",",
"filedata",
")",
":",
"attributes",
"=",
"{",
"'filename'",
":",
"filename",
",",
"'source'",
":",
"filedata",
"}",
"return",
"self",
".",
"transport",
".",
"POST",
"(",
"url",
"=",
"'/file/v2/'",
",",
... | Create a file from raw data | [
"Create",
"a",
"file",
"from",
"raw",
"data"
] | 5ce956034a06c98b0ef18fcd940b36da0908ad6c | https://github.com/podio/podio-py/blob/5ce956034a06c98b0ef18fcd940b36da0908ad6c/pypodio2/areas.py#L522-L526 | train | 40,836 |
podio/podio-py | pypodio2/areas.py | View.get | def get(self, app_id, view_specifier):
"""
Retrieve the definition of a given view, provided the app_id and the view_id
:param app_id: the app id
:param view_specifier:
Can be one of the following:
1. The view ID
2. The view's name
3. "last" to look up the last view used
"""
return self.transport.GET(url='/view/app/{}/{}'.format(app_id, view_specifier)) | python | def get(self, app_id, view_specifier):
"""
Retrieve the definition of a given view, provided the app_id and the view_id
:param app_id: the app id
:param view_specifier:
Can be one of the following:
1. The view ID
2. The view's name
3. "last" to look up the last view used
"""
return self.transport.GET(url='/view/app/{}/{}'.format(app_id, view_specifier)) | [
"def",
"get",
"(",
"self",
",",
"app_id",
",",
"view_specifier",
")",
":",
"return",
"self",
".",
"transport",
".",
"GET",
"(",
"url",
"=",
"'/view/app/{}/{}'",
".",
"format",
"(",
"app_id",
",",
"view_specifier",
")",
")"
] | Retrieve the definition of a given view, provided the app_id and the view_id
:param app_id: the app id
:param view_specifier:
Can be one of the following:
1. The view ID
2. The view's name
3. "last" to look up the last view used | [
"Retrieve",
"the",
"definition",
"of",
"a",
"given",
"view",
"provided",
"the",
"app_id",
"and",
"the",
"view_id"
] | 5ce956034a06c98b0ef18fcd940b36da0908ad6c | https://github.com/podio/podio-py/blob/5ce956034a06c98b0ef18fcd940b36da0908ad6c/pypodio2/areas.py#L557-L568 | train | 40,837 |
podio/podio-py | pypodio2/areas.py | View.get_views | def get_views(self, app_id, include_standard_views=False):
"""
Get all of the views for the specified app
:param app_id: the app containing the views
:param include_standard_views: defaults to false. Set to true if you wish to include standard views.
"""
include_standard = "true" if include_standard_views is True else "false"
return self.transport.GET(url='/view/app/{}/?include_standard_views={}'.format(app_id, include_standard)) | python | def get_views(self, app_id, include_standard_views=False):
"""
Get all of the views for the specified app
:param app_id: the app containing the views
:param include_standard_views: defaults to false. Set to true if you wish to include standard views.
"""
include_standard = "true" if include_standard_views is True else "false"
return self.transport.GET(url='/view/app/{}/?include_standard_views={}'.format(app_id, include_standard)) | [
"def",
"get_views",
"(",
"self",
",",
"app_id",
",",
"include_standard_views",
"=",
"False",
")",
":",
"include_standard",
"=",
"\"true\"",
"if",
"include_standard_views",
"is",
"True",
"else",
"\"false\"",
"return",
"self",
".",
"transport",
".",
"GET",
"(",
... | Get all of the views for the specified app
:param app_id: the app containing the views
:param include_standard_views: defaults to false. Set to true if you wish to include standard views. | [
"Get",
"all",
"of",
"the",
"views",
"for",
"the",
"specified",
"app"
] | 5ce956034a06c98b0ef18fcd940b36da0908ad6c | https://github.com/podio/podio-py/blob/5ce956034a06c98b0ef18fcd940b36da0908ad6c/pypodio2/areas.py#L570-L578 | train | 40,838 |
podio/podio-py | pypodio2/areas.py | View.update_last_view | def update_last_view(self, app_id, attributes):
"""
Updates the last view for the active user
:param app_id: the app id
:param attributes: the body of the request in dictionary format
"""
if not isinstance(attributes, dict):
raise TypeError('Must be of type dict')
attribute_data = json.dumps(attributes)
return self.transport.PUT(url='/view/app/{}/last'.format(app_id),
body=attribute_data, type='application/json') | python | def update_last_view(self, app_id, attributes):
"""
Updates the last view for the active user
:param app_id: the app id
:param attributes: the body of the request in dictionary format
"""
if not isinstance(attributes, dict):
raise TypeError('Must be of type dict')
attribute_data = json.dumps(attributes)
return self.transport.PUT(url='/view/app/{}/last'.format(app_id),
body=attribute_data, type='application/json') | [
"def",
"update_last_view",
"(",
"self",
",",
"app_id",
",",
"attributes",
")",
":",
"if",
"not",
"isinstance",
"(",
"attributes",
",",
"dict",
")",
":",
"raise",
"TypeError",
"(",
"'Must be of type dict'",
")",
"attribute_data",
"=",
"json",
".",
"dumps",
"(... | Updates the last view for the active user
:param app_id: the app id
:param attributes: the body of the request in dictionary format | [
"Updates",
"the",
"last",
"view",
"for",
"the",
"active",
"user"
] | 5ce956034a06c98b0ef18fcd940b36da0908ad6c | https://github.com/podio/podio-py/blob/5ce956034a06c98b0ef18fcd940b36da0908ad6c/pypodio2/areas.py#L589-L600 | train | 40,839 |
podio/podio-py | pypodio2/areas.py | View.update_view | def update_view(self, view_id, attributes):
"""
Update an existing view using the details supplied via the attributes parameter
:param view_id: the view's id
:param attributes: a dictionary containing the modifications to be made to the view
:return:
"""
if not isinstance(attributes, dict):
raise TypeError('Must be of type dict')
attribute_data = json.dumps(attributes)
return self.transport.PUT(url='/view/{}'.format(view_id),
body=attribute_data, type='application/json') | python | def update_view(self, view_id, attributes):
"""
Update an existing view using the details supplied via the attributes parameter
:param view_id: the view's id
:param attributes: a dictionary containing the modifications to be made to the view
:return:
"""
if not isinstance(attributes, dict):
raise TypeError('Must be of type dict')
attribute_data = json.dumps(attributes)
return self.transport.PUT(url='/view/{}'.format(view_id),
body=attribute_data, type='application/json') | [
"def",
"update_view",
"(",
"self",
",",
"view_id",
",",
"attributes",
")",
":",
"if",
"not",
"isinstance",
"(",
"attributes",
",",
"dict",
")",
":",
"raise",
"TypeError",
"(",
"'Must be of type dict'",
")",
"attribute_data",
"=",
"json",
".",
"dumps",
"(",
... | Update an existing view using the details supplied via the attributes parameter
:param view_id: the view's id
:param attributes: a dictionary containing the modifications to be made to the view
:return: | [
"Update",
"an",
"existing",
"view",
"using",
"the",
"details",
"supplied",
"via",
"the",
"attributes",
"parameter"
] | 5ce956034a06c98b0ef18fcd940b36da0908ad6c | https://github.com/podio/podio-py/blob/5ce956034a06c98b0ef18fcd940b36da0908ad6c/pypodio2/areas.py#L602-L614 | train | 40,840 |
PythonicNinja/pydrill | pydrill/client/__init__.py | PyDrill.query | def query(self, sql, timeout=10):
"""
Submit a query and return results.
:param sql: string
:param timeout: int
:return: pydrill.client.ResultQuery
"""
if not sql:
raise QueryError('No query passed to drill.')
result = ResultQuery(*self.perform_request(**{
'method': 'POST',
'url': '/query.json',
'body': {
"queryType": "SQL",
"query": sql
},
'params': {
'request_timeout': timeout
}
}))
return result | python | def query(self, sql, timeout=10):
"""
Submit a query and return results.
:param sql: string
:param timeout: int
:return: pydrill.client.ResultQuery
"""
if not sql:
raise QueryError('No query passed to drill.')
result = ResultQuery(*self.perform_request(**{
'method': 'POST',
'url': '/query.json',
'body': {
"queryType": "SQL",
"query": sql
},
'params': {
'request_timeout': timeout
}
}))
return result | [
"def",
"query",
"(",
"self",
",",
"sql",
",",
"timeout",
"=",
"10",
")",
":",
"if",
"not",
"sql",
":",
"raise",
"QueryError",
"(",
"'No query passed to drill.'",
")",
"result",
"=",
"ResultQuery",
"(",
"*",
"self",
".",
"perform_request",
"(",
"*",
"*",
... | Submit a query and return results.
:param sql: string
:param timeout: int
:return: pydrill.client.ResultQuery | [
"Submit",
"a",
"query",
"and",
"return",
"results",
"."
] | 0713e78c84d44cd438018e4ba1588a8e242f78c4 | https://github.com/PythonicNinja/pydrill/blob/0713e78c84d44cd438018e4ba1588a8e242f78c4/pydrill/client/__init__.py#L43-L66 | train | 40,841 |
PythonicNinja/pydrill | pydrill/client/__init__.py | PyDrill.storage_detail | def storage_detail(self, name, timeout=10):
"""
Get the definition of the named storage plugin.
:param name: The assigned name in the storage plugin definition.
:param timeout: int
:return: pydrill.client.Result
"""
result = Result(*self.perform_request(**{
'method': 'GET',
'url': '/storage/{0}.json'.format(name),
'params': {
'request_timeout': timeout
}
}))
return result | python | def storage_detail(self, name, timeout=10):
"""
Get the definition of the named storage plugin.
:param name: The assigned name in the storage plugin definition.
:param timeout: int
:return: pydrill.client.Result
"""
result = Result(*self.perform_request(**{
'method': 'GET',
'url': '/storage/{0}.json'.format(name),
'params': {
'request_timeout': timeout
}
}))
return result | [
"def",
"storage_detail",
"(",
"self",
",",
"name",
",",
"timeout",
"=",
"10",
")",
":",
"result",
"=",
"Result",
"(",
"*",
"self",
".",
"perform_request",
"(",
"*",
"*",
"{",
"'method'",
":",
"'GET'",
",",
"'url'",
":",
"'/storage/{0}.json'",
".",
"for... | Get the definition of the named storage plugin.
:param name: The assigned name in the storage plugin definition.
:param timeout: int
:return: pydrill.client.Result | [
"Get",
"the",
"definition",
"of",
"the",
"named",
"storage",
"plugin",
"."
] | 0713e78c84d44cd438018e4ba1588a8e242f78c4 | https://github.com/PythonicNinja/pydrill/blob/0713e78c84d44cd438018e4ba1588a8e242f78c4/pydrill/client/__init__.py#L157-L172 | train | 40,842 |
PythonicNinja/pydrill | pydrill/client/__init__.py | PyDrill.storage_enable | def storage_enable(self, name, value=True, timeout=10):
"""
Enable or disable the named storage plugin.
:param name: The assigned name in the storage plugin definition.
:param value: Either True (to enable) or False (to disable).
:param timeout: int
:return: pydrill.client.Result
"""
value = 'true' if value else 'false'
result = Result(*self.perform_request(**{
'method': 'GET',
'url': '/storage/{0}/enable/{1}'.format(name, value),
'params': {
'request_timeout': timeout
}
}))
return result | python | def storage_enable(self, name, value=True, timeout=10):
"""
Enable or disable the named storage plugin.
:param name: The assigned name in the storage plugin definition.
:param value: Either True (to enable) or False (to disable).
:param timeout: int
:return: pydrill.client.Result
"""
value = 'true' if value else 'false'
result = Result(*self.perform_request(**{
'method': 'GET',
'url': '/storage/{0}/enable/{1}'.format(name, value),
'params': {
'request_timeout': timeout
}
}))
return result | [
"def",
"storage_enable",
"(",
"self",
",",
"name",
",",
"value",
"=",
"True",
",",
"timeout",
"=",
"10",
")",
":",
"value",
"=",
"'true'",
"if",
"value",
"else",
"'false'",
"result",
"=",
"Result",
"(",
"*",
"self",
".",
"perform_request",
"(",
"*",
... | Enable or disable the named storage plugin.
:param name: The assigned name in the storage plugin definition.
:param value: Either True (to enable) or False (to disable).
:param timeout: int
:return: pydrill.client.Result | [
"Enable",
"or",
"disable",
"the",
"named",
"storage",
"plugin",
"."
] | 0713e78c84d44cd438018e4ba1588a8e242f78c4 | https://github.com/PythonicNinja/pydrill/blob/0713e78c84d44cd438018e4ba1588a8e242f78c4/pydrill/client/__init__.py#L174-L191 | train | 40,843 |
PythonicNinja/pydrill | pydrill/client/__init__.py | PyDrill.storage_update | def storage_update(self, name, config, timeout=10):
"""
Create or update a storage plugin configuration.
:param name: The name of the storage plugin configuration to create or update.
:param config: Overwrites the existing configuration if there is any, and therefore, must include all
required attributes and definitions.
:param timeout: int
:return: pydrill.client.Result
"""
result = Result(*self.perform_request(**{
'method': 'POST',
'url': '/storage/{0}.json'.format(name),
'body': config,
'params': {
'request_timeout': timeout
}
}))
return result | python | def storage_update(self, name, config, timeout=10):
"""
Create or update a storage plugin configuration.
:param name: The name of the storage plugin configuration to create or update.
:param config: Overwrites the existing configuration if there is any, and therefore, must include all
required attributes and definitions.
:param timeout: int
:return: pydrill.client.Result
"""
result = Result(*self.perform_request(**{
'method': 'POST',
'url': '/storage/{0}.json'.format(name),
'body': config,
'params': {
'request_timeout': timeout
}
}))
return result | [
"def",
"storage_update",
"(",
"self",
",",
"name",
",",
"config",
",",
"timeout",
"=",
"10",
")",
":",
"result",
"=",
"Result",
"(",
"*",
"self",
".",
"perform_request",
"(",
"*",
"*",
"{",
"'method'",
":",
"'POST'",
",",
"'url'",
":",
"'/storage/{0}.j... | Create or update a storage plugin configuration.
:param name: The name of the storage plugin configuration to create or update.
:param config: Overwrites the existing configuration if there is any, and therefore, must include all
required attributes and definitions.
:param timeout: int
:return: pydrill.client.Result | [
"Create",
"or",
"update",
"a",
"storage",
"plugin",
"configuration",
"."
] | 0713e78c84d44cd438018e4ba1588a8e242f78c4 | https://github.com/PythonicNinja/pydrill/blob/0713e78c84d44cd438018e4ba1588a8e242f78c4/pydrill/client/__init__.py#L193-L211 | train | 40,844 |
PythonicNinja/pydrill | pydrill/client/__init__.py | PyDrill.storage_delete | def storage_delete(self, name, timeout=10):
"""
Delete a storage plugin configuration.
:param name: The name of the storage plugin configuration to delete.
:param timeout: int
:return: pydrill.client.Result
"""
result = Result(*self.perform_request(**{
'method': 'DELETE',
'url': '/storage/{0}.json'.format(name),
'params': {
'request_timeout': timeout
}
}))
return result | python | def storage_delete(self, name, timeout=10):
"""
Delete a storage plugin configuration.
:param name: The name of the storage plugin configuration to delete.
:param timeout: int
:return: pydrill.client.Result
"""
result = Result(*self.perform_request(**{
'method': 'DELETE',
'url': '/storage/{0}.json'.format(name),
'params': {
'request_timeout': timeout
}
}))
return result | [
"def",
"storage_delete",
"(",
"self",
",",
"name",
",",
"timeout",
"=",
"10",
")",
":",
"result",
"=",
"Result",
"(",
"*",
"self",
".",
"perform_request",
"(",
"*",
"*",
"{",
"'method'",
":",
"'DELETE'",
",",
"'url'",
":",
"'/storage/{0}.json'",
".",
"... | Delete a storage plugin configuration.
:param name: The name of the storage plugin configuration to delete.
:param timeout: int
:return: pydrill.client.Result | [
"Delete",
"a",
"storage",
"plugin",
"configuration",
"."
] | 0713e78c84d44cd438018e4ba1588a8e242f78c4 | https://github.com/PythonicNinja/pydrill/blob/0713e78c84d44cd438018e4ba1588a8e242f78c4/pydrill/client/__init__.py#L213-L228 | train | 40,845 |
PythonicNinja/pydrill | pydrill/client/__init__.py | PyDrill.profile | def profile(self, query_id, timeout=10):
"""
Get the profile of the query that has the given queryid.
:param query_id: The UUID of the query in standard UUID format that Drill assigns to each query.
:param timeout: int
:return: pydrill.client.Result
"""
result = Result(*self.perform_request(**{
'method': 'GET',
'url': '/profiles/{0}.json'.format(query_id),
'params': {
'request_timeout': timeout
}
}))
return result | python | def profile(self, query_id, timeout=10):
"""
Get the profile of the query that has the given queryid.
:param query_id: The UUID of the query in standard UUID format that Drill assigns to each query.
:param timeout: int
:return: pydrill.client.Result
"""
result = Result(*self.perform_request(**{
'method': 'GET',
'url': '/profiles/{0}.json'.format(query_id),
'params': {
'request_timeout': timeout
}
}))
return result | [
"def",
"profile",
"(",
"self",
",",
"query_id",
",",
"timeout",
"=",
"10",
")",
":",
"result",
"=",
"Result",
"(",
"*",
"self",
".",
"perform_request",
"(",
"*",
"*",
"{",
"'method'",
":",
"'GET'",
",",
"'url'",
":",
"'/profiles/{0}.json'",
".",
"forma... | Get the profile of the query that has the given queryid.
:param query_id: The UUID of the query in standard UUID format that Drill assigns to each query.
:param timeout: int
:return: pydrill.client.Result | [
"Get",
"the",
"profile",
"of",
"the",
"query",
"that",
"has",
"the",
"given",
"queryid",
"."
] | 0713e78c84d44cd438018e4ba1588a8e242f78c4 | https://github.com/PythonicNinja/pydrill/blob/0713e78c84d44cd438018e4ba1588a8e242f78c4/pydrill/client/__init__.py#L246-L261 | train | 40,846 |
PythonicNinja/pydrill | pydrill/client/__init__.py | PyDrill.profile_cancel | def profile_cancel(self, query_id, timeout=10):
"""
Cancel the query that has the given queryid.
:param query_id: The UUID of the query in standard UUID format that Drill assigns to each query.
:param timeout: int
:return: pydrill.client.Result
"""
result = Result(*self.perform_request(**{
'method': 'GET',
'url': '/profiles/cancel/{0}'.format(query_id),
'params': {
'request_timeout': timeout
}
}))
return result | python | def profile_cancel(self, query_id, timeout=10):
"""
Cancel the query that has the given queryid.
:param query_id: The UUID of the query in standard UUID format that Drill assigns to each query.
:param timeout: int
:return: pydrill.client.Result
"""
result = Result(*self.perform_request(**{
'method': 'GET',
'url': '/profiles/cancel/{0}'.format(query_id),
'params': {
'request_timeout': timeout
}
}))
return result | [
"def",
"profile_cancel",
"(",
"self",
",",
"query_id",
",",
"timeout",
"=",
"10",
")",
":",
"result",
"=",
"Result",
"(",
"*",
"self",
".",
"perform_request",
"(",
"*",
"*",
"{",
"'method'",
":",
"'GET'",
",",
"'url'",
":",
"'/profiles/cancel/{0}'",
".",... | Cancel the query that has the given queryid.
:param query_id: The UUID of the query in standard UUID format that Drill assigns to each query.
:param timeout: int
:return: pydrill.client.Result | [
"Cancel",
"the",
"query",
"that",
"has",
"the",
"given",
"queryid",
"."
] | 0713e78c84d44cd438018e4ba1588a8e242f78c4 | https://github.com/PythonicNinja/pydrill/blob/0713e78c84d44cd438018e4ba1588a8e242f78c4/pydrill/client/__init__.py#L263-L278 | train | 40,847 |
PythonicNinja/pydrill | pydrill/transport.py | Transport.perform_request | def perform_request(self, method, url, params=None, body=None):
"""
Perform the actual request.
Retrieve a connection.
Pass all the information to it's perform_request method and return the data.
:arg method: HTTP method to use
:arg url: absolute url (without host) to target
:arg params: dictionary of query parameters, will be handed over to the
underlying :class:`~pydrill.Connection` class for serialization
:arg body: body of the request, will be serializes using serializer and
passed to the connection
"""
if body is not None:
body = self.serializer.dumps(body)
# some clients or environments don't support sending GET with body
if method in ('HEAD', 'GET') and self.send_get_body_as != 'GET':
# send it as post instead
if self.send_get_body_as == 'POST':
method = 'POST'
# or as source parameter
elif self.send_get_body_as == 'source':
if params is None:
params = {}
params['source'] = body
body = None
if body is not None:
try:
body = body.encode('utf-8')
except (UnicodeDecodeError, AttributeError):
# bytes/str - no need to re-encode
pass
ignore = ()
timeout = None
if params:
timeout = params.pop('request_timeout', None)
ignore = params.pop('ignore', ())
if isinstance(ignore, int):
ignore = (ignore,)
for attempt in range(self.max_retries + 1):
connection = self.get_connection()
try:
response, data, duration = connection.perform_request(method, url, params, body, ignore=ignore,
timeout=timeout)
except TransportError as e:
retry = False
if isinstance(e, ConnectionTimeout):
retry = self.retry_on_timeout
elif isinstance(e, ConnectionError):
retry = True
elif e.status_code in self.retry_on_status:
retry = True
if retry:
if attempt == self.max_retries:
raise
else:
raise
else:
if data:
data = self.deserializer.loads(data, mimetype=response.headers.get('Content-Type'))
else:
data = {}
return response, data, duration | python | def perform_request(self, method, url, params=None, body=None):
"""
Perform the actual request.
Retrieve a connection.
Pass all the information to it's perform_request method and return the data.
:arg method: HTTP method to use
:arg url: absolute url (without host) to target
:arg params: dictionary of query parameters, will be handed over to the
underlying :class:`~pydrill.Connection` class for serialization
:arg body: body of the request, will be serializes using serializer and
passed to the connection
"""
if body is not None:
body = self.serializer.dumps(body)
# some clients or environments don't support sending GET with body
if method in ('HEAD', 'GET') and self.send_get_body_as != 'GET':
# send it as post instead
if self.send_get_body_as == 'POST':
method = 'POST'
# or as source parameter
elif self.send_get_body_as == 'source':
if params is None:
params = {}
params['source'] = body
body = None
if body is not None:
try:
body = body.encode('utf-8')
except (UnicodeDecodeError, AttributeError):
# bytes/str - no need to re-encode
pass
ignore = ()
timeout = None
if params:
timeout = params.pop('request_timeout', None)
ignore = params.pop('ignore', ())
if isinstance(ignore, int):
ignore = (ignore,)
for attempt in range(self.max_retries + 1):
connection = self.get_connection()
try:
response, data, duration = connection.perform_request(method, url, params, body, ignore=ignore,
timeout=timeout)
except TransportError as e:
retry = False
if isinstance(e, ConnectionTimeout):
retry = self.retry_on_timeout
elif isinstance(e, ConnectionError):
retry = True
elif e.status_code in self.retry_on_status:
retry = True
if retry:
if attempt == self.max_retries:
raise
else:
raise
else:
if data:
data = self.deserializer.loads(data, mimetype=response.headers.get('Content-Type'))
else:
data = {}
return response, data, duration | [
"def",
"perform_request",
"(",
"self",
",",
"method",
",",
"url",
",",
"params",
"=",
"None",
",",
"body",
"=",
"None",
")",
":",
"if",
"body",
"is",
"not",
"None",
":",
"body",
"=",
"self",
".",
"serializer",
".",
"dumps",
"(",
"body",
")",
"# som... | Perform the actual request.
Retrieve a connection.
Pass all the information to it's perform_request method and return the data.
:arg method: HTTP method to use
:arg url: absolute url (without host) to target
:arg params: dictionary of query parameters, will be handed over to the
underlying :class:`~pydrill.Connection` class for serialization
:arg body: body of the request, will be serializes using serializer and
passed to the connection | [
"Perform",
"the",
"actual",
"request",
".",
"Retrieve",
"a",
"connection",
".",
"Pass",
"all",
"the",
"information",
"to",
"it",
"s",
"perform_request",
"method",
"and",
"return",
"the",
"data",
"."
] | 0713e78c84d44cd438018e4ba1588a8e242f78c4 | https://github.com/PythonicNinja/pydrill/blob/0713e78c84d44cd438018e4ba1588a8e242f78c4/pydrill/transport.py#L30-L99 | train | 40,848 |
inveniosoftware/invenio-accounts | invenio_accounts/views/settings.py | check_security_settings | def check_security_settings():
"""Warn if session cookie is not secure in production."""
in_production = not (current_app.debug or current_app.testing)
secure = current_app.config.get('SESSION_COOKIE_SECURE')
if in_production and not secure:
current_app.logger.warning(
"SESSION_COOKIE_SECURE setting must be set to True to prevent the "
"session cookie from being leaked over an insecure channel."
) | python | def check_security_settings():
"""Warn if session cookie is not secure in production."""
in_production = not (current_app.debug or current_app.testing)
secure = current_app.config.get('SESSION_COOKIE_SECURE')
if in_production and not secure:
current_app.logger.warning(
"SESSION_COOKIE_SECURE setting must be set to True to prevent the "
"session cookie from being leaked over an insecure channel."
) | [
"def",
"check_security_settings",
"(",
")",
":",
"in_production",
"=",
"not",
"(",
"current_app",
".",
"debug",
"or",
"current_app",
".",
"testing",
")",
"secure",
"=",
"current_app",
".",
"config",
".",
"get",
"(",
"'SESSION_COOKIE_SECURE'",
")",
"if",
"in_pr... | Warn if session cookie is not secure in production. | [
"Warn",
"if",
"session",
"cookie",
"is",
"not",
"secure",
"in",
"production",
"."
] | b0d2f0739b00dbefea22ca15d7d374a1b4a63aec | https://github.com/inveniosoftware/invenio-accounts/blob/b0d2f0739b00dbefea22ca15d7d374a1b4a63aec/invenio_accounts/views/settings.py#L82-L90 | train | 40,849 |
inveniosoftware/invenio-accounts | invenio_accounts/context_processors/jwt.py | jwt_proccessor | def jwt_proccessor():
"""Context processor for jwt."""
def jwt():
"""Context processor function to generate jwt."""
token = current_accounts.jwt_creation_factory()
return Markup(
render_template(
current_app.config['ACCOUNTS_JWT_DOM_TOKEN_TEMPLATE'],
token=token
)
)
def jwt_token():
"""Context processor function to generate jwt."""
return current_accounts.jwt_creation_factory()
return {
'jwt': jwt,
'jwt_token': jwt_token,
} | python | def jwt_proccessor():
"""Context processor for jwt."""
def jwt():
"""Context processor function to generate jwt."""
token = current_accounts.jwt_creation_factory()
return Markup(
render_template(
current_app.config['ACCOUNTS_JWT_DOM_TOKEN_TEMPLATE'],
token=token
)
)
def jwt_token():
"""Context processor function to generate jwt."""
return current_accounts.jwt_creation_factory()
return {
'jwt': jwt,
'jwt_token': jwt_token,
} | [
"def",
"jwt_proccessor",
"(",
")",
":",
"def",
"jwt",
"(",
")",
":",
"\"\"\"Context processor function to generate jwt.\"\"\"",
"token",
"=",
"current_accounts",
".",
"jwt_creation_factory",
"(",
")",
"return",
"Markup",
"(",
"render_template",
"(",
"current_app",
"."... | Context processor for jwt. | [
"Context",
"processor",
"for",
"jwt",
"."
] | b0d2f0739b00dbefea22ca15d7d374a1b4a63aec | https://github.com/inveniosoftware/invenio-accounts/blob/b0d2f0739b00dbefea22ca15d7d374a1b4a63aec/invenio_accounts/context_processors/jwt.py#L17-L36 | train | 40,850 |
inveniosoftware/invenio-accounts | invenio_accounts/hash.py | _to_binary | def _to_binary(val):
"""Convert to binary."""
if isinstance(val, text_type):
return val.encode('utf-8')
assert isinstance(val, binary_type)
return val | python | def _to_binary(val):
"""Convert to binary."""
if isinstance(val, text_type):
return val.encode('utf-8')
assert isinstance(val, binary_type)
return val | [
"def",
"_to_binary",
"(",
"val",
")",
":",
"if",
"isinstance",
"(",
"val",
",",
"text_type",
")",
":",
"return",
"val",
".",
"encode",
"(",
"'utf-8'",
")",
"assert",
"isinstance",
"(",
"val",
",",
"binary_type",
")",
"return",
"val"
] | Convert to binary. | [
"Convert",
"to",
"binary",
"."
] | b0d2f0739b00dbefea22ca15d7d374a1b4a63aec | https://github.com/inveniosoftware/invenio-accounts/blob/b0d2f0739b00dbefea22ca15d7d374a1b4a63aec/invenio_accounts/hash.py#L23-L28 | train | 40,851 |
inveniosoftware/invenio-accounts | invenio_accounts/hash.py | _to_string | def _to_string(val):
"""Convert to text."""
if isinstance(val, binary_type):
return val.decode('utf-8')
assert isinstance(val, text_type)
return val | python | def _to_string(val):
"""Convert to text."""
if isinstance(val, binary_type):
return val.decode('utf-8')
assert isinstance(val, text_type)
return val | [
"def",
"_to_string",
"(",
"val",
")",
":",
"if",
"isinstance",
"(",
"val",
",",
"binary_type",
")",
":",
"return",
"val",
".",
"decode",
"(",
"'utf-8'",
")",
"assert",
"isinstance",
"(",
"val",
",",
"text_type",
")",
"return",
"val"
] | Convert to text. | [
"Convert",
"to",
"text",
"."
] | b0d2f0739b00dbefea22ca15d7d374a1b4a63aec | https://github.com/inveniosoftware/invenio-accounts/blob/b0d2f0739b00dbefea22ca15d7d374a1b4a63aec/invenio_accounts/hash.py#L31-L36 | train | 40,852 |
inveniosoftware/invenio-accounts | invenio_accounts/hash.py | _mysql_aes_key | def _mysql_aes_key(key):
"""Format key."""
final_key = bytearray(16)
for i, c in enumerate(key):
final_key[i % 16] ^= key[i] if PY3 else ord(key[i])
return bytes(final_key) | python | def _mysql_aes_key(key):
"""Format key."""
final_key = bytearray(16)
for i, c in enumerate(key):
final_key[i % 16] ^= key[i] if PY3 else ord(key[i])
return bytes(final_key) | [
"def",
"_mysql_aes_key",
"(",
"key",
")",
":",
"final_key",
"=",
"bytearray",
"(",
"16",
")",
"for",
"i",
",",
"c",
"in",
"enumerate",
"(",
"key",
")",
":",
"final_key",
"[",
"i",
"%",
"16",
"]",
"^=",
"key",
"[",
"i",
"]",
"if",
"PY3",
"else",
... | Format key. | [
"Format",
"key",
"."
] | b0d2f0739b00dbefea22ca15d7d374a1b4a63aec | https://github.com/inveniosoftware/invenio-accounts/blob/b0d2f0739b00dbefea22ca15d7d374a1b4a63aec/invenio_accounts/hash.py#L39-L44 | train | 40,853 |
inveniosoftware/invenio-accounts | invenio_accounts/hash.py | _mysql_aes_unpad | def _mysql_aes_unpad(val):
"""Reverse padding."""
val = _to_string(val)
pad_value = ord(val[-1])
return val[:-pad_value] | python | def _mysql_aes_unpad(val):
"""Reverse padding."""
val = _to_string(val)
pad_value = ord(val[-1])
return val[:-pad_value] | [
"def",
"_mysql_aes_unpad",
"(",
"val",
")",
":",
"val",
"=",
"_to_string",
"(",
"val",
")",
"pad_value",
"=",
"ord",
"(",
"val",
"[",
"-",
"1",
"]",
")",
"return",
"val",
"[",
":",
"-",
"pad_value",
"]"
] | Reverse padding. | [
"Reverse",
"padding",
"."
] | b0d2f0739b00dbefea22ca15d7d374a1b4a63aec | https://github.com/inveniosoftware/invenio-accounts/blob/b0d2f0739b00dbefea22ca15d7d374a1b4a63aec/invenio_accounts/hash.py#L54-L58 | train | 40,854 |
inveniosoftware/invenio-accounts | invenio_accounts/hash.py | mysql_aes_encrypt | def mysql_aes_encrypt(val, key):
"""Mysql AES encrypt value with secret key.
:param val: Plain text value.
:param key: The AES key.
:returns: The encrypted AES value.
"""
assert isinstance(val, binary_type) or isinstance(val, text_type)
assert isinstance(key, binary_type) or isinstance(key, text_type)
k = _mysql_aes_key(_to_binary(key))
v = _mysql_aes_pad(_to_binary(val))
e = _mysql_aes_engine(k).encryptor()
return e.update(v) + e.finalize() | python | def mysql_aes_encrypt(val, key):
"""Mysql AES encrypt value with secret key.
:param val: Plain text value.
:param key: The AES key.
:returns: The encrypted AES value.
"""
assert isinstance(val, binary_type) or isinstance(val, text_type)
assert isinstance(key, binary_type) or isinstance(key, text_type)
k = _mysql_aes_key(_to_binary(key))
v = _mysql_aes_pad(_to_binary(val))
e = _mysql_aes_engine(k).encryptor()
return e.update(v) + e.finalize() | [
"def",
"mysql_aes_encrypt",
"(",
"val",
",",
"key",
")",
":",
"assert",
"isinstance",
"(",
"val",
",",
"binary_type",
")",
"or",
"isinstance",
"(",
"val",
",",
"text_type",
")",
"assert",
"isinstance",
"(",
"key",
",",
"binary_type",
")",
"or",
"isinstance... | Mysql AES encrypt value with secret key.
:param val: Plain text value.
:param key: The AES key.
:returns: The encrypted AES value. | [
"Mysql",
"AES",
"encrypt",
"value",
"with",
"secret",
"key",
"."
] | b0d2f0739b00dbefea22ca15d7d374a1b4a63aec | https://github.com/inveniosoftware/invenio-accounts/blob/b0d2f0739b00dbefea22ca15d7d374a1b4a63aec/invenio_accounts/hash.py#L66-L79 | train | 40,855 |
inveniosoftware/invenio-accounts | invenio_accounts/hash.py | mysql_aes_decrypt | def mysql_aes_decrypt(encrypted_val, key):
"""Mysql AES decrypt value with secret key.
:param encrypted_val: Encrypted value.
:param key: The AES key.
:returns: The AES value decrypted.
"""
assert isinstance(encrypted_val, binary_type) \
or isinstance(encrypted_val, text_type)
assert isinstance(key, binary_type) or isinstance(key, text_type)
k = _mysql_aes_key(_to_binary(key))
d = _mysql_aes_engine(_to_binary(k)).decryptor()
return _mysql_aes_unpad(d.update(_to_binary(encrypted_val)) + d.finalize()) | python | def mysql_aes_decrypt(encrypted_val, key):
"""Mysql AES decrypt value with secret key.
:param encrypted_val: Encrypted value.
:param key: The AES key.
:returns: The AES value decrypted.
"""
assert isinstance(encrypted_val, binary_type) \
or isinstance(encrypted_val, text_type)
assert isinstance(key, binary_type) or isinstance(key, text_type)
k = _mysql_aes_key(_to_binary(key))
d = _mysql_aes_engine(_to_binary(k)).decryptor()
return _mysql_aes_unpad(d.update(_to_binary(encrypted_val)) + d.finalize()) | [
"def",
"mysql_aes_decrypt",
"(",
"encrypted_val",
",",
"key",
")",
":",
"assert",
"isinstance",
"(",
"encrypted_val",
",",
"binary_type",
")",
"or",
"isinstance",
"(",
"encrypted_val",
",",
"text_type",
")",
"assert",
"isinstance",
"(",
"key",
",",
"binary_type"... | Mysql AES decrypt value with secret key.
:param encrypted_val: Encrypted value.
:param key: The AES key.
:returns: The AES value decrypted. | [
"Mysql",
"AES",
"decrypt",
"value",
"with",
"secret",
"key",
"."
] | b0d2f0739b00dbefea22ca15d7d374a1b4a63aec | https://github.com/inveniosoftware/invenio-accounts/blob/b0d2f0739b00dbefea22ca15d7d374a1b4a63aec/invenio_accounts/hash.py#L82-L94 | train | 40,856 |
inveniosoftware/invenio-accounts | invenio_accounts/hash.py | InvenioAesEncryptedEmail.from_string | def from_string(cls, hash, **context):
"""Parse instance from configuration string in Modular Crypt Format."""
salt, checksum = parse_mc2(hash, cls.ident, handler=cls)
return cls(salt=salt, checksum=checksum) | python | def from_string(cls, hash, **context):
"""Parse instance from configuration string in Modular Crypt Format."""
salt, checksum = parse_mc2(hash, cls.ident, handler=cls)
return cls(salt=salt, checksum=checksum) | [
"def",
"from_string",
"(",
"cls",
",",
"hash",
",",
"*",
"*",
"context",
")",
":",
"salt",
",",
"checksum",
"=",
"parse_mc2",
"(",
"hash",
",",
"cls",
".",
"ident",
",",
"handler",
"=",
"cls",
")",
"return",
"cls",
"(",
"salt",
"=",
"salt",
",",
... | Parse instance from configuration string in Modular Crypt Format. | [
"Parse",
"instance",
"from",
"configuration",
"string",
"in",
"Modular",
"Crypt",
"Format",
"."
] | b0d2f0739b00dbefea22ca15d7d374a1b4a63aec | https://github.com/inveniosoftware/invenio-accounts/blob/b0d2f0739b00dbefea22ca15d7d374a1b4a63aec/invenio_accounts/hash.py#L116-L120 | train | 40,857 |
inveniosoftware/invenio-accounts | invenio_accounts/hash.py | InvenioAesEncryptedEmail._calc_checksum | def _calc_checksum(self, secret):
"""Calculate string.
:param secret: The secret key.
:returns: The checksum.
"""
return str_to_uascii(
hashlib.sha256(mysql_aes_encrypt(self.salt, secret)).hexdigest()
) | python | def _calc_checksum(self, secret):
"""Calculate string.
:param secret: The secret key.
:returns: The checksum.
"""
return str_to_uascii(
hashlib.sha256(mysql_aes_encrypt(self.salt, secret)).hexdigest()
) | [
"def",
"_calc_checksum",
"(",
"self",
",",
"secret",
")",
":",
"return",
"str_to_uascii",
"(",
"hashlib",
".",
"sha256",
"(",
"mysql_aes_encrypt",
"(",
"self",
".",
"salt",
",",
"secret",
")",
")",
".",
"hexdigest",
"(",
")",
")"
] | Calculate string.
:param secret: The secret key.
:returns: The checksum. | [
"Calculate",
"string",
"."
] | b0d2f0739b00dbefea22ca15d7d374a1b4a63aec | https://github.com/inveniosoftware/invenio-accounts/blob/b0d2f0739b00dbefea22ca15d7d374a1b4a63aec/invenio_accounts/hash.py#L126-L134 | train | 40,858 |
inveniosoftware/invenio-accounts | invenio_accounts/sessions.py | _ip2country | def _ip2country(ip):
"""Get user country."""
if ip:
match = geolite2.reader().get(ip)
return match.get('country', {}).get('iso_code') if match else None | python | def _ip2country(ip):
"""Get user country."""
if ip:
match = geolite2.reader().get(ip)
return match.get('country', {}).get('iso_code') if match else None | [
"def",
"_ip2country",
"(",
"ip",
")",
":",
"if",
"ip",
":",
"match",
"=",
"geolite2",
".",
"reader",
"(",
")",
".",
"get",
"(",
"ip",
")",
"return",
"match",
".",
"get",
"(",
"'country'",
",",
"{",
"}",
")",
".",
"get",
"(",
"'iso_code'",
")",
... | Get user country. | [
"Get",
"user",
"country",
"."
] | b0d2f0739b00dbefea22ca15d7d374a1b4a63aec | https://github.com/inveniosoftware/invenio-accounts/blob/b0d2f0739b00dbefea22ca15d7d374a1b4a63aec/invenio_accounts/sessions.py#L31-L35 | train | 40,859 |
inveniosoftware/invenio-accounts | invenio_accounts/sessions.py | _extract_info_from_useragent | def _extract_info_from_useragent(user_agent):
"""Extract extra informations from user."""
parsed_string = user_agent_parser.Parse(user_agent)
return {
'os': parsed_string.get('os', {}).get('family'),
'browser': parsed_string.get('user_agent', {}).get('family'),
'browser_version': parsed_string.get('user_agent', {}).get('major'),
'device': parsed_string.get('device', {}).get('family'),
} | python | def _extract_info_from_useragent(user_agent):
"""Extract extra informations from user."""
parsed_string = user_agent_parser.Parse(user_agent)
return {
'os': parsed_string.get('os', {}).get('family'),
'browser': parsed_string.get('user_agent', {}).get('family'),
'browser_version': parsed_string.get('user_agent', {}).get('major'),
'device': parsed_string.get('device', {}).get('family'),
} | [
"def",
"_extract_info_from_useragent",
"(",
"user_agent",
")",
":",
"parsed_string",
"=",
"user_agent_parser",
".",
"Parse",
"(",
"user_agent",
")",
"return",
"{",
"'os'",
":",
"parsed_string",
".",
"get",
"(",
"'os'",
",",
"{",
"}",
")",
".",
"get",
"(",
... | Extract extra informations from user. | [
"Extract",
"extra",
"informations",
"from",
"user",
"."
] | b0d2f0739b00dbefea22ca15d7d374a1b4a63aec | https://github.com/inveniosoftware/invenio-accounts/blob/b0d2f0739b00dbefea22ca15d7d374a1b4a63aec/invenio_accounts/sessions.py#L38-L46 | train | 40,860 |
inveniosoftware/invenio-accounts | invenio_accounts/sessions.py | add_session | def add_session(session=None):
r"""Add a session to the SessionActivity table.
:param session: Flask Session object to add. If None, ``session``
is used. The object is expected to have a dictionary entry named
``"user_id"`` and a field ``sid_s``
"""
user_id, sid_s = session['user_id'], session.sid_s
with db.session.begin_nested():
session_activity = SessionActivity(
user_id=user_id,
sid_s=sid_s,
ip=request.remote_addr,
country=_ip2country(request.remote_addr),
**_extract_info_from_useragent(
request.headers.get('User-Agent', '')
)
)
db.session.merge(session_activity) | python | def add_session(session=None):
r"""Add a session to the SessionActivity table.
:param session: Flask Session object to add. If None, ``session``
is used. The object is expected to have a dictionary entry named
``"user_id"`` and a field ``sid_s``
"""
user_id, sid_s = session['user_id'], session.sid_s
with db.session.begin_nested():
session_activity = SessionActivity(
user_id=user_id,
sid_s=sid_s,
ip=request.remote_addr,
country=_ip2country(request.remote_addr),
**_extract_info_from_useragent(
request.headers.get('User-Agent', '')
)
)
db.session.merge(session_activity) | [
"def",
"add_session",
"(",
"session",
"=",
"None",
")",
":",
"user_id",
",",
"sid_s",
"=",
"session",
"[",
"'user_id'",
"]",
",",
"session",
".",
"sid_s",
"with",
"db",
".",
"session",
".",
"begin_nested",
"(",
")",
":",
"session_activity",
"=",
"Session... | r"""Add a session to the SessionActivity table.
:param session: Flask Session object to add. If None, ``session``
is used. The object is expected to have a dictionary entry named
``"user_id"`` and a field ``sid_s`` | [
"r",
"Add",
"a",
"session",
"to",
"the",
"SessionActivity",
"table",
"."
] | b0d2f0739b00dbefea22ca15d7d374a1b4a63aec | https://github.com/inveniosoftware/invenio-accounts/blob/b0d2f0739b00dbefea22ca15d7d374a1b4a63aec/invenio_accounts/sessions.py#L49-L67 | train | 40,861 |
inveniosoftware/invenio-accounts | invenio_accounts/sessions.py | login_listener | def login_listener(app, user):
"""Connect to the user_logged_in signal for table population.
:param app: The Flask application.
:param user: The :class:`invenio_accounts.models.User` instance.
"""
@after_this_request
def add_user_session(response):
"""Regenerate current session and add to the SessionActivity table.
.. note:: `flask.session.regenerate()` actually calls Flask-KVSession's
`flask_kvsession.KVSession.regenerate`.
"""
# Regenerate the session to avoid session fixation vulnerabilities.
session.regenerate()
# Save the session first so that the sid_s gets generated.
app.session_interface.save_session(app, session, response)
add_session(session)
current_accounts.datastore.commit()
return response | python | def login_listener(app, user):
"""Connect to the user_logged_in signal for table population.
:param app: The Flask application.
:param user: The :class:`invenio_accounts.models.User` instance.
"""
@after_this_request
def add_user_session(response):
"""Regenerate current session and add to the SessionActivity table.
.. note:: `flask.session.regenerate()` actually calls Flask-KVSession's
`flask_kvsession.KVSession.regenerate`.
"""
# Regenerate the session to avoid session fixation vulnerabilities.
session.regenerate()
# Save the session first so that the sid_s gets generated.
app.session_interface.save_session(app, session, response)
add_session(session)
current_accounts.datastore.commit()
return response | [
"def",
"login_listener",
"(",
"app",
",",
"user",
")",
":",
"@",
"after_this_request",
"def",
"add_user_session",
"(",
"response",
")",
":",
"\"\"\"Regenerate current session and add to the SessionActivity table.\n\n .. note:: `flask.session.regenerate()` actually calls Flask-... | Connect to the user_logged_in signal for table population.
:param app: The Flask application.
:param user: The :class:`invenio_accounts.models.User` instance. | [
"Connect",
"to",
"the",
"user_logged_in",
"signal",
"for",
"table",
"population",
"."
] | b0d2f0739b00dbefea22ca15d7d374a1b4a63aec | https://github.com/inveniosoftware/invenio-accounts/blob/b0d2f0739b00dbefea22ca15d7d374a1b4a63aec/invenio_accounts/sessions.py#L70-L89 | train | 40,862 |
inveniosoftware/invenio-accounts | invenio_accounts/sessions.py | logout_listener | def logout_listener(app, user):
"""Connect to the user_logged_out signal.
:param app: The Flask application.
:param user: The :class:`invenio_accounts.models.User` instance.
"""
@after_this_request
def _commit(response=None):
if hasattr(session, 'sid_s'):
delete_session(session.sid_s)
# Regenerate the session to avoid session fixation vulnerabilities.
session.regenerate()
current_accounts.datastore.commit()
return response | python | def logout_listener(app, user):
"""Connect to the user_logged_out signal.
:param app: The Flask application.
:param user: The :class:`invenio_accounts.models.User` instance.
"""
@after_this_request
def _commit(response=None):
if hasattr(session, 'sid_s'):
delete_session(session.sid_s)
# Regenerate the session to avoid session fixation vulnerabilities.
session.regenerate()
current_accounts.datastore.commit()
return response | [
"def",
"logout_listener",
"(",
"app",
",",
"user",
")",
":",
"@",
"after_this_request",
"def",
"_commit",
"(",
"response",
"=",
"None",
")",
":",
"if",
"hasattr",
"(",
"session",
",",
"'sid_s'",
")",
":",
"delete_session",
"(",
"session",
".",
"sid_s",
"... | Connect to the user_logged_out signal.
:param app: The Flask application.
:param user: The :class:`invenio_accounts.models.User` instance. | [
"Connect",
"to",
"the",
"user_logged_out",
"signal",
"."
] | b0d2f0739b00dbefea22ca15d7d374a1b4a63aec | https://github.com/inveniosoftware/invenio-accounts/blob/b0d2f0739b00dbefea22ca15d7d374a1b4a63aec/invenio_accounts/sessions.py#L92-L105 | train | 40,863 |
inveniosoftware/invenio-accounts | invenio_accounts/sessions.py | delete_session | def delete_session(sid_s):
"""Delete entries in the data- and kvsessionstore with the given sid_s.
On a successful deletion, the flask-kvsession store returns 1 while the
sqlalchemy datastore returns None.
:param sid_s: The session ID.
:returns: ``1`` if deletion was successful.
"""
# Remove entries from sessionstore
_sessionstore.delete(sid_s)
# Find and remove the corresponding SessionActivity entry
with db.session.begin_nested():
SessionActivity.query.filter_by(sid_s=sid_s).delete()
return 1 | python | def delete_session(sid_s):
"""Delete entries in the data- and kvsessionstore with the given sid_s.
On a successful deletion, the flask-kvsession store returns 1 while the
sqlalchemy datastore returns None.
:param sid_s: The session ID.
:returns: ``1`` if deletion was successful.
"""
# Remove entries from sessionstore
_sessionstore.delete(sid_s)
# Find and remove the corresponding SessionActivity entry
with db.session.begin_nested():
SessionActivity.query.filter_by(sid_s=sid_s).delete()
return 1 | [
"def",
"delete_session",
"(",
"sid_s",
")",
":",
"# Remove entries from sessionstore",
"_sessionstore",
".",
"delete",
"(",
"sid_s",
")",
"# Find and remove the corresponding SessionActivity entry",
"with",
"db",
".",
"session",
".",
"begin_nested",
"(",
")",
":",
"Sess... | Delete entries in the data- and kvsessionstore with the given sid_s.
On a successful deletion, the flask-kvsession store returns 1 while the
sqlalchemy datastore returns None.
:param sid_s: The session ID.
:returns: ``1`` if deletion was successful. | [
"Delete",
"entries",
"in",
"the",
"data",
"-",
"and",
"kvsessionstore",
"with",
"the",
"given",
"sid_s",
"."
] | b0d2f0739b00dbefea22ca15d7d374a1b4a63aec | https://github.com/inveniosoftware/invenio-accounts/blob/b0d2f0739b00dbefea22ca15d7d374a1b4a63aec/invenio_accounts/sessions.py#L108-L122 | train | 40,864 |
inveniosoftware/invenio-accounts | invenio_accounts/sessions.py | delete_user_sessions | def delete_user_sessions(user):
"""Delete all active user sessions.
:param user: User instance.
:returns: If ``True`` then the session is successfully deleted.
"""
with db.session.begin_nested():
for s in user.active_sessions:
_sessionstore.delete(s.sid_s)
SessionActivity.query.filter_by(user=user).delete()
return True | python | def delete_user_sessions(user):
"""Delete all active user sessions.
:param user: User instance.
:returns: If ``True`` then the session is successfully deleted.
"""
with db.session.begin_nested():
for s in user.active_sessions:
_sessionstore.delete(s.sid_s)
SessionActivity.query.filter_by(user=user).delete()
return True | [
"def",
"delete_user_sessions",
"(",
"user",
")",
":",
"with",
"db",
".",
"session",
".",
"begin_nested",
"(",
")",
":",
"for",
"s",
"in",
"user",
".",
"active_sessions",
":",
"_sessionstore",
".",
"delete",
"(",
"s",
".",
"sid_s",
")",
"SessionActivity",
... | Delete all active user sessions.
:param user: User instance.
:returns: If ``True`` then the session is successfully deleted. | [
"Delete",
"all",
"active",
"user",
"sessions",
"."
] | b0d2f0739b00dbefea22ca15d7d374a1b4a63aec | https://github.com/inveniosoftware/invenio-accounts/blob/b0d2f0739b00dbefea22ca15d7d374a1b4a63aec/invenio_accounts/sessions.py#L125-L137 | train | 40,865 |
inveniosoftware/invenio-accounts | invenio_accounts/forms.py | confirm_register_form_factory | def confirm_register_form_factory(Form, app):
"""Return confirmation for extended registration form."""
if app.config.get('RECAPTCHA_PUBLIC_KEY') and \
app.config.get('RECAPTCHA_PRIVATE_KEY'):
class ConfirmRegisterForm(Form):
recaptcha = FormField(RegistrationFormRecaptcha, separator='.')
return ConfirmRegisterForm
return Form | python | def confirm_register_form_factory(Form, app):
"""Return confirmation for extended registration form."""
if app.config.get('RECAPTCHA_PUBLIC_KEY') and \
app.config.get('RECAPTCHA_PRIVATE_KEY'):
class ConfirmRegisterForm(Form):
recaptcha = FormField(RegistrationFormRecaptcha, separator='.')
return ConfirmRegisterForm
return Form | [
"def",
"confirm_register_form_factory",
"(",
"Form",
",",
"app",
")",
":",
"if",
"app",
".",
"config",
".",
"get",
"(",
"'RECAPTCHA_PUBLIC_KEY'",
")",
"and",
"app",
".",
"config",
".",
"get",
"(",
"'RECAPTCHA_PRIVATE_KEY'",
")",
":",
"class",
"ConfirmRegisterF... | Return confirmation for extended registration form. | [
"Return",
"confirmation",
"for",
"extended",
"registration",
"form",
"."
] | b0d2f0739b00dbefea22ca15d7d374a1b4a63aec | https://github.com/inveniosoftware/invenio-accounts/blob/b0d2f0739b00dbefea22ca15d7d374a1b4a63aec/invenio_accounts/forms.py#L31-L40 | train | 40,866 |
inveniosoftware/invenio-accounts | invenio_accounts/forms.py | register_form_factory | def register_form_factory(Form, app):
"""Return extended registration form."""
if app.config.get('RECAPTCHA_PUBLIC_KEY') and \
app.config.get('RECAPTCHA_PRIVATE_KEY'):
class RegisterForm(Form):
recaptcha = FormField(RegistrationFormRecaptcha, separator='.')
return RegisterForm
return Form | python | def register_form_factory(Form, app):
"""Return extended registration form."""
if app.config.get('RECAPTCHA_PUBLIC_KEY') and \
app.config.get('RECAPTCHA_PRIVATE_KEY'):
class RegisterForm(Form):
recaptcha = FormField(RegistrationFormRecaptcha, separator='.')
return RegisterForm
return Form | [
"def",
"register_form_factory",
"(",
"Form",
",",
"app",
")",
":",
"if",
"app",
".",
"config",
".",
"get",
"(",
"'RECAPTCHA_PUBLIC_KEY'",
")",
"and",
"app",
".",
"config",
".",
"get",
"(",
"'RECAPTCHA_PRIVATE_KEY'",
")",
":",
"class",
"RegisterForm",
"(",
... | Return extended registration form. | [
"Return",
"extended",
"registration",
"form",
"."
] | b0d2f0739b00dbefea22ca15d7d374a1b4a63aec | https://github.com/inveniosoftware/invenio-accounts/blob/b0d2f0739b00dbefea22ca15d7d374a1b4a63aec/invenio_accounts/forms.py#L43-L52 | train | 40,867 |
inveniosoftware/invenio-accounts | invenio_accounts/forms.py | login_form_factory | def login_form_factory(Form, app):
"""Return extended login form."""
class LoginForm(Form):
def __init__(self, *args, **kwargs):
"""Init the login form.
.. note::
The ``remember me`` option will be completely disabled.
"""
super(LoginForm, self).__init__(*args, **kwargs)
self.remember.data = False
return LoginForm | python | def login_form_factory(Form, app):
"""Return extended login form."""
class LoginForm(Form):
def __init__(self, *args, **kwargs):
"""Init the login form.
.. note::
The ``remember me`` option will be completely disabled.
"""
super(LoginForm, self).__init__(*args, **kwargs)
self.remember.data = False
return LoginForm | [
"def",
"login_form_factory",
"(",
"Form",
",",
"app",
")",
":",
"class",
"LoginForm",
"(",
"Form",
")",
":",
"def",
"__init__",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"\"\"\"Init the login form.\n\n .. note::\n\n ... | Return extended login form. | [
"Return",
"extended",
"login",
"form",
"."
] | b0d2f0739b00dbefea22ca15d7d374a1b4a63aec | https://github.com/inveniosoftware/invenio-accounts/blob/b0d2f0739b00dbefea22ca15d7d374a1b4a63aec/invenio_accounts/forms.py#L55-L69 | train | 40,868 |
inveniosoftware/invenio-accounts | invenio_accounts/admin.py | UserView.on_model_change | def on_model_change(self, form, User, is_created):
"""Hash password when saving."""
if form.password.data is not None:
pwd_ctx = current_app.extensions['security'].pwd_context
if pwd_ctx.identify(form.password.data) is None:
User.password = hash_password(form.password.data) | python | def on_model_change(self, form, User, is_created):
"""Hash password when saving."""
if form.password.data is not None:
pwd_ctx = current_app.extensions['security'].pwd_context
if pwd_ctx.identify(form.password.data) is None:
User.password = hash_password(form.password.data) | [
"def",
"on_model_change",
"(",
"self",
",",
"form",
",",
"User",
",",
"is_created",
")",
":",
"if",
"form",
".",
"password",
".",
"data",
"is",
"not",
"None",
":",
"pwd_ctx",
"=",
"current_app",
".",
"extensions",
"[",
"'security'",
"]",
".",
"pwd_contex... | Hash password when saving. | [
"Hash",
"password",
"when",
"saving",
"."
] | b0d2f0739b00dbefea22ca15d7d374a1b4a63aec | https://github.com/inveniosoftware/invenio-accounts/blob/b0d2f0739b00dbefea22ca15d7d374a1b4a63aec/invenio_accounts/admin.py#L78-L83 | train | 40,869 |
inveniosoftware/invenio-accounts | invenio_accounts/admin.py | UserView.after_model_change | def after_model_change(self, form, User, is_created):
"""Send password instructions if desired."""
if is_created and form.notification.data is True:
send_reset_password_instructions(User) | python | def after_model_change(self, form, User, is_created):
"""Send password instructions if desired."""
if is_created and form.notification.data is True:
send_reset_password_instructions(User) | [
"def",
"after_model_change",
"(",
"self",
",",
"form",
",",
"User",
",",
"is_created",
")",
":",
"if",
"is_created",
"and",
"form",
".",
"notification",
".",
"data",
"is",
"True",
":",
"send_reset_password_instructions",
"(",
"User",
")"
] | Send password instructions if desired. | [
"Send",
"password",
"instructions",
"if",
"desired",
"."
] | b0d2f0739b00dbefea22ca15d7d374a1b4a63aec | https://github.com/inveniosoftware/invenio-accounts/blob/b0d2f0739b00dbefea22ca15d7d374a1b4a63aec/invenio_accounts/admin.py#L85-L88 | train | 40,870 |
inveniosoftware/invenio-accounts | invenio_accounts/admin.py | SessionActivityView.delete_model | def delete_model(self, model):
"""Delete a specific session."""
if SessionActivity.is_current(sid_s=model.sid_s):
flash('You could not remove your current session', 'error')
return
delete_session(sid_s=model.sid_s)
db.session.commit() | python | def delete_model(self, model):
"""Delete a specific session."""
if SessionActivity.is_current(sid_s=model.sid_s):
flash('You could not remove your current session', 'error')
return
delete_session(sid_s=model.sid_s)
db.session.commit() | [
"def",
"delete_model",
"(",
"self",
",",
"model",
")",
":",
"if",
"SessionActivity",
".",
"is_current",
"(",
"sid_s",
"=",
"model",
".",
"sid_s",
")",
":",
"flash",
"(",
"'You could not remove your current session'",
",",
"'error'",
")",
"return",
"delete_sessio... | Delete a specific session. | [
"Delete",
"a",
"specific",
"session",
"."
] | b0d2f0739b00dbefea22ca15d7d374a1b4a63aec | https://github.com/inveniosoftware/invenio-accounts/blob/b0d2f0739b00dbefea22ca15d7d374a1b4a63aec/invenio_accounts/admin.py#L193-L199 | train | 40,871 |
inveniosoftware/invenio-accounts | invenio_accounts/admin.py | SessionActivityView.action_delete | def action_delete(self, ids):
"""Delete selected sessions."""
is_current = any(SessionActivity.is_current(sid_s=id_) for id_ in ids)
if is_current:
flash('You could not remove your current session', 'error')
return
for id_ in ids:
delete_session(sid_s=id_)
db.session.commit() | python | def action_delete(self, ids):
"""Delete selected sessions."""
is_current = any(SessionActivity.is_current(sid_s=id_) for id_ in ids)
if is_current:
flash('You could not remove your current session', 'error')
return
for id_ in ids:
delete_session(sid_s=id_)
db.session.commit() | [
"def",
"action_delete",
"(",
"self",
",",
"ids",
")",
":",
"is_current",
"=",
"any",
"(",
"SessionActivity",
".",
"is_current",
"(",
"sid_s",
"=",
"id_",
")",
"for",
"id_",
"in",
"ids",
")",
"if",
"is_current",
":",
"flash",
"(",
"'You could not remove you... | Delete selected sessions. | [
"Delete",
"selected",
"sessions",
"."
] | b0d2f0739b00dbefea22ca15d7d374a1b4a63aec | https://github.com/inveniosoftware/invenio-accounts/blob/b0d2f0739b00dbefea22ca15d7d374a1b4a63aec/invenio_accounts/admin.py#L203-L211 | train | 40,872 |
inveniosoftware/invenio-accounts | invenio_accounts/tasks.py | send_security_email | def send_security_email(data):
"""Celery task to send security email.
:param data: Contains the email data.
"""
msg = Message()
msg.__dict__.update(data)
current_app.extensions['mail'].send(msg) | python | def send_security_email(data):
"""Celery task to send security email.
:param data: Contains the email data.
"""
msg = Message()
msg.__dict__.update(data)
current_app.extensions['mail'].send(msg) | [
"def",
"send_security_email",
"(",
"data",
")",
":",
"msg",
"=",
"Message",
"(",
")",
"msg",
".",
"__dict__",
".",
"update",
"(",
"data",
")",
"current_app",
".",
"extensions",
"[",
"'mail'",
"]",
".",
"send",
"(",
"msg",
")"
] | Celery task to send security email.
:param data: Contains the email data. | [
"Celery",
"task",
"to",
"send",
"security",
"email",
"."
] | b0d2f0739b00dbefea22ca15d7d374a1b4a63aec | https://github.com/inveniosoftware/invenio-accounts/blob/b0d2f0739b00dbefea22ca15d7d374a1b4a63aec/invenio_accounts/tasks.py#L24-L31 | train | 40,873 |
inveniosoftware/invenio-accounts | invenio_accounts/tasks.py | clean_session_table | def clean_session_table():
"""Automatically clean session table.
To enable a periodically clean of the session table, you should configure
the task as a celery periodic task.
.. code-block:: python
from datetime import timedelta
CELERYBEAT_SCHEDULE = {
'session_cleaner': {
'task': 'invenio_accounts.tasks.clean_session_table',
'schedule': timedelta(days=1),
},
}
See `Invenio-Celery <https://invenio-celery.readthedocs.io/>`_
documentation for further details.
"""
sessions = SessionActivity.query_by_expired().all()
for session in sessions:
delete_session(sid_s=session.sid_s)
db.session.commit() | python | def clean_session_table():
"""Automatically clean session table.
To enable a periodically clean of the session table, you should configure
the task as a celery periodic task.
.. code-block:: python
from datetime import timedelta
CELERYBEAT_SCHEDULE = {
'session_cleaner': {
'task': 'invenio_accounts.tasks.clean_session_table',
'schedule': timedelta(days=1),
},
}
See `Invenio-Celery <https://invenio-celery.readthedocs.io/>`_
documentation for further details.
"""
sessions = SessionActivity.query_by_expired().all()
for session in sessions:
delete_session(sid_s=session.sid_s)
db.session.commit() | [
"def",
"clean_session_table",
"(",
")",
":",
"sessions",
"=",
"SessionActivity",
".",
"query_by_expired",
"(",
")",
".",
"all",
"(",
")",
"for",
"session",
"in",
"sessions",
":",
"delete_session",
"(",
"sid_s",
"=",
"session",
".",
"sid_s",
")",
"db",
".",... | Automatically clean session table.
To enable a periodically clean of the session table, you should configure
the task as a celery periodic task.
.. code-block:: python
from datetime import timedelta
CELERYBEAT_SCHEDULE = {
'session_cleaner': {
'task': 'invenio_accounts.tasks.clean_session_table',
'schedule': timedelta(days=1),
},
}
See `Invenio-Celery <https://invenio-celery.readthedocs.io/>`_
documentation for further details. | [
"Automatically",
"clean",
"session",
"table",
"."
] | b0d2f0739b00dbefea22ca15d7d374a1b4a63aec | https://github.com/inveniosoftware/invenio-accounts/blob/b0d2f0739b00dbefea22ca15d7d374a1b4a63aec/invenio_accounts/tasks.py#L35-L57 | train | 40,874 |
inveniosoftware/invenio-accounts | invenio_accounts/utils.py | jwt_create_token | def jwt_create_token(user_id=None, additional_data=None):
"""Encode the JWT token.
:param int user_id: Addition of user_id.
:param dict additional_data: Additional information for the token.
:returns: The encoded token.
:rtype: str
.. note::
Definition of the JWT claims:
* exp: ((Expiration Time) expiration time of the JWT.
* sub: (subject) the principal that is the subject of the JWT.
* jti: (JWT ID) UID for the JWT.
"""
# Create an ID
uid = str(uuid.uuid4())
# The time in UTC now
now = datetime.utcnow()
# Build the token data
token_data = {
'exp': now + current_app.config['ACCOUNTS_JWT_EXPIRATION_DELTA'],
'sub': user_id or current_user.get_id(),
'jti': uid,
}
# Add any additional data to the token
if additional_data is not None:
token_data.update(additional_data)
# Encode the token and send it back
encoded_token = encode(
token_data,
current_app.config['ACCOUNTS_JWT_SECRET_KEY'],
current_app.config['ACCOUNTS_JWT_ALOGORITHM']
).decode('utf-8')
return encoded_token | python | def jwt_create_token(user_id=None, additional_data=None):
"""Encode the JWT token.
:param int user_id: Addition of user_id.
:param dict additional_data: Additional information for the token.
:returns: The encoded token.
:rtype: str
.. note::
Definition of the JWT claims:
* exp: ((Expiration Time) expiration time of the JWT.
* sub: (subject) the principal that is the subject of the JWT.
* jti: (JWT ID) UID for the JWT.
"""
# Create an ID
uid = str(uuid.uuid4())
# The time in UTC now
now = datetime.utcnow()
# Build the token data
token_data = {
'exp': now + current_app.config['ACCOUNTS_JWT_EXPIRATION_DELTA'],
'sub': user_id or current_user.get_id(),
'jti': uid,
}
# Add any additional data to the token
if additional_data is not None:
token_data.update(additional_data)
# Encode the token and send it back
encoded_token = encode(
token_data,
current_app.config['ACCOUNTS_JWT_SECRET_KEY'],
current_app.config['ACCOUNTS_JWT_ALOGORITHM']
).decode('utf-8')
return encoded_token | [
"def",
"jwt_create_token",
"(",
"user_id",
"=",
"None",
",",
"additional_data",
"=",
"None",
")",
":",
"# Create an ID",
"uid",
"=",
"str",
"(",
"uuid",
".",
"uuid4",
"(",
")",
")",
"# The time in UTC now",
"now",
"=",
"datetime",
".",
"utcnow",
"(",
")",
... | Encode the JWT token.
:param int user_id: Addition of user_id.
:param dict additional_data: Additional information for the token.
:returns: The encoded token.
:rtype: str
.. note::
Definition of the JWT claims:
* exp: ((Expiration Time) expiration time of the JWT.
* sub: (subject) the principal that is the subject of the JWT.
* jti: (JWT ID) UID for the JWT. | [
"Encode",
"the",
"JWT",
"token",
"."
] | b0d2f0739b00dbefea22ca15d7d374a1b4a63aec | https://github.com/inveniosoftware/invenio-accounts/blob/b0d2f0739b00dbefea22ca15d7d374a1b4a63aec/invenio_accounts/utils.py#L22-L57 | train | 40,875 |
inveniosoftware/invenio-accounts | invenio_accounts/utils.py | jwt_decode_token | def jwt_decode_token(token):
"""Decode the JWT token.
:param str token: Additional information for the token.
:returns: The token data.
:rtype: dict
"""
try:
return decode(
token,
current_app.config['ACCOUNTS_JWT_SECRET_KEY'],
algorithms=[
current_app.config['ACCOUNTS_JWT_ALOGORITHM']
]
)
except DecodeError as exc:
raise_from(JWTDecodeError(), exc)
except ExpiredSignatureError as exc:
raise_from(JWTExpiredToken(), exc) | python | def jwt_decode_token(token):
"""Decode the JWT token.
:param str token: Additional information for the token.
:returns: The token data.
:rtype: dict
"""
try:
return decode(
token,
current_app.config['ACCOUNTS_JWT_SECRET_KEY'],
algorithms=[
current_app.config['ACCOUNTS_JWT_ALOGORITHM']
]
)
except DecodeError as exc:
raise_from(JWTDecodeError(), exc)
except ExpiredSignatureError as exc:
raise_from(JWTExpiredToken(), exc) | [
"def",
"jwt_decode_token",
"(",
"token",
")",
":",
"try",
":",
"return",
"decode",
"(",
"token",
",",
"current_app",
".",
"config",
"[",
"'ACCOUNTS_JWT_SECRET_KEY'",
"]",
",",
"algorithms",
"=",
"[",
"current_app",
".",
"config",
"[",
"'ACCOUNTS_JWT_ALOGORITHM'"... | Decode the JWT token.
:param str token: Additional information for the token.
:returns: The token data.
:rtype: dict | [
"Decode",
"the",
"JWT",
"token",
"."
] | b0d2f0739b00dbefea22ca15d7d374a1b4a63aec | https://github.com/inveniosoftware/invenio-accounts/blob/b0d2f0739b00dbefea22ca15d7d374a1b4a63aec/invenio_accounts/utils.py#L60-L78 | train | 40,876 |
inveniosoftware/invenio-accounts | invenio_accounts/utils.py | set_session_info | def set_session_info(app, response, **extra):
"""Add X-Session-ID and X-User-ID to http response."""
session_id = getattr(session, 'sid_s', None)
if session_id:
response.headers['X-Session-ID'] = session_id
if current_user.is_authenticated:
response.headers['X-User-ID'] = current_user.get_id() | python | def set_session_info(app, response, **extra):
"""Add X-Session-ID and X-User-ID to http response."""
session_id = getattr(session, 'sid_s', None)
if session_id:
response.headers['X-Session-ID'] = session_id
if current_user.is_authenticated:
response.headers['X-User-ID'] = current_user.get_id() | [
"def",
"set_session_info",
"(",
"app",
",",
"response",
",",
"*",
"*",
"extra",
")",
":",
"session_id",
"=",
"getattr",
"(",
"session",
",",
"'sid_s'",
",",
"None",
")",
"if",
"session_id",
":",
"response",
".",
"headers",
"[",
"'X-Session-ID'",
"]",
"="... | Add X-Session-ID and X-User-ID to http response. | [
"Add",
"X",
"-",
"Session",
"-",
"ID",
"and",
"X",
"-",
"User",
"-",
"ID",
"to",
"http",
"response",
"."
] | b0d2f0739b00dbefea22ca15d7d374a1b4a63aec | https://github.com/inveniosoftware/invenio-accounts/blob/b0d2f0739b00dbefea22ca15d7d374a1b4a63aec/invenio_accounts/utils.py#L81-L87 | train | 40,877 |
inveniosoftware/invenio-accounts | invenio_accounts/views/security.py | security | def security():
"""View for security page."""
sessions = SessionActivity.query_by_user(
user_id=current_user.get_id()
).all()
master_session = None
for index, session in enumerate(sessions):
if SessionActivity.is_current(session.sid_s):
master_session = session
del sessions[index]
return render_template(
current_app.config['ACCOUNTS_SETTINGS_SECURITY_TEMPLATE'],
formclass=RevokeForm,
sessions=[master_session] + sessions,
is_current=SessionActivity.is_current
) | python | def security():
"""View for security page."""
sessions = SessionActivity.query_by_user(
user_id=current_user.get_id()
).all()
master_session = None
for index, session in enumerate(sessions):
if SessionActivity.is_current(session.sid_s):
master_session = session
del sessions[index]
return render_template(
current_app.config['ACCOUNTS_SETTINGS_SECURITY_TEMPLATE'],
formclass=RevokeForm,
sessions=[master_session] + sessions,
is_current=SessionActivity.is_current
) | [
"def",
"security",
"(",
")",
":",
"sessions",
"=",
"SessionActivity",
".",
"query_by_user",
"(",
"user_id",
"=",
"current_user",
".",
"get_id",
"(",
")",
")",
".",
"all",
"(",
")",
"master_session",
"=",
"None",
"for",
"index",
",",
"session",
"in",
"enu... | View for security page. | [
"View",
"for",
"security",
"page",
"."
] | b0d2f0739b00dbefea22ca15d7d374a1b4a63aec | https://github.com/inveniosoftware/invenio-accounts/blob/b0d2f0739b00dbefea22ca15d7d374a1b4a63aec/invenio_accounts/views/security.py#L35-L50 | train | 40,878 |
inveniosoftware/invenio-accounts | invenio_accounts/views/security.py | revoke_session | def revoke_session():
"""Revoke a session."""
form = RevokeForm(request.form)
if not form.validate_on_submit():
abort(403)
sid_s = form.data['sid_s']
if SessionActivity.query.filter_by(
user_id=current_user.get_id(), sid_s=sid_s).count() == 1:
delete_session(sid_s=sid_s)
db.session.commit()
if not SessionActivity.is_current(sid_s=sid_s):
# if it's the same session doesn't show the message, otherwise
# the session will be still open without the database record
flash('Session {0} successfully removed.'.format(sid_s), 'success')
else:
flash('Unable to remove the session {0}.'.format(sid_s), 'error')
return redirect(url_for('invenio_accounts.security')) | python | def revoke_session():
"""Revoke a session."""
form = RevokeForm(request.form)
if not form.validate_on_submit():
abort(403)
sid_s = form.data['sid_s']
if SessionActivity.query.filter_by(
user_id=current_user.get_id(), sid_s=sid_s).count() == 1:
delete_session(sid_s=sid_s)
db.session.commit()
if not SessionActivity.is_current(sid_s=sid_s):
# if it's the same session doesn't show the message, otherwise
# the session will be still open without the database record
flash('Session {0} successfully removed.'.format(sid_s), 'success')
else:
flash('Unable to remove the session {0}.'.format(sid_s), 'error')
return redirect(url_for('invenio_accounts.security')) | [
"def",
"revoke_session",
"(",
")",
":",
"form",
"=",
"RevokeForm",
"(",
"request",
".",
"form",
")",
"if",
"not",
"form",
".",
"validate_on_submit",
"(",
")",
":",
"abort",
"(",
"403",
")",
"sid_s",
"=",
"form",
".",
"data",
"[",
"'sid_s'",
"]",
"if"... | Revoke a session. | [
"Revoke",
"a",
"session",
"."
] | b0d2f0739b00dbefea22ca15d7d374a1b4a63aec | https://github.com/inveniosoftware/invenio-accounts/blob/b0d2f0739b00dbefea22ca15d7d374a1b4a63aec/invenio_accounts/views/security.py#L54-L71 | train | 40,879 |
inveniosoftware/invenio-accounts | invenio_accounts/models.py | SessionActivity.query_by_expired | def query_by_expired(cls):
"""Query to select all expired sessions."""
lifetime = current_app.permanent_session_lifetime
expired_moment = datetime.utcnow() - lifetime
return cls.query.filter(cls.created < expired_moment) | python | def query_by_expired(cls):
"""Query to select all expired sessions."""
lifetime = current_app.permanent_session_lifetime
expired_moment = datetime.utcnow() - lifetime
return cls.query.filter(cls.created < expired_moment) | [
"def",
"query_by_expired",
"(",
"cls",
")",
":",
"lifetime",
"=",
"current_app",
".",
"permanent_session_lifetime",
"expired_moment",
"=",
"datetime",
".",
"utcnow",
"(",
")",
"-",
"lifetime",
"return",
"cls",
".",
"query",
".",
"filter",
"(",
"cls",
".",
"c... | Query to select all expired sessions. | [
"Query",
"to",
"select",
"all",
"expired",
"sessions",
"."
] | b0d2f0739b00dbefea22ca15d7d374a1b4a63aec | https://github.com/inveniosoftware/invenio-accounts/blob/b0d2f0739b00dbefea22ca15d7d374a1b4a63aec/invenio_accounts/models.py#L141-L145 | train | 40,880 |
inveniosoftware/invenio-accounts | invenio_accounts/ext.py | InvenioAccounts.monkey_patch_flask_security | def monkey_patch_flask_security():
"""Monkey-patch Flask-Security."""
if utils.get_hmac != get_hmac:
utils.get_hmac = get_hmac
if utils.hash_password != hash_password:
utils.hash_password = hash_password
changeable.hash_password = hash_password
recoverable.hash_password = hash_password
registerable.hash_password = hash_password
# Disable remember me cookie generation as it does not work with
# session activity tracking (a remember me token will bypass revoking
# of a session).
def patch_do_nothing(*args, **kwargs):
pass
LoginManager._set_cookie = patch_do_nothing
# Disable loading user from headers and object because we want to be
# sure we can load user only through the login form.
def patch_reload_anonym(self, *args, **kwargs):
self.reload_user()
LoginManager._load_from_header = patch_reload_anonym
LoginManager._load_from_request = patch_reload_anonym | python | def monkey_patch_flask_security():
"""Monkey-patch Flask-Security."""
if utils.get_hmac != get_hmac:
utils.get_hmac = get_hmac
if utils.hash_password != hash_password:
utils.hash_password = hash_password
changeable.hash_password = hash_password
recoverable.hash_password = hash_password
registerable.hash_password = hash_password
# Disable remember me cookie generation as it does not work with
# session activity tracking (a remember me token will bypass revoking
# of a session).
def patch_do_nothing(*args, **kwargs):
pass
LoginManager._set_cookie = patch_do_nothing
# Disable loading user from headers and object because we want to be
# sure we can load user only through the login form.
def patch_reload_anonym(self, *args, **kwargs):
self.reload_user()
LoginManager._load_from_header = patch_reload_anonym
LoginManager._load_from_request = patch_reload_anonym | [
"def",
"monkey_patch_flask_security",
"(",
")",
":",
"if",
"utils",
".",
"get_hmac",
"!=",
"get_hmac",
":",
"utils",
".",
"get_hmac",
"=",
"get_hmac",
"if",
"utils",
".",
"hash_password",
"!=",
"hash_password",
":",
"utils",
".",
"hash_password",
"=",
"hash_pa... | Monkey-patch Flask-Security. | [
"Monkey",
"-",
"patch",
"Flask",
"-",
"Security",
"."
] | b0d2f0739b00dbefea22ca15d7d374a1b4a63aec | https://github.com/inveniosoftware/invenio-accounts/blob/b0d2f0739b00dbefea22ca15d7d374a1b4a63aec/invenio_accounts/ext.py#L72-L94 | train | 40,881 |
inveniosoftware/invenio-accounts | invenio_accounts/ext.py | InvenioAccounts._enable_session_activity | def _enable_session_activity(self, app):
"""Enable session activity."""
user_logged_in.connect(login_listener, app)
user_logged_out.connect(logout_listener, app)
from .views.settings import blueprint
from .views.security import security, revoke_session
blueprint.route('/security/', methods=['GET'])(security)
blueprint.route('/sessions/revoke/', methods=['POST'])(revoke_session) | python | def _enable_session_activity(self, app):
"""Enable session activity."""
user_logged_in.connect(login_listener, app)
user_logged_out.connect(logout_listener, app)
from .views.settings import blueprint
from .views.security import security, revoke_session
blueprint.route('/security/', methods=['GET'])(security)
blueprint.route('/sessions/revoke/', methods=['POST'])(revoke_session) | [
"def",
"_enable_session_activity",
"(",
"self",
",",
"app",
")",
":",
"user_logged_in",
".",
"connect",
"(",
"login_listener",
",",
"app",
")",
"user_logged_out",
".",
"connect",
"(",
"logout_listener",
",",
"app",
")",
"from",
".",
"views",
".",
"settings",
... | Enable session activity. | [
"Enable",
"session",
"activity",
"."
] | b0d2f0739b00dbefea22ca15d7d374a1b4a63aec | https://github.com/inveniosoftware/invenio-accounts/blob/b0d2f0739b00dbefea22ca15d7d374a1b4a63aec/invenio_accounts/ext.py#L266-L273 | train | 40,882 |
iamteem/redisco | redisco/models/base.py | _initialize_attributes | def _initialize_attributes(model_class, name, bases, attrs):
"""Initialize the attributes of the model."""
model_class._attributes = {}
for k, v in attrs.iteritems():
if isinstance(v, Attribute):
model_class._attributes[k] = v
v.name = v.name or k | python | def _initialize_attributes(model_class, name, bases, attrs):
"""Initialize the attributes of the model."""
model_class._attributes = {}
for k, v in attrs.iteritems():
if isinstance(v, Attribute):
model_class._attributes[k] = v
v.name = v.name or k | [
"def",
"_initialize_attributes",
"(",
"model_class",
",",
"name",
",",
"bases",
",",
"attrs",
")",
":",
"model_class",
".",
"_attributes",
"=",
"{",
"}",
"for",
"k",
",",
"v",
"in",
"attrs",
".",
"iteritems",
"(",
")",
":",
"if",
"isinstance",
"(",
"v"... | Initialize the attributes of the model. | [
"Initialize",
"the",
"attributes",
"of",
"the",
"model",
"."
] | a7ba19ff3c38061d6d8bc0c10fa754baadcfeb91 | https://github.com/iamteem/redisco/blob/a7ba19ff3c38061d6d8bc0c10fa754baadcfeb91/redisco/models/base.py#L19-L25 | train | 40,883 |
iamteem/redisco | redisco/models/base.py | _initialize_referenced | def _initialize_referenced(model_class, attribute):
"""Adds a property to the target of a reference field that
returns the list of associated objects.
"""
# this should be a descriptor
def _related_objects(self):
return (model_class.objects
.filter(**{attribute.attname: self.id}))
klass = attribute._target_type
if isinstance(klass, basestring):
return (klass, model_class, attribute)
else:
related_name = (attribute.related_name or
model_class.__name__.lower() + '_set')
setattr(klass, related_name,
property(_related_objects)) | python | def _initialize_referenced(model_class, attribute):
"""Adds a property to the target of a reference field that
returns the list of associated objects.
"""
# this should be a descriptor
def _related_objects(self):
return (model_class.objects
.filter(**{attribute.attname: self.id}))
klass = attribute._target_type
if isinstance(klass, basestring):
return (klass, model_class, attribute)
else:
related_name = (attribute.related_name or
model_class.__name__.lower() + '_set')
setattr(klass, related_name,
property(_related_objects)) | [
"def",
"_initialize_referenced",
"(",
"model_class",
",",
"attribute",
")",
":",
"# this should be a descriptor",
"def",
"_related_objects",
"(",
"self",
")",
":",
"return",
"(",
"model_class",
".",
"objects",
".",
"filter",
"(",
"*",
"*",
"{",
"attribute",
".",... | Adds a property to the target of a reference field that
returns the list of associated objects. | [
"Adds",
"a",
"property",
"to",
"the",
"target",
"of",
"a",
"reference",
"field",
"that",
"returns",
"the",
"list",
"of",
"associated",
"objects",
"."
] | a7ba19ff3c38061d6d8bc0c10fa754baadcfeb91 | https://github.com/iamteem/redisco/blob/a7ba19ff3c38061d6d8bc0c10fa754baadcfeb91/redisco/models/base.py#L27-L43 | train | 40,884 |
iamteem/redisco | redisco/models/base.py | _initialize_lists | def _initialize_lists(model_class, name, bases, attrs):
"""Stores the list fields descriptors of a model."""
model_class._lists = {}
for k, v in attrs.iteritems():
if isinstance(v, ListField):
model_class._lists[k] = v
v.name = v.name or k | python | def _initialize_lists(model_class, name, bases, attrs):
"""Stores the list fields descriptors of a model."""
model_class._lists = {}
for k, v in attrs.iteritems():
if isinstance(v, ListField):
model_class._lists[k] = v
v.name = v.name or k | [
"def",
"_initialize_lists",
"(",
"model_class",
",",
"name",
",",
"bases",
",",
"attrs",
")",
":",
"model_class",
".",
"_lists",
"=",
"{",
"}",
"for",
"k",
",",
"v",
"in",
"attrs",
".",
"iteritems",
"(",
")",
":",
"if",
"isinstance",
"(",
"v",
",",
... | Stores the list fields descriptors of a model. | [
"Stores",
"the",
"list",
"fields",
"descriptors",
"of",
"a",
"model",
"."
] | a7ba19ff3c38061d6d8bc0c10fa754baadcfeb91 | https://github.com/iamteem/redisco/blob/a7ba19ff3c38061d6d8bc0c10fa754baadcfeb91/redisco/models/base.py#L45-L51 | train | 40,885 |
iamteem/redisco | redisco/models/base.py | _initialize_references | def _initialize_references(model_class, name, bases, attrs):
"""Stores the list of reference field descriptors of a model."""
model_class._references = {}
h = {}
deferred = []
for k, v in attrs.iteritems():
if isinstance(v, ReferenceField):
model_class._references[k] = v
v.name = v.name or k
att = Attribute(name=v.attname)
h[v.attname] = att
setattr(model_class, v.attname, att)
refd = _initialize_referenced(model_class, v)
if refd:
deferred.append(refd)
attrs.update(h)
return deferred | python | def _initialize_references(model_class, name, bases, attrs):
"""Stores the list of reference field descriptors of a model."""
model_class._references = {}
h = {}
deferred = []
for k, v in attrs.iteritems():
if isinstance(v, ReferenceField):
model_class._references[k] = v
v.name = v.name or k
att = Attribute(name=v.attname)
h[v.attname] = att
setattr(model_class, v.attname, att)
refd = _initialize_referenced(model_class, v)
if refd:
deferred.append(refd)
attrs.update(h)
return deferred | [
"def",
"_initialize_references",
"(",
"model_class",
",",
"name",
",",
"bases",
",",
"attrs",
")",
":",
"model_class",
".",
"_references",
"=",
"{",
"}",
"h",
"=",
"{",
"}",
"deferred",
"=",
"[",
"]",
"for",
"k",
",",
"v",
"in",
"attrs",
".",
"iterit... | Stores the list of reference field descriptors of a model. | [
"Stores",
"the",
"list",
"of",
"reference",
"field",
"descriptors",
"of",
"a",
"model",
"."
] | a7ba19ff3c38061d6d8bc0c10fa754baadcfeb91 | https://github.com/iamteem/redisco/blob/a7ba19ff3c38061d6d8bc0c10fa754baadcfeb91/redisco/models/base.py#L53-L69 | train | 40,886 |
iamteem/redisco | redisco/models/base.py | _initialize_indices | def _initialize_indices(model_class, name, bases, attrs):
"""Stores the list of indexed attributes."""
model_class._indices = []
for k, v in attrs.iteritems():
if isinstance(v, (Attribute, ListField)) and v.indexed:
model_class._indices.append(k)
if model_class._meta['indices']:
model_class._indices.extend(model_class._meta['indices']) | python | def _initialize_indices(model_class, name, bases, attrs):
"""Stores the list of indexed attributes."""
model_class._indices = []
for k, v in attrs.iteritems():
if isinstance(v, (Attribute, ListField)) and v.indexed:
model_class._indices.append(k)
if model_class._meta['indices']:
model_class._indices.extend(model_class._meta['indices']) | [
"def",
"_initialize_indices",
"(",
"model_class",
",",
"name",
",",
"bases",
",",
"attrs",
")",
":",
"model_class",
".",
"_indices",
"=",
"[",
"]",
"for",
"k",
",",
"v",
"in",
"attrs",
".",
"iteritems",
"(",
")",
":",
"if",
"isinstance",
"(",
"v",
",... | Stores the list of indexed attributes. | [
"Stores",
"the",
"list",
"of",
"indexed",
"attributes",
"."
] | a7ba19ff3c38061d6d8bc0c10fa754baadcfeb91 | https://github.com/iamteem/redisco/blob/a7ba19ff3c38061d6d8bc0c10fa754baadcfeb91/redisco/models/base.py#L71-L78 | train | 40,887 |
iamteem/redisco | redisco/models/base.py | _initialize_counters | def _initialize_counters(model_class, name, bases, attrs):
"""Stores the list of counter fields."""
model_class._counters = []
for k, v in attrs.iteritems():
if isinstance(v, Counter):
model_class._counters.append(k) | python | def _initialize_counters(model_class, name, bases, attrs):
"""Stores the list of counter fields."""
model_class._counters = []
for k, v in attrs.iteritems():
if isinstance(v, Counter):
model_class._counters.append(k) | [
"def",
"_initialize_counters",
"(",
"model_class",
",",
"name",
",",
"bases",
",",
"attrs",
")",
":",
"model_class",
".",
"_counters",
"=",
"[",
"]",
"for",
"k",
",",
"v",
"in",
"attrs",
".",
"iteritems",
"(",
")",
":",
"if",
"isinstance",
"(",
"v",
... | Stores the list of counter fields. | [
"Stores",
"the",
"list",
"of",
"counter",
"fields",
"."
] | a7ba19ff3c38061d6d8bc0c10fa754baadcfeb91 | https://github.com/iamteem/redisco/blob/a7ba19ff3c38061d6d8bc0c10fa754baadcfeb91/redisco/models/base.py#L80-L85 | train | 40,888 |
iamteem/redisco | redisco/models/base.py | get_model_from_key | def get_model_from_key(key):
"""Gets the model from a given key."""
_known_models = {}
model_name = key.split(':', 2)[0]
# populate
for klass in Model.__subclasses__():
_known_models[klass.__name__] = klass
return _known_models.get(model_name, None) | python | def get_model_from_key(key):
"""Gets the model from a given key."""
_known_models = {}
model_name = key.split(':', 2)[0]
# populate
for klass in Model.__subclasses__():
_known_models[klass.__name__] = klass
return _known_models.get(model_name, None) | [
"def",
"get_model_from_key",
"(",
"key",
")",
":",
"_known_models",
"=",
"{",
"}",
"model_name",
"=",
"key",
".",
"split",
"(",
"':'",
",",
"2",
")",
"[",
"0",
"]",
"# populate",
"for",
"klass",
"in",
"Model",
".",
"__subclasses__",
"(",
")",
":",
"_... | Gets the model from a given key. | [
"Gets",
"the",
"model",
"from",
"a",
"given",
"key",
"."
] | a7ba19ff3c38061d6d8bc0c10fa754baadcfeb91 | https://github.com/iamteem/redisco/blob/a7ba19ff3c38061d6d8bc0c10fa754baadcfeb91/redisco/models/base.py#L521-L528 | train | 40,889 |
iamteem/redisco | redisco/models/base.py | from_key | def from_key(key):
"""Returns the model instance based on the key.
Raises BadKeyError if the key is not recognized by
redisco or no defined model can be found.
Returns None if the key could not be found.
"""
model = get_model_from_key(key)
if model is None:
raise BadKeyError
try:
_, id = key.split(':', 2)
id = int(id)
except ValueError, TypeError:
raise BadKeyError
return model.objects.get_by_id(id) | python | def from_key(key):
"""Returns the model instance based on the key.
Raises BadKeyError if the key is not recognized by
redisco or no defined model can be found.
Returns None if the key could not be found.
"""
model = get_model_from_key(key)
if model is None:
raise BadKeyError
try:
_, id = key.split(':', 2)
id = int(id)
except ValueError, TypeError:
raise BadKeyError
return model.objects.get_by_id(id) | [
"def",
"from_key",
"(",
"key",
")",
":",
"model",
"=",
"get_model_from_key",
"(",
"key",
")",
"if",
"model",
"is",
"None",
":",
"raise",
"BadKeyError",
"try",
":",
"_",
",",
"id",
"=",
"key",
".",
"split",
"(",
"':'",
",",
"2",
")",
"id",
"=",
"i... | Returns the model instance based on the key.
Raises BadKeyError if the key is not recognized by
redisco or no defined model can be found.
Returns None if the key could not be found. | [
"Returns",
"the",
"model",
"instance",
"based",
"on",
"the",
"key",
"."
] | a7ba19ff3c38061d6d8bc0c10fa754baadcfeb91 | https://github.com/iamteem/redisco/blob/a7ba19ff3c38061d6d8bc0c10fa754baadcfeb91/redisco/models/base.py#L531-L546 | train | 40,890 |
iamteem/redisco | redisco/models/base.py | Model.is_valid | def is_valid(self):
"""Returns True if all the fields are valid.
It first validates the fields (required, unique, etc.)
and then calls the validate method.
"""
self._errors = []
for field in self.fields:
try:
field.validate(self)
except FieldValidationError, e:
self._errors.extend(e.errors)
self.validate()
return not bool(self._errors) | python | def is_valid(self):
"""Returns True if all the fields are valid.
It first validates the fields (required, unique, etc.)
and then calls the validate method.
"""
self._errors = []
for field in self.fields:
try:
field.validate(self)
except FieldValidationError, e:
self._errors.extend(e.errors)
self.validate()
return not bool(self._errors) | [
"def",
"is_valid",
"(",
"self",
")",
":",
"self",
".",
"_errors",
"=",
"[",
"]",
"for",
"field",
"in",
"self",
".",
"fields",
":",
"try",
":",
"field",
".",
"validate",
"(",
"self",
")",
"except",
"FieldValidationError",
",",
"e",
":",
"self",
".",
... | Returns True if all the fields are valid.
It first validates the fields (required, unique, etc.)
and then calls the validate method. | [
"Returns",
"True",
"if",
"all",
"the",
"fields",
"are",
"valid",
"."
] | a7ba19ff3c38061d6d8bc0c10fa754baadcfeb91 | https://github.com/iamteem/redisco/blob/a7ba19ff3c38061d6d8bc0c10fa754baadcfeb91/redisco/models/base.py#L154-L167 | train | 40,891 |
iamteem/redisco | redisco/models/base.py | Model.update_attributes | def update_attributes(self, **kwargs):
"""Updates the attributes of the model."""
attrs = self.attributes.values() + self.lists.values() \
+ self.references.values()
for att in attrs:
if att.name in kwargs:
att.__set__(self, kwargs[att.name]) | python | def update_attributes(self, **kwargs):
"""Updates the attributes of the model."""
attrs = self.attributes.values() + self.lists.values() \
+ self.references.values()
for att in attrs:
if att.name in kwargs:
att.__set__(self, kwargs[att.name]) | [
"def",
"update_attributes",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"attrs",
"=",
"self",
".",
"attributes",
".",
"values",
"(",
")",
"+",
"self",
".",
"lists",
".",
"values",
"(",
")",
"+",
"self",
".",
"references",
".",
"values",
"(",
")... | Updates the attributes of the model. | [
"Updates",
"the",
"attributes",
"of",
"the",
"model",
"."
] | a7ba19ff3c38061d6d8bc0c10fa754baadcfeb91 | https://github.com/iamteem/redisco/blob/a7ba19ff3c38061d6d8bc0c10fa754baadcfeb91/redisco/models/base.py#L186-L192 | train | 40,892 |
iamteem/redisco | redisco/models/base.py | Model.save | def save(self):
"""Saves the instance to the datastore."""
if not self.is_valid():
return self._errors
_new = self.is_new()
if _new:
self._initialize_id()
with Mutex(self):
self._write(_new)
return True | python | def save(self):
"""Saves the instance to the datastore."""
if not self.is_valid():
return self._errors
_new = self.is_new()
if _new:
self._initialize_id()
with Mutex(self):
self._write(_new)
return True | [
"def",
"save",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"is_valid",
"(",
")",
":",
"return",
"self",
".",
"_errors",
"_new",
"=",
"self",
".",
"is_new",
"(",
")",
"if",
"_new",
":",
"self",
".",
"_initialize_id",
"(",
")",
"with",
"Mutex",
... | Saves the instance to the datastore. | [
"Saves",
"the",
"instance",
"to",
"the",
"datastore",
"."
] | a7ba19ff3c38061d6d8bc0c10fa754baadcfeb91 | https://github.com/iamteem/redisco/blob/a7ba19ff3c38061d6d8bc0c10fa754baadcfeb91/redisco/models/base.py#L194-L203 | train | 40,893 |
iamteem/redisco | redisco/models/base.py | Model.key | def key(self, att=None):
"""Returns the Redis key where the values are stored."""
if att is not None:
return self._key[self.id][att]
else:
return self._key[self.id] | python | def key(self, att=None):
"""Returns the Redis key where the values are stored."""
if att is not None:
return self._key[self.id][att]
else:
return self._key[self.id] | [
"def",
"key",
"(",
"self",
",",
"att",
"=",
"None",
")",
":",
"if",
"att",
"is",
"not",
"None",
":",
"return",
"self",
".",
"_key",
"[",
"self",
".",
"id",
"]",
"[",
"att",
"]",
"else",
":",
"return",
"self",
".",
"_key",
"[",
"self",
".",
"i... | Returns the Redis key where the values are stored. | [
"Returns",
"the",
"Redis",
"key",
"where",
"the",
"values",
"are",
"stored",
"."
] | a7ba19ff3c38061d6d8bc0c10fa754baadcfeb91 | https://github.com/iamteem/redisco/blob/a7ba19ff3c38061d6d8bc0c10fa754baadcfeb91/redisco/models/base.py#L205-L210 | train | 40,894 |
iamteem/redisco | redisco/models/base.py | Model.delete | def delete(self):
"""Deletes the object from the datastore."""
pipeline = self.db.pipeline()
self._delete_from_indices(pipeline)
self._delete_membership(pipeline)
pipeline.delete(self.key())
pipeline.execute() | python | def delete(self):
"""Deletes the object from the datastore."""
pipeline = self.db.pipeline()
self._delete_from_indices(pipeline)
self._delete_membership(pipeline)
pipeline.delete(self.key())
pipeline.execute() | [
"def",
"delete",
"(",
"self",
")",
":",
"pipeline",
"=",
"self",
".",
"db",
".",
"pipeline",
"(",
")",
"self",
".",
"_delete_from_indices",
"(",
"pipeline",
")",
"self",
".",
"_delete_membership",
"(",
"pipeline",
")",
"pipeline",
".",
"delete",
"(",
"se... | Deletes the object from the datastore. | [
"Deletes",
"the",
"object",
"from",
"the",
"datastore",
"."
] | a7ba19ff3c38061d6d8bc0c10fa754baadcfeb91 | https://github.com/iamteem/redisco/blob/a7ba19ff3c38061d6d8bc0c10fa754baadcfeb91/redisco/models/base.py#L212-L218 | train | 40,895 |
iamteem/redisco | redisco/models/base.py | Model.incr | def incr(self, att, val=1):
"""Increments a counter."""
if att not in self.counters:
raise ValueError("%s is not a counter.")
self.db.hincrby(self.key(), att, val) | python | def incr(self, att, val=1):
"""Increments a counter."""
if att not in self.counters:
raise ValueError("%s is not a counter.")
self.db.hincrby(self.key(), att, val) | [
"def",
"incr",
"(",
"self",
",",
"att",
",",
"val",
"=",
"1",
")",
":",
"if",
"att",
"not",
"in",
"self",
".",
"counters",
":",
"raise",
"ValueError",
"(",
"\"%s is not a counter.\"",
")",
"self",
".",
"db",
".",
"hincrby",
"(",
"self",
".",
"key",
... | Increments a counter. | [
"Increments",
"a",
"counter",
"."
] | a7ba19ff3c38061d6d8bc0c10fa754baadcfeb91 | https://github.com/iamteem/redisco/blob/a7ba19ff3c38061d6d8bc0c10fa754baadcfeb91/redisco/models/base.py#L227-L231 | train | 40,896 |
iamteem/redisco | redisco/models/base.py | Model.attributes_dict | def attributes_dict(self):
"""Returns the mapping of the model attributes and their
values.
"""
h = {}
for k in self.attributes.keys():
h[k] = getattr(self, k)
for k in self.lists.keys():
h[k] = getattr(self, k)
for k in self.references.keys():
h[k] = getattr(self, k)
return h | python | def attributes_dict(self):
"""Returns the mapping of the model attributes and their
values.
"""
h = {}
for k in self.attributes.keys():
h[k] = getattr(self, k)
for k in self.lists.keys():
h[k] = getattr(self, k)
for k in self.references.keys():
h[k] = getattr(self, k)
return h | [
"def",
"attributes_dict",
"(",
"self",
")",
":",
"h",
"=",
"{",
"}",
"for",
"k",
"in",
"self",
".",
"attributes",
".",
"keys",
"(",
")",
":",
"h",
"[",
"k",
"]",
"=",
"getattr",
"(",
"self",
",",
"k",
")",
"for",
"k",
"in",
"self",
".",
"list... | Returns the mapping of the model attributes and their
values. | [
"Returns",
"the",
"mapping",
"of",
"the",
"model",
"attributes",
"and",
"their",
"values",
"."
] | a7ba19ff3c38061d6d8bc0c10fa754baadcfeb91 | https://github.com/iamteem/redisco/blob/a7ba19ff3c38061d6d8bc0c10fa754baadcfeb91/redisco/models/base.py#L239-L250 | train | 40,897 |
iamteem/redisco | redisco/models/base.py | Model.fields | def fields(self):
"""Returns the list of field names of the model."""
return (self.attributes.values() + self.lists.values()
+ self.references.values()) | python | def fields(self):
"""Returns the list of field names of the model."""
return (self.attributes.values() + self.lists.values()
+ self.references.values()) | [
"def",
"fields",
"(",
"self",
")",
":",
"return",
"(",
"self",
".",
"attributes",
".",
"values",
"(",
")",
"+",
"self",
".",
"lists",
".",
"values",
"(",
")",
"+",
"self",
".",
"references",
".",
"values",
"(",
")",
")"
] | Returns the list of field names of the model. | [
"Returns",
"the",
"list",
"of",
"field",
"names",
"of",
"the",
"model",
"."
] | a7ba19ff3c38061d6d8bc0c10fa754baadcfeb91 | https://github.com/iamteem/redisco/blob/a7ba19ff3c38061d6d8bc0c10fa754baadcfeb91/redisco/models/base.py#L309-L312 | train | 40,898 |
iamteem/redisco | redisco/models/base.py | Model.exists | def exists(cls, id):
"""Checks if the model with id exists."""
return bool(redisco.get_client().exists(cls._key[str(id)]) or
redisco.get_client().sismember(cls._key['all'], str(id))) | python | def exists(cls, id):
"""Checks if the model with id exists."""
return bool(redisco.get_client().exists(cls._key[str(id)]) or
redisco.get_client().sismember(cls._key['all'], str(id))) | [
"def",
"exists",
"(",
"cls",
",",
"id",
")",
":",
"return",
"bool",
"(",
"redisco",
".",
"get_client",
"(",
")",
".",
"exists",
"(",
"cls",
".",
"_key",
"[",
"str",
"(",
"id",
")",
"]",
")",
"or",
"redisco",
".",
"get_client",
"(",
")",
".",
"s... | Checks if the model with id exists. | [
"Checks",
"if",
"the",
"model",
"with",
"id",
"exists",
"."
] | a7ba19ff3c38061d6d8bc0c10fa754baadcfeb91 | https://github.com/iamteem/redisco/blob/a7ba19ff3c38061d6d8bc0c10fa754baadcfeb91/redisco/models/base.py#L324-L327 | train | 40,899 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.