id
int32
0
252k
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
51
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
25,800
briancappello/flask-unchained
flask_unchained/unchained.py
Unchained.template_filter
def template_filter(self, arg: Optional[Callable] = None, *, name: Optional[str] = None, pass_context: bool = False, inject: Optional[Union[bool, Iterable[str]]] = None, safe: bool = False, ) -> Callable: """ Decorator to mark a function as a Jinja template filter. :param name: The name of the filter, if different from the function name. :param pass_context: Whether or not to pass the template context into the filter. If ``True``, the first argument must be the context. :param inject: Whether or not this filter needs any dependencies injected. :param safe: Whether or not to mark the output of this filter as html-safe. """ def wrapper(fn): fn = _inject(fn, inject) if safe: fn = _make_safe(fn) if pass_context: fn = jinja2.contextfilter(fn) self._defer(lambda app: app.add_template_filter(fn, name=name)) return fn if callable(arg): return wrapper(arg) return wrapper
python
def template_filter(self, arg: Optional[Callable] = None, *, name: Optional[str] = None, pass_context: bool = False, inject: Optional[Union[bool, Iterable[str]]] = None, safe: bool = False, ) -> Callable: def wrapper(fn): fn = _inject(fn, inject) if safe: fn = _make_safe(fn) if pass_context: fn = jinja2.contextfilter(fn) self._defer(lambda app: app.add_template_filter(fn, name=name)) return fn if callable(arg): return wrapper(arg) return wrapper
[ "def", "template_filter", "(", "self", ",", "arg", ":", "Optional", "[", "Callable", "]", "=", "None", ",", "*", ",", "name", ":", "Optional", "[", "str", "]", "=", "None", ",", "pass_context", ":", "bool", "=", "False", ",", "inject", ":", "Optional...
Decorator to mark a function as a Jinja template filter. :param name: The name of the filter, if different from the function name. :param pass_context: Whether or not to pass the template context into the filter. If ``True``, the first argument must be the context. :param inject: Whether or not this filter needs any dependencies injected. :param safe: Whether or not to mark the output of this filter as html-safe.
[ "Decorator", "to", "mark", "a", "function", "as", "a", "Jinja", "template", "filter", "." ]
4d536cb90e2cc4829c1c05f2c74d3e22901a1399
https://github.com/briancappello/flask-unchained/blob/4d536cb90e2cc4829c1c05f2c74d3e22901a1399/flask_unchained/unchained.py#L520-L548
25,801
briancappello/flask-unchained
flask_unchained/unchained.py
Unchained._reset
def _reset(self): """ This method is for use by tests only! """ self.bundles = AttrDict() self._bundles = _DeferredBundleFunctionsStore() self.babel_bundle = None self.env = None self.extensions = AttrDict() self.services = AttrDict() self._deferred_functions = [] self._initialized = False self._models_initialized = False self._services_initialized = False self._services_registry = {} self._shell_ctx = {}
python
def _reset(self): self.bundles = AttrDict() self._bundles = _DeferredBundleFunctionsStore() self.babel_bundle = None self.env = None self.extensions = AttrDict() self.services = AttrDict() self._deferred_functions = [] self._initialized = False self._models_initialized = False self._services_initialized = False self._services_registry = {} self._shell_ctx = {}
[ "def", "_reset", "(", "self", ")", ":", "self", ".", "bundles", "=", "AttrDict", "(", ")", "self", ".", "_bundles", "=", "_DeferredBundleFunctionsStore", "(", ")", "self", ".", "babel_bundle", "=", "None", "self", ".", "env", "=", "None", "self", ".", ...
This method is for use by tests only!
[ "This", "method", "is", "for", "use", "by", "tests", "only!" ]
4d536cb90e2cc4829c1c05f2c74d3e22901a1399
https://github.com/briancappello/flask-unchained/blob/4d536cb90e2cc4829c1c05f2c74d3e22901a1399/flask_unchained/unchained.py#L625-L641
25,802
briancappello/flask-unchained
flask_unchained/bundles/sqlalchemy/forms.py
model_fields
def model_fields(model, db_session=None, only=None, exclude=None, field_args=None, converter=None, exclude_pk=False, exclude_fk=False): """ Generate a dictionary of fields for a given SQLAlchemy model. See `model_form` docstring for description of parameters. """ mapper = model._sa_class_manager.mapper converter = converter or _ModelConverter() field_args = field_args or {} properties = [] for prop in mapper.iterate_properties: if getattr(prop, 'columns', None): if exclude_fk and prop.columns[0].foreign_keys: continue elif exclude_pk and prop.columns[0].primary_key: continue properties.append((prop.key, prop)) # the following if condition is modified: if only is not None: properties = (x for x in properties if x[0] in only) elif exclude: properties = (x for x in properties if x[0] not in exclude) field_dict = {} for name, prop in properties: field = converter.convert( model, mapper, prop, field_args.get(name), db_session ) if field is not None: field_dict[name] = field return field_dict
python
def model_fields(model, db_session=None, only=None, exclude=None, field_args=None, converter=None, exclude_pk=False, exclude_fk=False): mapper = model._sa_class_manager.mapper converter = converter or _ModelConverter() field_args = field_args or {} properties = [] for prop in mapper.iterate_properties: if getattr(prop, 'columns', None): if exclude_fk and prop.columns[0].foreign_keys: continue elif exclude_pk and prop.columns[0].primary_key: continue properties.append((prop.key, prop)) # the following if condition is modified: if only is not None: properties = (x for x in properties if x[0] in only) elif exclude: properties = (x for x in properties if x[0] not in exclude) field_dict = {} for name, prop in properties: field = converter.convert( model, mapper, prop, field_args.get(name), db_session ) if field is not None: field_dict[name] = field return field_dict
[ "def", "model_fields", "(", "model", ",", "db_session", "=", "None", ",", "only", "=", "None", ",", "exclude", "=", "None", ",", "field_args", "=", "None", ",", "converter", "=", "None", ",", "exclude_pk", "=", "False", ",", "exclude_fk", "=", "False", ...
Generate a dictionary of fields for a given SQLAlchemy model. See `model_form` docstring for description of parameters.
[ "Generate", "a", "dictionary", "of", "fields", "for", "a", "given", "SQLAlchemy", "model", "." ]
4d536cb90e2cc4829c1c05f2c74d3e22901a1399
https://github.com/briancappello/flask-unchained/blob/4d536cb90e2cc4829c1c05f2c74d3e22901a1399/flask_unchained/bundles/sqlalchemy/forms.py#L121-L158
25,803
briancappello/flask-unchained
flask_unchained/commands/urls.py
url
def url(url: str, method: str): """Show details for a specific URL.""" try: url_rule, params = (current_app.url_map.bind('localhost') .match(url, method=method, return_rule=True)) except (NotFound, MethodNotAllowed)\ as e: click.secho(str(e), fg='white', bg='red') else: headings = ('Method(s)', 'Rule', 'Params', 'Endpoint', 'View', 'Options') print_table(headings, [(_get_http_methods(url_rule), url_rule.rule if url_rule.strict_slashes else url_rule.rule + '[/]', _format_dict(params), url_rule.endpoint, _get_rule_view(url_rule), _format_rule_options(url_rule))], ['<' if i > 0 else '>' for i, col in enumerate(headings)], primary_column_idx=1)
python
def url(url: str, method: str): try: url_rule, params = (current_app.url_map.bind('localhost') .match(url, method=method, return_rule=True)) except (NotFound, MethodNotAllowed)\ as e: click.secho(str(e), fg='white', bg='red') else: headings = ('Method(s)', 'Rule', 'Params', 'Endpoint', 'View', 'Options') print_table(headings, [(_get_http_methods(url_rule), url_rule.rule if url_rule.strict_slashes else url_rule.rule + '[/]', _format_dict(params), url_rule.endpoint, _get_rule_view(url_rule), _format_rule_options(url_rule))], ['<' if i > 0 else '>' for i, col in enumerate(headings)], primary_column_idx=1)
[ "def", "url", "(", "url", ":", "str", ",", "method", ":", "str", ")", ":", "try", ":", "url_rule", ",", "params", "=", "(", "current_app", ".", "url_map", ".", "bind", "(", "'localhost'", ")", ".", "match", "(", "url", ",", "method", "=", "method",...
Show details for a specific URL.
[ "Show", "details", "for", "a", "specific", "URL", "." ]
4d536cb90e2cc4829c1c05f2c74d3e22901a1399
https://github.com/briancappello/flask-unchained/blob/4d536cb90e2cc4829c1c05f2c74d3e22901a1399/flask_unchained/commands/urls.py#L18-L37
25,804
briancappello/flask-unchained
flask_unchained/commands/urls.py
urls
def urls(order_by: Optional[str] = None): """List all URLs registered with the app.""" url_rules: List[Rule] = current_app.url_map._rules # sort the rules. by default they're sorted by priority, # ie in the order they were registered with the app if order_by == 'view': url_rules = sorted(url_rules, key=lambda rule: _get_rule_view(rule)) elif order_by != 'priority': url_rules = sorted(url_rules, key=lambda rule: getattr(rule, order_by)) headings = ('Method(s)', 'Rule', 'Endpoint', 'View', 'Options') print_table(headings, [(_get_http_methods(url_rule), url_rule.rule if url_rule.strict_slashes else url_rule.rule.rstrip('/') + '[/]', url_rule.endpoint, _get_rule_view(url_rule), _format_rule_options(url_rule), ) for url_rule in url_rules], ['<' if i > 0 else '>' for i, col in enumerate(headings)], primary_column_idx=1)
python
def urls(order_by: Optional[str] = None): url_rules: List[Rule] = current_app.url_map._rules # sort the rules. by default they're sorted by priority, # ie in the order they were registered with the app if order_by == 'view': url_rules = sorted(url_rules, key=lambda rule: _get_rule_view(rule)) elif order_by != 'priority': url_rules = sorted(url_rules, key=lambda rule: getattr(rule, order_by)) headings = ('Method(s)', 'Rule', 'Endpoint', 'View', 'Options') print_table(headings, [(_get_http_methods(url_rule), url_rule.rule if url_rule.strict_slashes else url_rule.rule.rstrip('/') + '[/]', url_rule.endpoint, _get_rule_view(url_rule), _format_rule_options(url_rule), ) for url_rule in url_rules], ['<' if i > 0 else '>' for i, col in enumerate(headings)], primary_column_idx=1)
[ "def", "urls", "(", "order_by", ":", "Optional", "[", "str", "]", "=", "None", ")", ":", "url_rules", ":", "List", "[", "Rule", "]", "=", "current_app", ".", "url_map", ".", "_rules", "# sort the rules. by default they're sorted by priority,", "# ie in the order t...
List all URLs registered with the app.
[ "List", "all", "URLs", "registered", "with", "the", "app", "." ]
4d536cb90e2cc4829c1c05f2c74d3e22901a1399
https://github.com/briancappello/flask-unchained/blob/4d536cb90e2cc4829c1c05f2c74d3e22901a1399/flask_unchained/commands/urls.py#L45-L66
25,805
briancappello/flask-unchained
flask_unchained/bundles/api/extensions/api.py
Api.register_converter
def register_converter(self, converter, conv_type, conv_format=None, *, name=None): """ Register custom path parameter converter. :param BaseConverter converter: Converter Subclass of werkzeug's BaseConverter :param str conv_type: Parameter type :param str conv_format: Parameter format (optional) :param str name: Name of the converter. If not None, this name is used to register the converter in the Flask app. Example:: api.register_converter( UUIDConverter, 'string', 'UUID', name='uuid') @blp.route('/pets/{uuid:pet_id}') # ... api.register_blueprint(blp) This registers the converter in the Flask app and in the internal APISpec instance. Once the converter is registered, all paths using it will have corresponding path parameter documented with the right type and format. The `name` parameter need not be passed if the converter is already registered in the app, for instance if it belongs to a Flask extension that already registers it in the app. """ if name: self.app.url_map.converters[name] = converter self.spec.register_converter(converter, conv_type, conv_format)
python
def register_converter(self, converter, conv_type, conv_format=None, *, name=None): if name: self.app.url_map.converters[name] = converter self.spec.register_converter(converter, conv_type, conv_format)
[ "def", "register_converter", "(", "self", ",", "converter", ",", "conv_type", ",", "conv_format", "=", "None", ",", "*", ",", "name", "=", "None", ")", ":", "if", "name", ":", "self", ".", "app", ".", "url_map", ".", "converters", "[", "name", "]", "...
Register custom path parameter converter. :param BaseConverter converter: Converter Subclass of werkzeug's BaseConverter :param str conv_type: Parameter type :param str conv_format: Parameter format (optional) :param str name: Name of the converter. If not None, this name is used to register the converter in the Flask app. Example:: api.register_converter( UUIDConverter, 'string', 'UUID', name='uuid') @blp.route('/pets/{uuid:pet_id}') # ... api.register_blueprint(blp) This registers the converter in the Flask app and in the internal APISpec instance. Once the converter is registered, all paths using it will have corresponding path parameter documented with the right type and format. The `name` parameter need not be passed if the converter is already registered in the app, for instance if it belongs to a Flask extension that already registers it in the app.
[ "Register", "custom", "path", "parameter", "converter", "." ]
4d536cb90e2cc4829c1c05f2c74d3e22901a1399
https://github.com/briancappello/flask-unchained/blob/4d536cb90e2cc4829c1c05f2c74d3e22901a1399/flask_unchained/bundles/api/extensions/api.py#L138-L167
25,806
briancappello/flask-unchained
flask_unchained/app_factory_hook.py
AppFactoryHook.run_hook
def run_hook(self, app: FlaskUnchained, bundles: List[Bundle]): """ Hook entry point. Override to disable standard behavior of iterating over bundles to discover objects and processing them. """ self.process_objects(app, self.collect_from_bundles(bundles))
python
def run_hook(self, app: FlaskUnchained, bundles: List[Bundle]): self.process_objects(app, self.collect_from_bundles(bundles))
[ "def", "run_hook", "(", "self", ",", "app", ":", "FlaskUnchained", ",", "bundles", ":", "List", "[", "Bundle", "]", ")", ":", "self", ".", "process_objects", "(", "app", ",", "self", ".", "collect_from_bundles", "(", "bundles", ")", ")" ]
Hook entry point. Override to disable standard behavior of iterating over bundles to discover objects and processing them.
[ "Hook", "entry", "point", ".", "Override", "to", "disable", "standard", "behavior", "of", "iterating", "over", "bundles", "to", "discover", "objects", "and", "processing", "them", "." ]
4d536cb90e2cc4829c1c05f2c74d3e22901a1399
https://github.com/briancappello/flask-unchained/blob/4d536cb90e2cc4829c1c05f2c74d3e22901a1399/flask_unchained/app_factory_hook.py#L93-L98
25,807
briancappello/flask-unchained
flask_unchained/clips_pattern.py
singularize
def singularize(word, pos=NOUN, custom=None): """ Returns the singular of a given word. """ if custom and word in custom: return custom[word] # Recurse compound words (e.g. mothers-in-law). if "-" in word: w = word.split("-") if len(w) > 1 and w[1] in plural_prepositions: return singularize(w[0], pos, custom) + "-" + "-".join(w[1:]) # dogs' => dog's if word.endswith("'"): return singularize(word[:-1]) + "'s" w = word.lower() for x in singular_uninflected: if x.endswith(w): return word for x in singular_uncountable: if x.endswith(w): return word for x in singular_ie: if w.endswith(x + "s"): return w[:-1] for x in singular_irregular: if w.endswith(x): return re.sub('(?i)' + x + '$', singular_irregular[x], word) for suffix, inflection in singular_rules: m = suffix.search(word) g = m and m.groups() or [] if m: for k in range(len(g)): if g[k] is None: inflection = inflection.replace('\\' + str(k + 1), '') return suffix.sub(inflection, word) return word
python
def singularize(word, pos=NOUN, custom=None): if custom and word in custom: return custom[word] # Recurse compound words (e.g. mothers-in-law). if "-" in word: w = word.split("-") if len(w) > 1 and w[1] in plural_prepositions: return singularize(w[0], pos, custom) + "-" + "-".join(w[1:]) # dogs' => dog's if word.endswith("'"): return singularize(word[:-1]) + "'s" w = word.lower() for x in singular_uninflected: if x.endswith(w): return word for x in singular_uncountable: if x.endswith(w): return word for x in singular_ie: if w.endswith(x + "s"): return w[:-1] for x in singular_irregular: if w.endswith(x): return re.sub('(?i)' + x + '$', singular_irregular[x], word) for suffix, inflection in singular_rules: m = suffix.search(word) g = m and m.groups() or [] if m: for k in range(len(g)): if g[k] is None: inflection = inflection.replace('\\' + str(k + 1), '') return suffix.sub(inflection, word) return word
[ "def", "singularize", "(", "word", ",", "pos", "=", "NOUN", ",", "custom", "=", "None", ")", ":", "if", "custom", "and", "word", "in", "custom", ":", "return", "custom", "[", "word", "]", "# Recurse compound words (e.g. mothers-in-law).", "if", "\"-\"", "in"...
Returns the singular of a given word.
[ "Returns", "the", "singular", "of", "a", "given", "word", "." ]
4d536cb90e2cc4829c1c05f2c74d3e22901a1399
https://github.com/briancappello/flask-unchained/blob/4d536cb90e2cc4829c1c05f2c74d3e22901a1399/flask_unchained/clips_pattern.py#L539-L573
25,808
briancappello/flask-unchained
flask_unchained/app_factory.py
AppFactory.create_basic_app
def create_basic_app(cls, bundles=None, _config_overrides=None): """ Creates a "fake" app for use while developing """ bundles = bundles or [] name = bundles[-1].module_name if bundles else 'basic_app' app = FlaskUnchained(name, template_folder=os.path.join( os.path.dirname(__file__), 'templates')) for bundle in bundles: bundle.before_init_app(app) unchained.init_app(app, DEV, bundles, _config_overrides=_config_overrides) for bundle in bundles: bundle.after_init_app(app) return app
python
def create_basic_app(cls, bundles=None, _config_overrides=None): bundles = bundles or [] name = bundles[-1].module_name if bundles else 'basic_app' app = FlaskUnchained(name, template_folder=os.path.join( os.path.dirname(__file__), 'templates')) for bundle in bundles: bundle.before_init_app(app) unchained.init_app(app, DEV, bundles, _config_overrides=_config_overrides) for bundle in bundles: bundle.after_init_app(app) return app
[ "def", "create_basic_app", "(", "cls", ",", "bundles", "=", "None", ",", "_config_overrides", "=", "None", ")", ":", "bundles", "=", "bundles", "or", "[", "]", "name", "=", "bundles", "[", "-", "1", "]", ".", "module_name", "if", "bundles", "else", "'b...
Creates a "fake" app for use while developing
[ "Creates", "a", "fake", "app", "for", "use", "while", "developing" ]
4d536cb90e2cc4829c1c05f2c74d3e22901a1399
https://github.com/briancappello/flask-unchained/blob/4d536cb90e2cc4829c1c05f2c74d3e22901a1399/flask_unchained/app_factory.py#L83-L100
25,809
briancappello/flask-unchained
flask_unchained/bundles/security/commands/roles.py
list_roles
def list_roles(): """ List roles. """ roles = role_manager.all() if roles: print_table(['ID', 'Name'], [(role.id, role.name) for role in roles]) else: click.echo('No roles found.')
python
def list_roles(): roles = role_manager.all() if roles: print_table(['ID', 'Name'], [(role.id, role.name) for role in roles]) else: click.echo('No roles found.')
[ "def", "list_roles", "(", ")", ":", "roles", "=", "role_manager", ".", "all", "(", ")", "if", "roles", ":", "print_table", "(", "[", "'ID'", ",", "'Name'", "]", ",", "[", "(", "role", ".", "id", ",", "role", ".", "name", ")", "for", "role", "in",...
List roles.
[ "List", "roles", "." ]
4d536cb90e2cc4829c1c05f2c74d3e22901a1399
https://github.com/briancappello/flask-unchained/blob/4d536cb90e2cc4829c1c05f2c74d3e22901a1399/flask_unchained/bundles/security/commands/roles.py#L19-L27
25,810
briancappello/flask-unchained
flask_unchained/bundles/security/commands/roles.py
create_role
def create_role(name): """ Create a new role. """ role = role_manager.create(name=name) if click.confirm(f'Are you sure you want to create {role!r}?'): role_manager.save(role, commit=True) click.echo(f'Successfully created {role!r}') else: click.echo('Cancelled.')
python
def create_role(name): role = role_manager.create(name=name) if click.confirm(f'Are you sure you want to create {role!r}?'): role_manager.save(role, commit=True) click.echo(f'Successfully created {role!r}') else: click.echo('Cancelled.')
[ "def", "create_role", "(", "name", ")", ":", "role", "=", "role_manager", ".", "create", "(", "name", "=", "name", ")", "if", "click", ".", "confirm", "(", "f'Are you sure you want to create {role!r}?'", ")", ":", "role_manager", ".", "save", "(", "role", ",...
Create a new role.
[ "Create", "a", "new", "role", "." ]
4d536cb90e2cc4829c1c05f2c74d3e22901a1399
https://github.com/briancappello/flask-unchained/blob/4d536cb90e2cc4829c1c05f2c74d3e22901a1399/flask_unchained/bundles/security/commands/roles.py#L33-L42
25,811
briancappello/flask-unchained
flask_unchained/bundles/security/commands/roles.py
delete_role
def delete_role(query): """ Delete a role. """ role = _query_to_role(query) if click.confirm(f'Are you sure you want to delete {role!r}?'): role_manager.delete(role, commit=True) click.echo(f'Successfully deleted {role!r}') else: click.echo('Cancelled.')
python
def delete_role(query): role = _query_to_role(query) if click.confirm(f'Are you sure you want to delete {role!r}?'): role_manager.delete(role, commit=True) click.echo(f'Successfully deleted {role!r}') else: click.echo('Cancelled.')
[ "def", "delete_role", "(", "query", ")", ":", "role", "=", "_query_to_role", "(", "query", ")", "if", "click", ".", "confirm", "(", "f'Are you sure you want to delete {role!r}?'", ")", ":", "role_manager", ".", "delete", "(", "role", ",", "commit", "=", "True"...
Delete a role.
[ "Delete", "a", "role", "." ]
4d536cb90e2cc4829c1c05f2c74d3e22901a1399
https://github.com/briancappello/flask-unchained/blob/4d536cb90e2cc4829c1c05f2c74d3e22901a1399/flask_unchained/bundles/security/commands/roles.py#L48-L57
25,812
briancappello/flask-unchained
flask_unchained/bundles/sqlalchemy/sqla/events.py
slugify
def slugify(field_name, slug_field_name=None, mutable=False): """Class decorator to specify a field to slugify. Slugs are immutable by default unless mutable=True is passed. Usage:: @slugify('title') def Post(Model): title = Column(String(100)) slug = Column(String(100)) # pass a second argument to specify the slug attribute field: @slugify('title', 'title_slug') def Post(Model) title = Column(String(100)) title_slug = Column(String(100)) # optionally set mutable to True for a slug that changes every time # the slugified field changes: @slugify('title', mutable=True) def Post(Model): title = Column(String(100)) slug = Column(String(100)) """ slug_field_name = slug_field_name or 'slug' def _set_slug(target, value, old_value, _, mutable=False): existing_slug = getattr(target, slug_field_name) if existing_slug and not mutable: return if value and (not existing_slug or value != old_value): setattr(target, slug_field_name, _slugify(value)) def wrapper(cls): event.listen(getattr(cls, field_name), 'set', partial(_set_slug, mutable=mutable)) return cls return wrapper
python
def slugify(field_name, slug_field_name=None, mutable=False): slug_field_name = slug_field_name or 'slug' def _set_slug(target, value, old_value, _, mutable=False): existing_slug = getattr(target, slug_field_name) if existing_slug and not mutable: return if value and (not existing_slug or value != old_value): setattr(target, slug_field_name, _slugify(value)) def wrapper(cls): event.listen(getattr(cls, field_name), 'set', partial(_set_slug, mutable=mutable)) return cls return wrapper
[ "def", "slugify", "(", "field_name", ",", "slug_field_name", "=", "None", ",", "mutable", "=", "False", ")", ":", "slug_field_name", "=", "slug_field_name", "or", "'slug'", "def", "_set_slug", "(", "target", ",", "value", ",", "old_value", ",", "_", ",", "...
Class decorator to specify a field to slugify. Slugs are immutable by default unless mutable=True is passed. Usage:: @slugify('title') def Post(Model): title = Column(String(100)) slug = Column(String(100)) # pass a second argument to specify the slug attribute field: @slugify('title', 'title_slug') def Post(Model) title = Column(String(100)) title_slug = Column(String(100)) # optionally set mutable to True for a slug that changes every time # the slugified field changes: @slugify('title', mutable=True) def Post(Model): title = Column(String(100)) slug = Column(String(100))
[ "Class", "decorator", "to", "specify", "a", "field", "to", "slugify", ".", "Slugs", "are", "immutable", "by", "default", "unless", "mutable", "=", "True", "is", "passed", "." ]
4d536cb90e2cc4829c1c05f2c74d3e22901a1399
https://github.com/briancappello/flask-unchained/blob/4d536cb90e2cc4829c1c05f2c74d3e22901a1399/flask_unchained/bundles/sqlalchemy/sqla/events.py#L87-L124
25,813
briancappello/flask-unchained
flask_unchained/bundles/mail/utils.py
get_message_plain_text
def get_message_plain_text(msg: Message): """ Converts an HTML message to plain text. :param msg: A :class:`~flask_mail.Message` :return: The plain text message. """ if msg.body: return msg.body if BeautifulSoup is None or not msg.html: return msg.html plain_text = '\n'.join(line.strip() for line in BeautifulSoup(msg.html, 'lxml').text.splitlines()) return re.sub(r'\n\n+', '\n\n', plain_text).strip()
python
def get_message_plain_text(msg: Message): if msg.body: return msg.body if BeautifulSoup is None or not msg.html: return msg.html plain_text = '\n'.join(line.strip() for line in BeautifulSoup(msg.html, 'lxml').text.splitlines()) return re.sub(r'\n\n+', '\n\n', plain_text).strip()
[ "def", "get_message_plain_text", "(", "msg", ":", "Message", ")", ":", "if", "msg", ".", "body", ":", "return", "msg", ".", "body", "if", "BeautifulSoup", "is", "None", "or", "not", "msg", ".", "html", ":", "return", "msg", ".", "html", "plain_text", "...
Converts an HTML message to plain text. :param msg: A :class:`~flask_mail.Message` :return: The plain text message.
[ "Converts", "an", "HTML", "message", "to", "plain", "text", "." ]
4d536cb90e2cc4829c1c05f2c74d3e22901a1399
https://github.com/briancappello/flask-unchained/blob/4d536cb90e2cc4829c1c05f2c74d3e22901a1399/flask_unchained/bundles/mail/utils.py#L31-L46
25,814
briancappello/flask-unchained
flask_unchained/bundles/mail/utils.py
_send_mail
def _send_mail(subject_or_message: Optional[Union[str, Message]] = None, to: Optional[Union[str, List[str]]] = None, template: Optional[str] = None, **kwargs): """ The default function used for sending emails. :param subject_or_message: A subject string, or for backwards compatibility with stock Flask-Mail, a :class:`~flask_mail.Message` instance :param to: An email address, or a list of email addresses :param template: Which template to render. :param kwargs: Extra kwargs to pass on to :class:`~flask_mail.Message` """ subject_or_message = subject_or_message or kwargs.pop('subject') to = to or kwargs.pop('recipients', []) msg = make_message(subject_or_message, to, template, **kwargs) with mail.connect() as connection: connection.send(msg)
python
def _send_mail(subject_or_message: Optional[Union[str, Message]] = None, to: Optional[Union[str, List[str]]] = None, template: Optional[str] = None, **kwargs): subject_or_message = subject_or_message or kwargs.pop('subject') to = to or kwargs.pop('recipients', []) msg = make_message(subject_or_message, to, template, **kwargs) with mail.connect() as connection: connection.send(msg)
[ "def", "_send_mail", "(", "subject_or_message", ":", "Optional", "[", "Union", "[", "str", ",", "Message", "]", "]", "=", "None", ",", "to", ":", "Optional", "[", "Union", "[", "str", ",", "List", "[", "str", "]", "]", "]", "=", "None", ",", "templ...
The default function used for sending emails. :param subject_or_message: A subject string, or for backwards compatibility with stock Flask-Mail, a :class:`~flask_mail.Message` instance :param to: An email address, or a list of email addresses :param template: Which template to render. :param kwargs: Extra kwargs to pass on to :class:`~flask_mail.Message`
[ "The", "default", "function", "used", "for", "sending", "emails", "." ]
4d536cb90e2cc4829c1c05f2c74d3e22901a1399
https://github.com/briancappello/flask-unchained/blob/4d536cb90e2cc4829c1c05f2c74d3e22901a1399/flask_unchained/bundles/mail/utils.py#L80-L97
25,815
briancappello/flask-unchained
flask_unchained/bundles/babel/commands.py
extract
def extract(domain): """ Extract newly added translations keys from source code. """ translations_dir = _get_translations_dir() domain = _get_translations_domain(domain) babel_cfg = _get_babel_cfg() pot = os.path.join(translations_dir, f'{domain}.pot') return _run(f'extract -F {babel_cfg} -o {pot} .')
python
def extract(domain): translations_dir = _get_translations_dir() domain = _get_translations_domain(domain) babel_cfg = _get_babel_cfg() pot = os.path.join(translations_dir, f'{domain}.pot') return _run(f'extract -F {babel_cfg} -o {pot} .')
[ "def", "extract", "(", "domain", ")", ":", "translations_dir", "=", "_get_translations_dir", "(", ")", "domain", "=", "_get_translations_domain", "(", "domain", ")", "babel_cfg", "=", "_get_babel_cfg", "(", ")", "pot", "=", "os", ".", "path", ".", "join", "(...
Extract newly added translations keys from source code.
[ "Extract", "newly", "added", "translations", "keys", "from", "source", "code", "." ]
4d536cb90e2cc4829c1c05f2c74d3e22901a1399
https://github.com/briancappello/flask-unchained/blob/4d536cb90e2cc4829c1c05f2c74d3e22901a1399/flask_unchained/bundles/babel/commands.py#L22-L30
25,816
briancappello/flask-unchained
flask_unchained/bundles/babel/commands.py
init
def init(lang, domain): """ Initialize translations for a language code. """ translations_dir = _get_translations_dir() domain = _get_translations_domain(domain) pot = os.path.join(translations_dir, f'{domain}.pot') return _run(f'init -i {pot} -d {translations_dir} -l {lang} --domain={domain}')
python
def init(lang, domain): translations_dir = _get_translations_dir() domain = _get_translations_domain(domain) pot = os.path.join(translations_dir, f'{domain}.pot') return _run(f'init -i {pot} -d {translations_dir} -l {lang} --domain={domain}')
[ "def", "init", "(", "lang", ",", "domain", ")", ":", "translations_dir", "=", "_get_translations_dir", "(", ")", "domain", "=", "_get_translations_domain", "(", "domain", ")", "pot", "=", "os", ".", "path", ".", "join", "(", "translations_dir", ",", "f'{doma...
Initialize translations for a language code.
[ "Initialize", "translations", "for", "a", "language", "code", "." ]
4d536cb90e2cc4829c1c05f2c74d3e22901a1399
https://github.com/briancappello/flask-unchained/blob/4d536cb90e2cc4829c1c05f2c74d3e22901a1399/flask_unchained/bundles/babel/commands.py#L36-L43
25,817
briancappello/flask-unchained
flask_unchained/bundles/babel/commands.py
update
def update(domain): """ Update language-specific translations files with new keys discovered by ``flask babel extract``. """ translations_dir = _get_translations_dir() domain = _get_translations_domain(domain) pot = os.path.join(translations_dir, f'{domain}.pot') return _run(f'update -i {pot} -d {translations_dir} --domain={domain}')
python
def update(domain): translations_dir = _get_translations_dir() domain = _get_translations_domain(domain) pot = os.path.join(translations_dir, f'{domain}.pot') return _run(f'update -i {pot} -d {translations_dir} --domain={domain}')
[ "def", "update", "(", "domain", ")", ":", "translations_dir", "=", "_get_translations_dir", "(", ")", "domain", "=", "_get_translations_domain", "(", "domain", ")", "pot", "=", "os", ".", "path", ".", "join", "(", "translations_dir", ",", "f'{domain}.pot'", ")...
Update language-specific translations files with new keys discovered by ``flask babel extract``.
[ "Update", "language", "-", "specific", "translations", "files", "with", "new", "keys", "discovered", "by", "flask", "babel", "extract", "." ]
4d536cb90e2cc4829c1c05f2c74d3e22901a1399
https://github.com/briancappello/flask-unchained/blob/4d536cb90e2cc4829c1c05f2c74d3e22901a1399/flask_unchained/bundles/babel/commands.py#L59-L67
25,818
briancappello/flask-unchained
flask_unchained/bundles/sqlalchemy/meta_options.py
RelationshipsMetaOption.get_value
def get_value(self, meta, base_model_meta, mcs_args: McsArgs): """overridden to merge with inherited value""" if mcs_args.Meta.abstract: return None value = getattr(base_model_meta, self.name, {}) or {} value.update(getattr(meta, self.name, {})) return value
python
def get_value(self, meta, base_model_meta, mcs_args: McsArgs): if mcs_args.Meta.abstract: return None value = getattr(base_model_meta, self.name, {}) or {} value.update(getattr(meta, self.name, {})) return value
[ "def", "get_value", "(", "self", ",", "meta", ",", "base_model_meta", ",", "mcs_args", ":", "McsArgs", ")", ":", "if", "mcs_args", ".", "Meta", ".", "abstract", ":", "return", "None", "value", "=", "getattr", "(", "base_model_meta", ",", "self", ".", "na...
overridden to merge with inherited value
[ "overridden", "to", "merge", "with", "inherited", "value" ]
4d536cb90e2cc4829c1c05f2c74d3e22901a1399
https://github.com/briancappello/flask-unchained/blob/4d536cb90e2cc4829c1c05f2c74d3e22901a1399/flask_unchained/bundles/sqlalchemy/meta_options.py#L34-L40
25,819
briancappello/flask-unchained
flask_unchained/bundles/controller/controller.py
Controller.flash
def flash(self, msg: str, category: Optional[str] = None): """ Convenience method for flashing messages. :param msg: The message to flash. :param category: The category of the message. """ if not request.is_json and app.config.FLASH_MESSAGES: flash(msg, category)
python
def flash(self, msg: str, category: Optional[str] = None): if not request.is_json and app.config.FLASH_MESSAGES: flash(msg, category)
[ "def", "flash", "(", "self", ",", "msg", ":", "str", ",", "category", ":", "Optional", "[", "str", "]", "=", "None", ")", ":", "if", "not", "request", ".", "is_json", "and", "app", ".", "config", ".", "FLASH_MESSAGES", ":", "flash", "(", "msg", ","...
Convenience method for flashing messages. :param msg: The message to flash. :param category: The category of the message.
[ "Convenience", "method", "for", "flashing", "messages", "." ]
4d536cb90e2cc4829c1c05f2c74d3e22901a1399
https://github.com/briancappello/flask-unchained/blob/4d536cb90e2cc4829c1c05f2c74d3e22901a1399/flask_unchained/bundles/controller/controller.py#L190-L198
25,820
briancappello/flask-unchained
flask_unchained/bundles/controller/controller.py
Controller.render
def render(self, template_name: str, **ctx): """ Convenience method for rendering a template. :param template_name: The template's name. Can either be a full path, or a filename in the controller's template folder. :param ctx: Context variables to pass into the template. """ if '.' not in template_name: template_file_extension = (self.Meta.template_file_extension or app.config.TEMPLATE_FILE_EXTENSION) template_name = f'{template_name}{template_file_extension}' if self.Meta.template_folder_name and os.sep not in template_name: template_name = os.path.join(self.Meta.template_folder_name, template_name) return render_template(template_name, **ctx)
python
def render(self, template_name: str, **ctx): if '.' not in template_name: template_file_extension = (self.Meta.template_file_extension or app.config.TEMPLATE_FILE_EXTENSION) template_name = f'{template_name}{template_file_extension}' if self.Meta.template_folder_name and os.sep not in template_name: template_name = os.path.join(self.Meta.template_folder_name, template_name) return render_template(template_name, **ctx)
[ "def", "render", "(", "self", ",", "template_name", ":", "str", ",", "*", "*", "ctx", ")", ":", "if", "'.'", "not", "in", "template_name", ":", "template_file_extension", "=", "(", "self", ".", "Meta", ".", "template_file_extension", "or", "app", ".", "c...
Convenience method for rendering a template. :param template_name: The template's name. Can either be a full path, or a filename in the controller's template folder. :param ctx: Context variables to pass into the template.
[ "Convenience", "method", "for", "rendering", "a", "template", "." ]
4d536cb90e2cc4829c1c05f2c74d3e22901a1399
https://github.com/briancappello/flask-unchained/blob/4d536cb90e2cc4829c1c05f2c74d3e22901a1399/flask_unchained/bundles/controller/controller.py#L200-L215
25,821
briancappello/flask-unchained
flask_unchained/bundles/controller/controller.py
Controller.redirect
def redirect(self, where: Optional[str] = None, default: Optional[str] = None, override: Optional[str] = None, **url_kwargs): """ Convenience method for returning redirect responses. :param where: A URL, endpoint, or config key name to redirect to. :param default: A URL, endpoint, or config key name to redirect to if ``where`` is invalid. :param override: explicitly redirect to a URL, endpoint, or config key name (takes precedence over the ``next`` value in query strings or forms) :param url_kwargs: the variable arguments of the URL rule :param _anchor: if provided this is added as anchor to the URL. :param _external: if set to ``True``, an absolute URL is generated. Server address can be changed via ``SERVER_NAME`` configuration variable which defaults to `localhost`. :param _external_host: if specified, the host of an external server to generate urls for (eg https://example.com or localhost:8888) :param _method: if provided this explicitly specifies an HTTP method. :param _scheme: a string specifying the desired URL scheme. The `_external` parameter must be set to ``True`` or a :exc:`ValueError` is raised. The default behavior uses the same scheme as the current request, or ``PREFERRED_URL_SCHEME`` from the :ref:`app configuration <config>` if no request context is available. As of Werkzeug 0.10, this also can be set to an empty string to build protocol-relative URLs. """ return redirect(where, default, override, _cls=self, **url_kwargs)
python
def redirect(self, where: Optional[str] = None, default: Optional[str] = None, override: Optional[str] = None, **url_kwargs): return redirect(where, default, override, _cls=self, **url_kwargs)
[ "def", "redirect", "(", "self", ",", "where", ":", "Optional", "[", "str", "]", "=", "None", ",", "default", ":", "Optional", "[", "str", "]", "=", "None", ",", "override", ":", "Optional", "[", "str", "]", "=", "None", ",", "*", "*", "url_kwargs",...
Convenience method for returning redirect responses. :param where: A URL, endpoint, or config key name to redirect to. :param default: A URL, endpoint, or config key name to redirect to if ``where`` is invalid. :param override: explicitly redirect to a URL, endpoint, or config key name (takes precedence over the ``next`` value in query strings or forms) :param url_kwargs: the variable arguments of the URL rule :param _anchor: if provided this is added as anchor to the URL. :param _external: if set to ``True``, an absolute URL is generated. Server address can be changed via ``SERVER_NAME`` configuration variable which defaults to `localhost`. :param _external_host: if specified, the host of an external server to generate urls for (eg https://example.com or localhost:8888) :param _method: if provided this explicitly specifies an HTTP method. :param _scheme: a string specifying the desired URL scheme. The `_external` parameter must be set to ``True`` or a :exc:`ValueError` is raised. The default behavior uses the same scheme as the current request, or ``PREFERRED_URL_SCHEME`` from the :ref:`app configuration <config>` if no request context is available. As of Werkzeug 0.10, this also can be set to an empty string to build protocol-relative URLs.
[ "Convenience", "method", "for", "returning", "redirect", "responses", "." ]
4d536cb90e2cc4829c1c05f2c74d3e22901a1399
https://github.com/briancappello/flask-unchained/blob/4d536cb90e2cc4829c1c05f2c74d3e22901a1399/flask_unchained/bundles/controller/controller.py#L217-L248
25,822
briancappello/flask-unchained
flask_unchained/bundles/controller/controller.py
Controller.jsonify
def jsonify(self, data: Any, code: Union[int, Tuple[int, str, str]] = HTTPStatus.OK, headers: Optional[Dict[str, str]] = None, ): """ Convenience method to return json responses. :param data: The python data to jsonify. :param code: The HTTP status code to return. :param headers: Any optional headers. """ return jsonify(data), code, headers or {}
python
def jsonify(self, data: Any, code: Union[int, Tuple[int, str, str]] = HTTPStatus.OK, headers: Optional[Dict[str, str]] = None, ): return jsonify(data), code, headers or {}
[ "def", "jsonify", "(", "self", ",", "data", ":", "Any", ",", "code", ":", "Union", "[", "int", ",", "Tuple", "[", "int", ",", "str", ",", "str", "]", "]", "=", "HTTPStatus", ".", "OK", ",", "headers", ":", "Optional", "[", "Dict", "[", "str", "...
Convenience method to return json responses. :param data: The python data to jsonify. :param code: The HTTP status code to return. :param headers: Any optional headers.
[ "Convenience", "method", "to", "return", "json", "responses", "." ]
4d536cb90e2cc4829c1c05f2c74d3e22901a1399
https://github.com/briancappello/flask-unchained/blob/4d536cb90e2cc4829c1c05f2c74d3e22901a1399/flask_unchained/bundles/controller/controller.py#L250-L262
25,823
briancappello/flask-unchained
flask_unchained/bundles/controller/controller.py
Controller.errors
def errors(self, errors: List[str], code: Union[int, Tuple[int, str, str]] = HTTPStatus.BAD_REQUEST, key: str = 'errors', headers: Optional[Dict[str, str]] = None, ): """ Convenience method to return errors as json. :param errors: The list of errors. :param code: The HTTP status code. :param key: The key to return the errors under. :param headers: Any optional headers. """ return jsonify({key: errors}), code, headers or {}
python
def errors(self, errors: List[str], code: Union[int, Tuple[int, str, str]] = HTTPStatus.BAD_REQUEST, key: str = 'errors', headers: Optional[Dict[str, str]] = None, ): return jsonify({key: errors}), code, headers or {}
[ "def", "errors", "(", "self", ",", "errors", ":", "List", "[", "str", "]", ",", "code", ":", "Union", "[", "int", ",", "Tuple", "[", "int", ",", "str", ",", "str", "]", "]", "=", "HTTPStatus", ".", "BAD_REQUEST", ",", "key", ":", "str", "=", "'...
Convenience method to return errors as json. :param errors: The list of errors. :param code: The HTTP status code. :param key: The key to return the errors under. :param headers: Any optional headers.
[ "Convenience", "method", "to", "return", "errors", "as", "json", "." ]
4d536cb90e2cc4829c1c05f2c74d3e22901a1399
https://github.com/briancappello/flask-unchained/blob/4d536cb90e2cc4829c1c05f2c74d3e22901a1399/flask_unchained/bundles/controller/controller.py#L264-L278
25,824
briancappello/flask-unchained
flask_unchained/bundles/security/commands/users.py
set_password
def set_password(query, password, send_email): """ Set a user's password. """ user = _query_to_user(query) if click.confirm(f'Are you sure you want to change {user!r}\'s password?'): security_service.change_password(user, password, send_email=send_email) user_manager.save(user, commit=True) click.echo(f'Successfully updated password for {user!r}') else: click.echo('Cancelled.')
python
def set_password(query, password, send_email): user = _query_to_user(query) if click.confirm(f'Are you sure you want to change {user!r}\'s password?'): security_service.change_password(user, password, send_email=send_email) user_manager.save(user, commit=True) click.echo(f'Successfully updated password for {user!r}') else: click.echo('Cancelled.')
[ "def", "set_password", "(", "query", ",", "password", ",", "send_email", ")", ":", "user", "=", "_query_to_user", "(", "query", ")", "if", "click", ".", "confirm", "(", "f'Are you sure you want to change {user!r}\\'s password?'", ")", ":", "security_service", ".", ...
Set a user's password.
[ "Set", "a", "user", "s", "password", "." ]
4d536cb90e2cc4829c1c05f2c74d3e22901a1399
https://github.com/briancappello/flask-unchained/blob/4d536cb90e2cc4829c1c05f2c74d3e22901a1399/flask_unchained/bundles/security/commands/users.py#L95-L105
25,825
briancappello/flask-unchained
flask_unchained/bundles/security/commands/users.py
confirm_user
def confirm_user(query): """ Confirm a user account. """ user = _query_to_user(query) if click.confirm(f'Are you sure you want to confirm {user!r}?'): if security_service.confirm_user(user): click.echo(f'Successfully confirmed {user!r} at ' f'{user.confirmed_at.strftime("%Y-%m-%d %H:%M:%S%z")}') user_manager.save(user, commit=True) else: click.echo(f'{user!r} has already been confirmed.') else: click.echo('Cancelled.')
python
def confirm_user(query): user = _query_to_user(query) if click.confirm(f'Are you sure you want to confirm {user!r}?'): if security_service.confirm_user(user): click.echo(f'Successfully confirmed {user!r} at ' f'{user.confirmed_at.strftime("%Y-%m-%d %H:%M:%S%z")}') user_manager.save(user, commit=True) else: click.echo(f'{user!r} has already been confirmed.') else: click.echo('Cancelled.')
[ "def", "confirm_user", "(", "query", ")", ":", "user", "=", "_query_to_user", "(", "query", ")", "if", "click", ".", "confirm", "(", "f'Are you sure you want to confirm {user!r}?'", ")", ":", "if", "security_service", ".", "confirm_user", "(", "user", ")", ":", ...
Confirm a user account.
[ "Confirm", "a", "user", "account", "." ]
4d536cb90e2cc4829c1c05f2c74d3e22901a1399
https://github.com/briancappello/flask-unchained/blob/4d536cb90e2cc4829c1c05f2c74d3e22901a1399/flask_unchained/bundles/security/commands/users.py#L112-L125
25,826
briancappello/flask-unchained
flask_unchained/bundles/security/commands/users.py
add_role_to_user
def add_role_to_user(user, role): """ Add a role to a user. """ user = _query_to_user(user) role = _query_to_role(role) if click.confirm(f'Are you sure you want to add {role!r} to {user!r}?'): user.roles.append(role) user_manager.save(user, commit=True) click.echo(f'Successfully added {role!r} to {user!r}') else: click.echo('Cancelled.')
python
def add_role_to_user(user, role): user = _query_to_user(user) role = _query_to_role(role) if click.confirm(f'Are you sure you want to add {role!r} to {user!r}?'): user.roles.append(role) user_manager.save(user, commit=True) click.echo(f'Successfully added {role!r} to {user!r}') else: click.echo('Cancelled.')
[ "def", "add_role_to_user", "(", "user", ",", "role", ")", ":", "user", "=", "_query_to_user", "(", "user", ")", "role", "=", "_query_to_role", "(", "role", ")", "if", "click", ".", "confirm", "(", "f'Are you sure you want to add {role!r} to {user!r}?'", ")", ":"...
Add a role to a user.
[ "Add", "a", "role", "to", "a", "user", "." ]
4d536cb90e2cc4829c1c05f2c74d3e22901a1399
https://github.com/briancappello/flask-unchained/blob/4d536cb90e2cc4829c1c05f2c74d3e22901a1399/flask_unchained/bundles/security/commands/users.py#L168-L179
25,827
briancappello/flask-unchained
flask_unchained/bundles/security/commands/users.py
remove_role_from_user
def remove_role_from_user(user, role): """ Remove a role from a user. """ user = _query_to_user(user) role = _query_to_role(role) if click.confirm(f'Are you sure you want to remove {role!r} from {user!r}?'): user.roles.remove(role) user_manager.save(user, commit=True) click.echo(f'Successfully removed {role!r} from {user!r}') else: click.echo('Cancelled.')
python
def remove_role_from_user(user, role): user = _query_to_user(user) role = _query_to_role(role) if click.confirm(f'Are you sure you want to remove {role!r} from {user!r}?'): user.roles.remove(role) user_manager.save(user, commit=True) click.echo(f'Successfully removed {role!r} from {user!r}') else: click.echo('Cancelled.')
[ "def", "remove_role_from_user", "(", "user", ",", "role", ")", ":", "user", "=", "_query_to_user", "(", "user", ")", "role", "=", "_query_to_role", "(", "role", ")", "if", "click", ".", "confirm", "(", "f'Are you sure you want to remove {role!r} from {user!r}?'", ...
Remove a role from a user.
[ "Remove", "a", "role", "from", "a", "user", "." ]
4d536cb90e2cc4829c1c05f2c74d3e22901a1399
https://github.com/briancappello/flask-unchained/blob/4d536cb90e2cc4829c1c05f2c74d3e22901a1399/flask_unchained/bundles/security/commands/users.py#L188-L199
25,828
briancappello/flask-unchained
flask_unchained/bundles/security/decorators/anonymous_user_required.py
anonymous_user_required
def anonymous_user_required(*decorator_args, msg=None, category=None, redirect_url=None): """ Decorator requiring that there is no user currently logged in. Aborts with ``HTTP 403: Forbidden`` if there is an authenticated user. """ def wrapper(fn): @wraps(fn) def decorated(*args, **kwargs): if current_user.is_authenticated: if request.is_json: abort(HTTPStatus.FORBIDDEN) else: if msg: flash(msg, category) return redirect('SECURITY_POST_LOGIN_REDIRECT_ENDPOINT', override=redirect_url) return fn(*args, **kwargs) return decorated if decorator_args and callable(decorator_args[0]): return wrapper(decorator_args[0]) return wrapper
python
def anonymous_user_required(*decorator_args, msg=None, category=None, redirect_url=None): def wrapper(fn): @wraps(fn) def decorated(*args, **kwargs): if current_user.is_authenticated: if request.is_json: abort(HTTPStatus.FORBIDDEN) else: if msg: flash(msg, category) return redirect('SECURITY_POST_LOGIN_REDIRECT_ENDPOINT', override=redirect_url) return fn(*args, **kwargs) return decorated if decorator_args and callable(decorator_args[0]): return wrapper(decorator_args[0]) return wrapper
[ "def", "anonymous_user_required", "(", "*", "decorator_args", ",", "msg", "=", "None", ",", "category", "=", "None", ",", "redirect_url", "=", "None", ")", ":", "def", "wrapper", "(", "fn", ")", ":", "@", "wraps", "(", "fn", ")", "def", "decorated", "(...
Decorator requiring that there is no user currently logged in. Aborts with ``HTTP 403: Forbidden`` if there is an authenticated user.
[ "Decorator", "requiring", "that", "there", "is", "no", "user", "currently", "logged", "in", "." ]
4d536cb90e2cc4829c1c05f2c74d3e22901a1399
https://github.com/briancappello/flask-unchained/blob/4d536cb90e2cc4829c1c05f2c74d3e22901a1399/flask_unchained/bundles/security/decorators/anonymous_user_required.py#L9-L31
25,829
briancappello/flask-unchained
flask_unchained/bundles/security/services/security_service.py
SecurityService.login_user
def login_user(self, user: User, remember: Optional[bool] = None, duration: Optional[timedelta] = None, force: bool = False, fresh: bool = True, ) -> bool: """ Logs a user in. You should pass the actual user object to this. If the user's `active` property is ``False``, they will not be logged in unless `force` is ``True``. This will return ``True`` if the log in attempt succeeds, and ``False`` if it fails (i.e. because the user is inactive). :param user: The user object to log in. :type user: object :param remember: Whether to remember the user after their session expires. Defaults to ``False``. :type remember: bool :param duration: The amount of time before the remember cookie expires. If ``None`` the value set in the settings is used. Defaults to ``None``. :type duration: :class:`datetime.timedelta` :param force: If the user is inactive, setting this to ``True`` will log them in regardless. Defaults to ``False``. :type force: bool :param fresh: setting this to ``False`` will log in the user with a session marked as not "fresh". Defaults to ``True``. :type fresh: bool """ if not force: if not user.active: raise AuthenticationError( _('flask_unchained.bundles.security:error.disabled_account')) if (not user.confirmed_at and self.security.confirmable and not self.security.login_without_confirmation): raise AuthenticationError( _('flask_unchained.bundles.security:error.confirmation_required')) if not user.password: raise AuthenticationError( _('flask_unchained.bundles.security:error.password_not_set')) session['user_id'] = getattr(user, user.Meta.pk) session['_fresh'] = fresh session['_id'] = app.login_manager._session_identifier_generator() if remember is None: remember = app.config.SECURITY_DEFAULT_REMEMBER_ME if remember: session['remember'] = 'set' if duration is not None: try: session['remember_seconds'] = duration.total_seconds() except AttributeError: raise Exception('duration must be a datetime.timedelta, ' 'instead got: {0}'.format(duration)) _request_ctx_stack.top.user = user user_logged_in.send(app._get_current_object(), user=user) identity_changed.send(app._get_current_object(), identity=Identity(user.id)) return True
python
def login_user(self, user: User, remember: Optional[bool] = None, duration: Optional[timedelta] = None, force: bool = False, fresh: bool = True, ) -> bool: if not force: if not user.active: raise AuthenticationError( _('flask_unchained.bundles.security:error.disabled_account')) if (not user.confirmed_at and self.security.confirmable and not self.security.login_without_confirmation): raise AuthenticationError( _('flask_unchained.bundles.security:error.confirmation_required')) if not user.password: raise AuthenticationError( _('flask_unchained.bundles.security:error.password_not_set')) session['user_id'] = getattr(user, user.Meta.pk) session['_fresh'] = fresh session['_id'] = app.login_manager._session_identifier_generator() if remember is None: remember = app.config.SECURITY_DEFAULT_REMEMBER_ME if remember: session['remember'] = 'set' if duration is not None: try: session['remember_seconds'] = duration.total_seconds() except AttributeError: raise Exception('duration must be a datetime.timedelta, ' 'instead got: {0}'.format(duration)) _request_ctx_stack.top.user = user user_logged_in.send(app._get_current_object(), user=user) identity_changed.send(app._get_current_object(), identity=Identity(user.id)) return True
[ "def", "login_user", "(", "self", ",", "user", ":", "User", ",", "remember", ":", "Optional", "[", "bool", "]", "=", "None", ",", "duration", ":", "Optional", "[", "timedelta", "]", "=", "None", ",", "force", ":", "bool", "=", "False", ",", "fresh", ...
Logs a user in. You should pass the actual user object to this. If the user's `active` property is ``False``, they will not be logged in unless `force` is ``True``. This will return ``True`` if the log in attempt succeeds, and ``False`` if it fails (i.e. because the user is inactive). :param user: The user object to log in. :type user: object :param remember: Whether to remember the user after their session expires. Defaults to ``False``. :type remember: bool :param duration: The amount of time before the remember cookie expires. If ``None`` the value set in the settings is used. Defaults to ``None``. :type duration: :class:`datetime.timedelta` :param force: If the user is inactive, setting this to ``True`` will log them in regardless. Defaults to ``False``. :type force: bool :param fresh: setting this to ``False`` will log in the user with a session marked as not "fresh". Defaults to ``True``. :type fresh: bool
[ "Logs", "a", "user", "in", ".", "You", "should", "pass", "the", "actual", "user", "object", "to", "this", ".", "If", "the", "user", "s", "active", "property", "is", "False", "they", "will", "not", "be", "logged", "in", "unless", "force", "is", "True", ...
4d536cb90e2cc4829c1c05f2c74d3e22901a1399
https://github.com/briancappello/flask-unchained/blob/4d536cb90e2cc4829c1c05f2c74d3e22901a1399/flask_unchained/bundles/security/services/security_service.py#L42-L106
25,830
briancappello/flask-unchained
flask_unchained/bundles/security/services/security_service.py
SecurityService.register_user
def register_user(self, user, allow_login=None, send_email=None, _force_login_without_confirmation=False): """ Service method to register a user. Sends signal `user_registered`. Returns True if the user has been logged in, False otherwise. """ should_login_user = (not self.security.confirmable or self.security.login_without_confirmation or _force_login_without_confirmation) should_login_user = (should_login_user if allow_login is None else allow_login and should_login_user) if should_login_user: user.active = True # confirmation token depends on having user.id set, which requires # the user be committed to the database self.user_manager.save(user, commit=True) confirmation_link, token = None, None if self.security.confirmable and not _force_login_without_confirmation: token = self.security_utils_service.generate_confirmation_token(user) confirmation_link = url_for('security_controller.confirm_email', token=token, _external=True) user_registered.send(app._get_current_object(), user=user, confirm_token=token) if (send_email or ( send_email is None and app.config.SECURITY_SEND_REGISTER_EMAIL)): self.send_mail(_('flask_unchained.bundles.security:email_subject.register'), to=user.email, template='security/email/welcome.html', user=user, confirmation_link=confirmation_link) if should_login_user: return self.login_user(user, force=_force_login_without_confirmation) return False
python
def register_user(self, user, allow_login=None, send_email=None, _force_login_without_confirmation=False): should_login_user = (not self.security.confirmable or self.security.login_without_confirmation or _force_login_without_confirmation) should_login_user = (should_login_user if allow_login is None else allow_login and should_login_user) if should_login_user: user.active = True # confirmation token depends on having user.id set, which requires # the user be committed to the database self.user_manager.save(user, commit=True) confirmation_link, token = None, None if self.security.confirmable and not _force_login_without_confirmation: token = self.security_utils_service.generate_confirmation_token(user) confirmation_link = url_for('security_controller.confirm_email', token=token, _external=True) user_registered.send(app._get_current_object(), user=user, confirm_token=token) if (send_email or ( send_email is None and app.config.SECURITY_SEND_REGISTER_EMAIL)): self.send_mail(_('flask_unchained.bundles.security:email_subject.register'), to=user.email, template='security/email/welcome.html', user=user, confirmation_link=confirmation_link) if should_login_user: return self.login_user(user, force=_force_login_without_confirmation) return False
[ "def", "register_user", "(", "self", ",", "user", ",", "allow_login", "=", "None", ",", "send_email", "=", "None", ",", "_force_login_without_confirmation", "=", "False", ")", ":", "should_login_user", "=", "(", "not", "self", ".", "security", ".", "confirmabl...
Service method to register a user. Sends signal `user_registered`. Returns True if the user has been logged in, False otherwise.
[ "Service", "method", "to", "register", "a", "user", "." ]
4d536cb90e2cc4829c1c05f2c74d3e22901a1399
https://github.com/briancappello/flask-unchained/blob/4d536cb90e2cc4829c1c05f2c74d3e22901a1399/flask_unchained/bundles/security/services/security_service.py#L122-L163
25,831
briancappello/flask-unchained
flask_unchained/bundles/security/services/security_service.py
SecurityService.change_password
def change_password(self, user, password, send_email=None): """ Service method to change a user's password. Sends signal `password_changed`. :param user: The :class:`User`'s password to change. :param password: The new password. :param send_email: Whether or not to override the config option ``SECURITY_SEND_PASSWORD_CHANGED_EMAIL`` and force either sending or not sending an email. """ user.password = password self.user_manager.save(user) if send_email or (app.config.SECURITY_SEND_PASSWORD_CHANGED_EMAIL and send_email is None): self.send_mail( _('flask_unchained.bundles.security:email_subject.password_changed_notice'), to=user.email, template='security/email/password_changed_notice.html', user=user) password_changed.send(app._get_current_object(), user=user)
python
def change_password(self, user, password, send_email=None): user.password = password self.user_manager.save(user) if send_email or (app.config.SECURITY_SEND_PASSWORD_CHANGED_EMAIL and send_email is None): self.send_mail( _('flask_unchained.bundles.security:email_subject.password_changed_notice'), to=user.email, template='security/email/password_changed_notice.html', user=user) password_changed.send(app._get_current_object(), user=user)
[ "def", "change_password", "(", "self", ",", "user", ",", "password", ",", "send_email", "=", "None", ")", ":", "user", ".", "password", "=", "password", "self", ".", "user_manager", ".", "save", "(", "user", ")", "if", "send_email", "or", "(", "app", "...
Service method to change a user's password. Sends signal `password_changed`. :param user: The :class:`User`'s password to change. :param password: The new password. :param send_email: Whether or not to override the config option ``SECURITY_SEND_PASSWORD_CHANGED_EMAIL`` and force either sending or not sending an email.
[ "Service", "method", "to", "change", "a", "user", "s", "password", "." ]
4d536cb90e2cc4829c1c05f2c74d3e22901a1399
https://github.com/briancappello/flask-unchained/blob/4d536cb90e2cc4829c1c05f2c74d3e22901a1399/flask_unchained/bundles/security/services/security_service.py#L165-L186
25,832
briancappello/flask-unchained
flask_unchained/bundles/security/services/security_service.py
SecurityService.confirm_user
def confirm_user(self, user): """ Confirms the specified user. Returns False if the user has already been confirmed, True otherwise. :param user: The user to confirm. """ if user.confirmed_at is not None: return False user.confirmed_at = self.security.datetime_factory() user.active = True self.user_manager.save(user) user_confirmed.send(app._get_current_object(), user=user) return True
python
def confirm_user(self, user): if user.confirmed_at is not None: return False user.confirmed_at = self.security.datetime_factory() user.active = True self.user_manager.save(user) user_confirmed.send(app._get_current_object(), user=user) return True
[ "def", "confirm_user", "(", "self", ",", "user", ")", ":", "if", "user", ".", "confirmed_at", "is", "not", "None", ":", "return", "False", "user", ".", "confirmed_at", "=", "self", ".", "security", ".", "datetime_factory", "(", ")", "user", ".", "active"...
Confirms the specified user. Returns False if the user has already been confirmed, True otherwise. :param user: The user to confirm.
[ "Confirms", "the", "specified", "user", ".", "Returns", "False", "if", "the", "user", "has", "already", "been", "confirmed", "True", "otherwise", "." ]
4d536cb90e2cc4829c1c05f2c74d3e22901a1399
https://github.com/briancappello/flask-unchained/blob/4d536cb90e2cc4829c1c05f2c74d3e22901a1399/flask_unchained/bundles/security/services/security_service.py#L249-L263
25,833
briancappello/flask-unchained
flask_unchained/bundles/security/services/security_service.py
SecurityService.send_mail
def send_mail(self, subject, to, template, **template_ctx): """ Utility method to send mail with the `mail` template context. """ if not self.mail: from warnings import warn warn('Attempting to send mail without the mail bundle installed! ' 'Please install it, or fix your configuration.') return self.mail.send(subject, to, template, **dict( **self.security.run_ctx_processor('mail'), **template_ctx))
python
def send_mail(self, subject, to, template, **template_ctx): if not self.mail: from warnings import warn warn('Attempting to send mail without the mail bundle installed! ' 'Please install it, or fix your configuration.') return self.mail.send(subject, to, template, **dict( **self.security.run_ctx_processor('mail'), **template_ctx))
[ "def", "send_mail", "(", "self", ",", "subject", ",", "to", ",", "template", ",", "*", "*", "template_ctx", ")", ":", "if", "not", "self", ".", "mail", ":", "from", "warnings", "import", "warn", "warn", "(", "'Attempting to send mail without the mail bundle in...
Utility method to send mail with the `mail` template context.
[ "Utility", "method", "to", "send", "mail", "with", "the", "mail", "template", "context", "." ]
4d536cb90e2cc4829c1c05f2c74d3e22901a1399
https://github.com/briancappello/flask-unchained/blob/4d536cb90e2cc4829c1c05f2c74d3e22901a1399/flask_unchained/bundles/security/services/security_service.py#L265-L277
25,834
briancappello/flask-unchained
flask_unchained/bundles/api/model_serializer.py
_ModelSerializerMetaclass.get_declared_fields
def get_declared_fields(mcs, klass, cls_fields, inherited_fields, dict_cls): """ Updates declared fields with fields converted from the SQLAlchemy model passed as the `model` class Meta option. """ opts = klass.opts converter = opts.model_converter(schema_cls=klass) base_fields = _BaseModelSerializerMetaclass.get_declared_fields( klass, cls_fields, inherited_fields, dict_cls) declared_fields = mcs.get_fields(converter, opts, base_fields, dict_cls) if declared_fields is not None: # prevents sphinx from blowing up declared_fields.update(base_fields) return declared_fields
python
def get_declared_fields(mcs, klass, cls_fields, inherited_fields, dict_cls): opts = klass.opts converter = opts.model_converter(schema_cls=klass) base_fields = _BaseModelSerializerMetaclass.get_declared_fields( klass, cls_fields, inherited_fields, dict_cls) declared_fields = mcs.get_fields(converter, opts, base_fields, dict_cls) if declared_fields is not None: # prevents sphinx from blowing up declared_fields.update(base_fields) return declared_fields
[ "def", "get_declared_fields", "(", "mcs", ",", "klass", ",", "cls_fields", ",", "inherited_fields", ",", "dict_cls", ")", ":", "opts", "=", "klass", ".", "opts", "converter", "=", "opts", ".", "model_converter", "(", "schema_cls", "=", "klass", ")", "base_fi...
Updates declared fields with fields converted from the SQLAlchemy model passed as the `model` class Meta option.
[ "Updates", "declared", "fields", "with", "fields", "converted", "from", "the", "SQLAlchemy", "model", "passed", "as", "the", "model", "class", "Meta", "option", "." ]
4d536cb90e2cc4829c1c05f2c74d3e22901a1399
https://github.com/briancappello/flask-unchained/blob/4d536cb90e2cc4829c1c05f2c74d3e22901a1399/flask_unchained/bundles/api/model_serializer.py#L161-L173
25,835
briancappello/flask-unchained
flask_unchained/commands/qtconsole.py
JupyterWidget.reset
def reset(self, clear=False): """ Overridden to customize the order that the banners are printed """ if self._executing: self._executing = False self._request_info['execute'] = {} self._reading = False self._highlighter.highlighting_on = False if clear: self._control.clear() if self._display_banner: if self.kernel_banner: self._append_plain_text(self.kernel_banner) self._append_plain_text(self.banner) # update output marker for stdout/stderr, so that startup # messages appear after banner: self._show_interpreter_prompt()
python
def reset(self, clear=False): if self._executing: self._executing = False self._request_info['execute'] = {} self._reading = False self._highlighter.highlighting_on = False if clear: self._control.clear() if self._display_banner: if self.kernel_banner: self._append_plain_text(self.kernel_banner) self._append_plain_text(self.banner) # update output marker for stdout/stderr, so that startup # messages appear after banner: self._show_interpreter_prompt()
[ "def", "reset", "(", "self", ",", "clear", "=", "False", ")", ":", "if", "self", ".", "_executing", ":", "self", ".", "_executing", "=", "False", "self", ".", "_request_info", "[", "'execute'", "]", "=", "{", "}", "self", ".", "_reading", "=", "False...
Overridden to customize the order that the banners are printed
[ "Overridden", "to", "customize", "the", "order", "that", "the", "banners", "are", "printed" ]
4d536cb90e2cc4829c1c05f2c74d3e22901a1399
https://github.com/briancappello/flask-unchained/blob/4d536cb90e2cc4829c1c05f2c74d3e22901a1399/flask_unchained/commands/qtconsole.py#L100-L119
25,836
briancappello/flask-unchained
flask_unchained/commands/qtconsole.py
IPythonKernelApp.log_connection_info
def log_connection_info(self): """ Overridden to customize the start-up message printed to the terminal """ _ctrl_c_lines = [ 'NOTE: Ctrl-C does not work to exit from the command line.', 'To exit, just close the window, type "exit" or "quit" at the ' 'qtconsole prompt, or use Ctrl-\\ in UNIX-like environments ' '(at the command prompt).'] for line in _ctrl_c_lines: io.rprint(line) # upstream has this here, even though it seems like a silly place for it self.ports = dict(shell=self.shell_port, iopub=self.iopub_port, stdin=self.stdin_port, hb=self.hb_port, control=self.control_port)
python
def log_connection_info(self): _ctrl_c_lines = [ 'NOTE: Ctrl-C does not work to exit from the command line.', 'To exit, just close the window, type "exit" or "quit" at the ' 'qtconsole prompt, or use Ctrl-\\ in UNIX-like environments ' '(at the command prompt).'] for line in _ctrl_c_lines: io.rprint(line) # upstream has this here, even though it seems like a silly place for it self.ports = dict(shell=self.shell_port, iopub=self.iopub_port, stdin=self.stdin_port, hb=self.hb_port, control=self.control_port)
[ "def", "log_connection_info", "(", "self", ")", ":", "_ctrl_c_lines", "=", "[", "'NOTE: Ctrl-C does not work to exit from the command line.'", ",", "'To exit, just close the window, type \"exit\" or \"quit\" at the '", "'qtconsole prompt, or use Ctrl-\\\\ in UNIX-like environments '", "'(a...
Overridden to customize the start-up message printed to the terminal
[ "Overridden", "to", "customize", "the", "start", "-", "up", "message", "printed", "to", "the", "terminal" ]
4d536cb90e2cc4829c1c05f2c74d3e22901a1399
https://github.com/briancappello/flask-unchained/blob/4d536cb90e2cc4829c1c05f2c74d3e22901a1399/flask_unchained/commands/qtconsole.py#L135-L151
25,837
briancappello/flask-unchained
flask_unchained/bundles/controller/utils.py
url_for
def url_for(endpoint_or_url_or_config_key: str, _anchor: Optional[str] = None, _cls: Optional[Union[object, type]] = None, _external: Optional[bool] = False, _external_host: Optional[str] = None, _method: Optional[str] = None, _scheme: Optional[str] = None, **values, ) -> Union[str, None]: """ An improved version of flask's url_for function :param endpoint_or_url_or_config_key: what to lookup. it can be an endpoint name, an app config key, or an already-formed url. if _cls is specified, it also accepts a method name. :param values: the variable arguments of the URL rule :param _anchor: if provided this is added as anchor to the URL. :param _cls: if specified, can also pass a method name as the first argument :param _external: if set to ``True``, an absolute URL is generated. Server address can be changed via ``SERVER_NAME`` configuration variable which defaults to `localhost`. :param _external_host: if specified, the host of an external server to generate urls for (eg https://example.com or localhost:8888) :param _method: if provided this explicitly specifies an HTTP method. :param _scheme: a string specifying the desired URL scheme. The `_external` parameter must be set to ``True`` or a :exc:`ValueError` is raised. The default behavior uses the same scheme as the current request, or ``PREFERRED_URL_SCHEME`` from the :ref:`app configuration <config>` if no request context is available. As of Werkzeug 0.10, this also can be set to an empty string to build protocol-relative URLs. """ what = endpoint_or_url_or_config_key # if what is a config key if what and what.isupper(): what = current_app.config.get(what) if isinstance(what, LocalProxy): what = what._get_current_object() # if we already have a url (or an invalid value, eg None) if not what or '/' in what: return what flask_url_for_kwargs = dict(_anchor=_anchor, _external=_external, _external_host=_external_host, _method=_method, _scheme=_scheme, **values) # check if it's a class method name, and try that endpoint if _cls and '.' not in what: controller_routes = getattr(_cls, CONTROLLER_ROUTES_ATTR) method_routes = controller_routes.get(what) try: return _url_for(method_routes[0].endpoint, **flask_url_for_kwargs) except ( BuildError, # url not found IndexError, # method_routes[0] is out-of-range TypeError, # method_routes is None ): pass # what must be an endpoint return _url_for(what, **flask_url_for_kwargs)
python
def url_for(endpoint_or_url_or_config_key: str, _anchor: Optional[str] = None, _cls: Optional[Union[object, type]] = None, _external: Optional[bool] = False, _external_host: Optional[str] = None, _method: Optional[str] = None, _scheme: Optional[str] = None, **values, ) -> Union[str, None]: what = endpoint_or_url_or_config_key # if what is a config key if what and what.isupper(): what = current_app.config.get(what) if isinstance(what, LocalProxy): what = what._get_current_object() # if we already have a url (or an invalid value, eg None) if not what or '/' in what: return what flask_url_for_kwargs = dict(_anchor=_anchor, _external=_external, _external_host=_external_host, _method=_method, _scheme=_scheme, **values) # check if it's a class method name, and try that endpoint if _cls and '.' not in what: controller_routes = getattr(_cls, CONTROLLER_ROUTES_ATTR) method_routes = controller_routes.get(what) try: return _url_for(method_routes[0].endpoint, **flask_url_for_kwargs) except ( BuildError, # url not found IndexError, # method_routes[0] is out-of-range TypeError, # method_routes is None ): pass # what must be an endpoint return _url_for(what, **flask_url_for_kwargs)
[ "def", "url_for", "(", "endpoint_or_url_or_config_key", ":", "str", ",", "_anchor", ":", "Optional", "[", "str", "]", "=", "None", ",", "_cls", ":", "Optional", "[", "Union", "[", "object", ",", "type", "]", "]", "=", "None", ",", "_external", ":", "Op...
An improved version of flask's url_for function :param endpoint_or_url_or_config_key: what to lookup. it can be an endpoint name, an app config key, or an already-formed url. if _cls is specified, it also accepts a method name. :param values: the variable arguments of the URL rule :param _anchor: if provided this is added as anchor to the URL. :param _cls: if specified, can also pass a method name as the first argument :param _external: if set to ``True``, an absolute URL is generated. Server address can be changed via ``SERVER_NAME`` configuration variable which defaults to `localhost`. :param _external_host: if specified, the host of an external server to generate urls for (eg https://example.com or localhost:8888) :param _method: if provided this explicitly specifies an HTTP method. :param _scheme: a string specifying the desired URL scheme. The `_external` parameter must be set to ``True`` or a :exc:`ValueError` is raised. The default behavior uses the same scheme as the current request, or ``PREFERRED_URL_SCHEME`` from the :ref:`app configuration <config>` if no request context is available. As of Werkzeug 0.10, this also can be set to an empty string to build protocol-relative URLs.
[ "An", "improved", "version", "of", "flask", "s", "url_for", "function" ]
4d536cb90e2cc4829c1c05f2c74d3e22901a1399
https://github.com/briancappello/flask-unchained/blob/4d536cb90e2cc4829c1c05f2c74d3e22901a1399/flask_unchained/bundles/controller/utils.py#L99-L161
25,838
briancappello/flask-unchained
flask_unchained/bundles/controller/utils.py
redirect
def redirect(where: Optional[str] = None, default: Optional[str] = None, override: Optional[str] = None, _anchor: Optional[str] = None, _cls: Optional[Union[object, type]] = None, _external: Optional[bool] = False, _external_host: Optional[str] = None, _method: Optional[str] = None, _scheme: Optional[str] = None, **values, ) -> Response: """ An improved version of flask's redirect function :param where: A URL, endpoint, or config key name to redirect to :param default: A URL, endpoint, or config key name to redirect to if ``where`` is invalid :param override: explicitly redirect to a URL, endpoint, or config key name (takes precedence over the ``next`` value in query strings or forms) :param values: the variable arguments of the URL rule :param _anchor: if provided this is added as anchor to the URL. :param _cls: if specified, allows a method name to be passed to where, default, and/or override :param _external: if set to ``True``, an absolute URL is generated. Server address can be changed via ``SERVER_NAME`` configuration variable which defaults to `localhost`. :param _external_host: if specified, the host of an external server to generate urls for (eg https://example.com or localhost:8888) :param _method: if provided this explicitly specifies an HTTP method. :param _scheme: a string specifying the desired URL scheme. The `_external` parameter must be set to ``True`` or a :exc:`ValueError` is raised. The default behavior uses the same scheme as the current request, or ``PREFERRED_URL_SCHEME`` from the :ref:`app configuration <config>` if no request context is available. As of Werkzeug 0.10, this also can be set to an empty string to build protocol-relative URLs. """ flask_url_for_kwargs = dict(_anchor=_anchor, _external=_external, _external_host=_external_host, _method=_method, _scheme=_scheme, **values) urls = [url_for(request.args.get('next'), **flask_url_for_kwargs), url_for(request.form.get('next'), **flask_url_for_kwargs)] if where: urls.append(url_for(where, _cls=_cls, **flask_url_for_kwargs)) if default: urls.append(url_for(default, _cls=_cls, **flask_url_for_kwargs)) if override: urls.insert(0, url_for(override, _cls=_cls, **flask_url_for_kwargs)) for url in urls: if _validate_redirect_url(url, _external_host): return flask_redirect(url) return flask_redirect('/')
python
def redirect(where: Optional[str] = None, default: Optional[str] = None, override: Optional[str] = None, _anchor: Optional[str] = None, _cls: Optional[Union[object, type]] = None, _external: Optional[bool] = False, _external_host: Optional[str] = None, _method: Optional[str] = None, _scheme: Optional[str] = None, **values, ) -> Response: flask_url_for_kwargs = dict(_anchor=_anchor, _external=_external, _external_host=_external_host, _method=_method, _scheme=_scheme, **values) urls = [url_for(request.args.get('next'), **flask_url_for_kwargs), url_for(request.form.get('next'), **flask_url_for_kwargs)] if where: urls.append(url_for(where, _cls=_cls, **flask_url_for_kwargs)) if default: urls.append(url_for(default, _cls=_cls, **flask_url_for_kwargs)) if override: urls.insert(0, url_for(override, _cls=_cls, **flask_url_for_kwargs)) for url in urls: if _validate_redirect_url(url, _external_host): return flask_redirect(url) return flask_redirect('/')
[ "def", "redirect", "(", "where", ":", "Optional", "[", "str", "]", "=", "None", ",", "default", ":", "Optional", "[", "str", "]", "=", "None", ",", "override", ":", "Optional", "[", "str", "]", "=", "None", ",", "_anchor", ":", "Optional", "[", "st...
An improved version of flask's redirect function :param where: A URL, endpoint, or config key name to redirect to :param default: A URL, endpoint, or config key name to redirect to if ``where`` is invalid :param override: explicitly redirect to a URL, endpoint, or config key name (takes precedence over the ``next`` value in query strings or forms) :param values: the variable arguments of the URL rule :param _anchor: if provided this is added as anchor to the URL. :param _cls: if specified, allows a method name to be passed to where, default, and/or override :param _external: if set to ``True``, an absolute URL is generated. Server address can be changed via ``SERVER_NAME`` configuration variable which defaults to `localhost`. :param _external_host: if specified, the host of an external server to generate urls for (eg https://example.com or localhost:8888) :param _method: if provided this explicitly specifies an HTTP method. :param _scheme: a string specifying the desired URL scheme. The `_external` parameter must be set to ``True`` or a :exc:`ValueError` is raised. The default behavior uses the same scheme as the current request, or ``PREFERRED_URL_SCHEME`` from the :ref:`app configuration <config>` if no request context is available. As of Werkzeug 0.10, this also can be set to an empty string to build protocol-relative URLs.
[ "An", "improved", "version", "of", "flask", "s", "redirect", "function" ]
4d536cb90e2cc4829c1c05f2c74d3e22901a1399
https://github.com/briancappello/flask-unchained/blob/4d536cb90e2cc4829c1c05f2c74d3e22901a1399/flask_unchained/bundles/controller/utils.py#L193-L245
25,839
briancappello/flask-unchained
flask_unchained/bundles/controller/utils.py
_url_for
def _url_for(endpoint: str, **values) -> Union[str, None]: """ The same as flask's url_for, except this also supports building external urls for hosts that are different from app.config.SERVER_NAME. One case where this is especially useful is for single page apps, where the frontend is not hosted by the same server as the backend, but the backend still needs to generate urls to frontend routes :param endpoint: the name of the endpoint :param values: the variable arguments of the URL rule :return: a url path, or None """ _external_host = values.pop('_external_host', None) is_external = bool(_external_host or values.get('_external')) external_host = _external_host or current_app.config.get('EXTERNAL_SERVER_NAME') if not is_external or not external_host: return flask_url_for(endpoint, **values) if '://' not in external_host: external_host = f'http://{external_host}' values.pop('_external') return external_host.rstrip('/') + flask_url_for(endpoint, **values)
python
def _url_for(endpoint: str, **values) -> Union[str, None]: _external_host = values.pop('_external_host', None) is_external = bool(_external_host or values.get('_external')) external_host = _external_host or current_app.config.get('EXTERNAL_SERVER_NAME') if not is_external or not external_host: return flask_url_for(endpoint, **values) if '://' not in external_host: external_host = f'http://{external_host}' values.pop('_external') return external_host.rstrip('/') + flask_url_for(endpoint, **values)
[ "def", "_url_for", "(", "endpoint", ":", "str", ",", "*", "*", "values", ")", "->", "Union", "[", "str", ",", "None", "]", ":", "_external_host", "=", "values", ".", "pop", "(", "'_external_host'", ",", "None", ")", "is_external", "=", "bool", "(", "...
The same as flask's url_for, except this also supports building external urls for hosts that are different from app.config.SERVER_NAME. One case where this is especially useful is for single page apps, where the frontend is not hosted by the same server as the backend, but the backend still needs to generate urls to frontend routes :param endpoint: the name of the endpoint :param values: the variable arguments of the URL rule :return: a url path, or None
[ "The", "same", "as", "flask", "s", "url_for", "except", "this", "also", "supports", "building", "external", "urls", "for", "hosts", "that", "are", "different", "from", "app", ".", "config", ".", "SERVER_NAME", ".", "One", "case", "where", "this", "is", "es...
4d536cb90e2cc4829c1c05f2c74d3e22901a1399
https://github.com/briancappello/flask-unchained/blob/4d536cb90e2cc4829c1c05f2c74d3e22901a1399/flask_unchained/bundles/controller/utils.py#L263-L284
25,840
briancappello/flask-unchained
flask_unchained/bundles/security/decorators/roles_required.py
roles_required
def roles_required(*roles): """ Decorator which specifies that a user must have all the specified roles. Aborts with HTTP 403: Forbidden if the user doesn't have the required roles. Example:: @app.route('/dashboard') @roles_required('ROLE_ADMIN', 'ROLE_EDITOR') def dashboard(): return 'Dashboard' The current user must have both the `ROLE_ADMIN` and `ROLE_EDITOR` roles in order to view the page. :param roles: The required roles. """ def wrapper(fn): @wraps(fn) def decorated_view(*args, **kwargs): perms = [Permission(RoleNeed(role)) for role in roles] for perm in perms: if not perm.can(): abort(HTTPStatus.FORBIDDEN) return fn(*args, **kwargs) return decorated_view return wrapper
python
def roles_required(*roles): def wrapper(fn): @wraps(fn) def decorated_view(*args, **kwargs): perms = [Permission(RoleNeed(role)) for role in roles] for perm in perms: if not perm.can(): abort(HTTPStatus.FORBIDDEN) return fn(*args, **kwargs) return decorated_view return wrapper
[ "def", "roles_required", "(", "*", "roles", ")", ":", "def", "wrapper", "(", "fn", ")", ":", "@", "wraps", "(", "fn", ")", "def", "decorated_view", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "perms", "=", "[", "Permission", "(", "RoleNeed...
Decorator which specifies that a user must have all the specified roles. Aborts with HTTP 403: Forbidden if the user doesn't have the required roles. Example:: @app.route('/dashboard') @roles_required('ROLE_ADMIN', 'ROLE_EDITOR') def dashboard(): return 'Dashboard' The current user must have both the `ROLE_ADMIN` and `ROLE_EDITOR` roles in order to view the page. :param roles: The required roles.
[ "Decorator", "which", "specifies", "that", "a", "user", "must", "have", "all", "the", "specified", "roles", "." ]
4d536cb90e2cc4829c1c05f2c74d3e22901a1399
https://github.com/briancappello/flask-unchained/blob/4d536cb90e2cc4829c1c05f2c74d3e22901a1399/flask_unchained/bundles/security/decorators/roles_required.py#L7-L34
25,841
briancappello/flask-unchained
flask_unchained/bundles/security/services/security_utils_service.py
SecurityUtilsService.verify_hash
def verify_hash(self, hashed_data, compare_data): """ Verify a hash in the security token hashing context. """ return self.security.hashing_context.verify( encode_string(compare_data), hashed_data)
python
def verify_hash(self, hashed_data, compare_data): return self.security.hashing_context.verify( encode_string(compare_data), hashed_data)
[ "def", "verify_hash", "(", "self", ",", "hashed_data", ",", "compare_data", ")", ":", "return", "self", ".", "security", ".", "hashing_context", ".", "verify", "(", "encode_string", "(", "compare_data", ")", ",", "hashed_data", ")" ]
Verify a hash in the security token hashing context.
[ "Verify", "a", "hash", "in", "the", "security", "token", "hashing", "context", "." ]
4d536cb90e2cc4829c1c05f2c74d3e22901a1399
https://github.com/briancappello/flask-unchained/blob/4d536cb90e2cc4829c1c05f2c74d3e22901a1399/flask_unchained/bundles/security/services/security_utils_service.py#L89-L94
25,842
briancappello/flask-unchained
flask_unchained/bundles/security/decorators/auth_required.py
auth_required
def auth_required(decorated_fn=None, **role_rules): """ Decorator for requiring an authenticated user, optionally with roles. Roles are passed as keyword arguments, like so:: @auth_required(role='REQUIRE_THIS_ONE_ROLE') @auth_required(roles=['REQUIRE', 'ALL', 'OF', 'THESE', 'ROLES']) @auth_required(one_of=['EITHER_THIS_ROLE', 'OR_THIS_ONE']) One of role or roles kwargs can also be combined with one_of:: @auth_required(role='REQUIRED', one_of=['THIS', 'OR_THIS']) Aborts with ``HTTP 401: Unauthorized`` if no user is logged in, or ``HTTP 403: Forbidden`` if any of the specified role checks fail. """ required_roles = [] one_of_roles = [] if not (decorated_fn and callable(decorated_fn)): if 'role' in role_rules and 'roles' in role_rules: raise RuntimeError('specify only one of `role` or `roles` kwargs') elif 'role' in role_rules: required_roles = [role_rules['role']] elif 'roles' in role_rules: required_roles = role_rules['roles'] if 'one_of' in role_rules: one_of_roles = role_rules['one_of'] def wrapper(fn): @wraps(fn) @_auth_required() @roles_required(*required_roles) @roles_accepted(*one_of_roles) def decorated(*args, **kwargs): return fn(*args, **kwargs) return decorated if decorated_fn and callable(decorated_fn): return wrapper(decorated_fn) return wrapper
python
def auth_required(decorated_fn=None, **role_rules): required_roles = [] one_of_roles = [] if not (decorated_fn and callable(decorated_fn)): if 'role' in role_rules and 'roles' in role_rules: raise RuntimeError('specify only one of `role` or `roles` kwargs') elif 'role' in role_rules: required_roles = [role_rules['role']] elif 'roles' in role_rules: required_roles = role_rules['roles'] if 'one_of' in role_rules: one_of_roles = role_rules['one_of'] def wrapper(fn): @wraps(fn) @_auth_required() @roles_required(*required_roles) @roles_accepted(*one_of_roles) def decorated(*args, **kwargs): return fn(*args, **kwargs) return decorated if decorated_fn and callable(decorated_fn): return wrapper(decorated_fn) return wrapper
[ "def", "auth_required", "(", "decorated_fn", "=", "None", ",", "*", "*", "role_rules", ")", ":", "required_roles", "=", "[", "]", "one_of_roles", "=", "[", "]", "if", "not", "(", "decorated_fn", "and", "callable", "(", "decorated_fn", ")", ")", ":", "if"...
Decorator for requiring an authenticated user, optionally with roles. Roles are passed as keyword arguments, like so:: @auth_required(role='REQUIRE_THIS_ONE_ROLE') @auth_required(roles=['REQUIRE', 'ALL', 'OF', 'THESE', 'ROLES']) @auth_required(one_of=['EITHER_THIS_ROLE', 'OR_THIS_ONE']) One of role or roles kwargs can also be combined with one_of:: @auth_required(role='REQUIRED', one_of=['THIS', 'OR_THIS']) Aborts with ``HTTP 401: Unauthorized`` if no user is logged in, or ``HTTP 403: Forbidden`` if any of the specified role checks fail.
[ "Decorator", "for", "requiring", "an", "authenticated", "user", "optionally", "with", "roles", "." ]
4d536cb90e2cc4829c1c05f2c74d3e22901a1399
https://github.com/briancappello/flask-unchained/blob/4d536cb90e2cc4829c1c05f2c74d3e22901a1399/flask_unchained/bundles/security/decorators/auth_required.py#L13-L54
25,843
briancappello/flask-unchained
flask_unchained/bundles/security/decorators/auth_required.py
_auth_required
def _auth_required(): """ Decorator that protects endpoints through token and session auth mechanisms """ login_mechanisms = ( ('token', lambda: _check_token()), ('session', lambda: current_user.is_authenticated), ) def wrapper(fn): @wraps(fn) def decorated_view(*args, **kwargs): for method, mechanism in login_mechanisms: if mechanism and mechanism(): return fn(*args, **kwargs) return security._unauthorized_callback() return decorated_view return wrapper
python
def _auth_required(): login_mechanisms = ( ('token', lambda: _check_token()), ('session', lambda: current_user.is_authenticated), ) def wrapper(fn): @wraps(fn) def decorated_view(*args, **kwargs): for method, mechanism in login_mechanisms: if mechanism and mechanism(): return fn(*args, **kwargs) return security._unauthorized_callback() return decorated_view return wrapper
[ "def", "_auth_required", "(", ")", ":", "login_mechanisms", "=", "(", "(", "'token'", ",", "lambda", ":", "_check_token", "(", ")", ")", ",", "(", "'session'", ",", "lambda", ":", "current_user", ".", "is_authenticated", ")", ",", ")", "def", "wrapper", ...
Decorator that protects endpoints through token and session auth mechanisms
[ "Decorator", "that", "protects", "endpoints", "through", "token", "and", "session", "auth", "mechanisms" ]
4d536cb90e2cc4829c1c05f2c74d3e22901a1399
https://github.com/briancappello/flask-unchained/blob/4d536cb90e2cc4829c1c05f2c74d3e22901a1399/flask_unchained/bundles/security/decorators/auth_required.py#L57-L75
25,844
briancappello/flask-unchained
flask_unchained/bundles/celery/tasks.py
async_mail_task
def async_mail_task(subject_or_message, to=None, template=None, **kwargs): """ Celery task to send emails asynchronously using the mail bundle. """ to = to or kwargs.pop('recipients', []) msg = make_message(subject_or_message, to, template, **kwargs) with mail.connect() as connection: connection.send(msg)
python
def async_mail_task(subject_or_message, to=None, template=None, **kwargs): to = to or kwargs.pop('recipients', []) msg = make_message(subject_or_message, to, template, **kwargs) with mail.connect() as connection: connection.send(msg)
[ "def", "async_mail_task", "(", "subject_or_message", ",", "to", "=", "None", ",", "template", "=", "None", ",", "*", "*", "kwargs", ")", ":", "to", "=", "to", "or", "kwargs", ".", "pop", "(", "'recipients'", ",", "[", "]", ")", "msg", "=", "make_mess...
Celery task to send emails asynchronously using the mail bundle.
[ "Celery", "task", "to", "send", "emails", "asynchronously", "using", "the", "mail", "bundle", "." ]
4d536cb90e2cc4829c1c05f2c74d3e22901a1399
https://github.com/briancappello/flask-unchained/blob/4d536cb90e2cc4829c1c05f2c74d3e22901a1399/flask_unchained/bundles/celery/tasks.py#L16-L23
25,845
briancappello/flask-unchained
flask_unchained/bundles/api/__init__.py
ApiBundle.after_init_app
def after_init_app(self, app: FlaskUnchained): """ Configure the JSON encoder for Flask to be able to serialize Enums, LocalProxy objects, and SQLAlchemy models. """ self.set_json_encoder(app) app.before_first_request(self.register_model_resources)
python
def after_init_app(self, app: FlaskUnchained): self.set_json_encoder(app) app.before_first_request(self.register_model_resources)
[ "def", "after_init_app", "(", "self", ",", "app", ":", "FlaskUnchained", ")", ":", "self", ".", "set_json_encoder", "(", "app", ")", "app", ".", "before_first_request", "(", "self", ".", "register_model_resources", ")" ]
Configure the JSON encoder for Flask to be able to serialize Enums, LocalProxy objects, and SQLAlchemy models.
[ "Configure", "the", "JSON", "encoder", "for", "Flask", "to", "be", "able", "to", "serialize", "Enums", "LocalProxy", "objects", "and", "SQLAlchemy", "models", "." ]
4d536cb90e2cc4829c1c05f2c74d3e22901a1399
https://github.com/briancappello/flask-unchained/blob/4d536cb90e2cc4829c1c05f2c74d3e22901a1399/flask_unchained/bundles/api/__init__.py#L52-L58
25,846
briancappello/flask-unchained
flask_unchained/bundles/controller/route.py
Route.endpoint
def endpoint(self): """ The endpoint for this route. """ if self._endpoint: return self._endpoint elif self._controller_cls: endpoint = f'{snake_case(self._controller_cls.__name__)}.{self.method_name}' return endpoint if not self.bp_name else f'{self.bp_name}.{endpoint}' elif self.bp_name: return f'{self.bp_name}.{self.method_name}' return f'{self.view_func.__module__}.{self.method_name}'
python
def endpoint(self): if self._endpoint: return self._endpoint elif self._controller_cls: endpoint = f'{snake_case(self._controller_cls.__name__)}.{self.method_name}' return endpoint if not self.bp_name else f'{self.bp_name}.{endpoint}' elif self.bp_name: return f'{self.bp_name}.{self.method_name}' return f'{self.view_func.__module__}.{self.method_name}'
[ "def", "endpoint", "(", "self", ")", ":", "if", "self", ".", "_endpoint", ":", "return", "self", ".", "_endpoint", "elif", "self", ".", "_controller_cls", ":", "endpoint", "=", "f'{snake_case(self._controller_cls.__name__)}.{self.method_name}'", "return", "endpoint", ...
The endpoint for this route.
[ "The", "endpoint", "for", "this", "route", "." ]
4d536cb90e2cc4829c1c05f2c74d3e22901a1399
https://github.com/briancappello/flask-unchained/blob/4d536cb90e2cc4829c1c05f2c74d3e22901a1399/flask_unchained/bundles/controller/route.py#L102-L113
25,847
briancappello/flask-unchained
flask_unchained/bundles/controller/route.py
Route.method_name
def method_name(self): """ The string name of this route's view function. """ if isinstance(self.view_func, str): return self.view_func return self.view_func.__name__
python
def method_name(self): if isinstance(self.view_func, str): return self.view_func return self.view_func.__name__
[ "def", "method_name", "(", "self", ")", ":", "if", "isinstance", "(", "self", ".", "view_func", ",", "str", ")", ":", "return", "self", ".", "view_func", "return", "self", ".", "view_func", ".", "__name__" ]
The string name of this route's view function.
[ "The", "string", "name", "of", "this", "route", "s", "view", "function", "." ]
4d536cb90e2cc4829c1c05f2c74d3e22901a1399
https://github.com/briancappello/flask-unchained/blob/4d536cb90e2cc4829c1c05f2c74d3e22901a1399/flask_unchained/bundles/controller/route.py#L133-L139
25,848
briancappello/flask-unchained
flask_unchained/bundles/controller/route.py
Route.module_name
def module_name(self): """ The module where this route's view function was defined. """ if not self.view_func: return None elif self._controller_cls: rv = inspect.getmodule(self._controller_cls).__name__ return rv return inspect.getmodule(self.view_func).__name__
python
def module_name(self): if not self.view_func: return None elif self._controller_cls: rv = inspect.getmodule(self._controller_cls).__name__ return rv return inspect.getmodule(self.view_func).__name__
[ "def", "module_name", "(", "self", ")", ":", "if", "not", "self", ".", "view_func", ":", "return", "None", "elif", "self", ".", "_controller_cls", ":", "rv", "=", "inspect", ".", "getmodule", "(", "self", ".", "_controller_cls", ")", ".", "__name__", "re...
The module where this route's view function was defined.
[ "The", "module", "where", "this", "route", "s", "view", "function", "was", "defined", "." ]
4d536cb90e2cc4829c1c05f2c74d3e22901a1399
https://github.com/briancappello/flask-unchained/blob/4d536cb90e2cc4829c1c05f2c74d3e22901a1399/flask_unchained/bundles/controller/route.py#L153-L162
25,849
briancappello/flask-unchained
flask_unchained/bundles/controller/route.py
Route.full_rule
def full_rule(self): """ The full url rule for this route, including any blueprint prefix. """ return join(self.bp_prefix, self.rule, trailing_slash=self.rule.endswith('/'))
python
def full_rule(self): return join(self.bp_prefix, self.rule, trailing_slash=self.rule.endswith('/'))
[ "def", "full_rule", "(", "self", ")", ":", "return", "join", "(", "self", ".", "bp_prefix", ",", "self", ".", "rule", ",", "trailing_slash", "=", "self", ".", "rule", ".", "endswith", "(", "'/'", ")", ")" ]
The full url rule for this route, including any blueprint prefix.
[ "The", "full", "url", "rule", "for", "this", "route", "including", "any", "blueprint", "prefix", "." ]
4d536cb90e2cc4829c1c05f2c74d3e22901a1399
https://github.com/briancappello/flask-unchained/blob/4d536cb90e2cc4829c1c05f2c74d3e22901a1399/flask_unchained/bundles/controller/route.py#L195-L199
25,850
briancappello/flask-unchained
flask_unchained/bundles/controller/route.py
Route.full_name
def full_name(self): """ The full name of this route's view function, including the module path and controller name, if any. """ if not self.view_func: return None prefix = self.view_func.__module__ if self._controller_cls: prefix = f'{prefix}.{self._controller_cls.__name__}' return f'{prefix}.{self.method_name}'
python
def full_name(self): if not self.view_func: return None prefix = self.view_func.__module__ if self._controller_cls: prefix = f'{prefix}.{self._controller_cls.__name__}' return f'{prefix}.{self.method_name}'
[ "def", "full_name", "(", "self", ")", ":", "if", "not", "self", ".", "view_func", ":", "return", "None", "prefix", "=", "self", ".", "view_func", ".", "__module__", "if", "self", ".", "_controller_cls", ":", "prefix", "=", "f'{prefix}.{self._controller_cls.__n...
The full name of this route's view function, including the module path and controller name, if any.
[ "The", "full", "name", "of", "this", "route", "s", "view", "function", "including", "the", "module", "path", "and", "controller", "name", "if", "any", "." ]
4d536cb90e2cc4829c1c05f2c74d3e22901a1399
https://github.com/briancappello/flask-unchained/blob/4d536cb90e2cc4829c1c05f2c74d3e22901a1399/flask_unchained/bundles/controller/route.py#L235-L246
25,851
briancappello/flask-unchained
flask_unchained/commands/new.py
project
def project(dest, app_bundle, force, dev, admin, api, celery, graphene, mail, oauth, security, session, sqlalchemy, webpack): """ Create a new Flask Unchained project. """ if os.path.exists(dest) and os.listdir(dest) and not force: if not click.confirm(f'WARNING: Project directory {dest!r} exists and is ' f'not empty. It will be DELETED!!! Continue?'): click.echo(f'Exiting.') sys.exit(1) # build up a list of dependencies # IMPORTANT: keys here must match setup.py's `extra_requires` keys ctx = dict(dev=dev, admin=admin, api=api, celery=celery, graphene=graphene, mail=mail, oauth=oauth, security=security or oauth, session=security or session, sqlalchemy=security or sqlalchemy, webpack=webpack) ctx['requirements'] = [k for k, v in ctx.items() if v] # remaining ctx vars ctx['app_bundle_module_name'] = app_bundle # copy the project template into place copy_file_tree(PROJECT_TEMPLATE, dest, ctx, [ (option, files) for option, files in [('api', ['app/serializers']), ('celery', ['app/tasks', 'celery_app.py']), ('graphene', ['app/graphql']), ('mail', ['templates/email']), ('security', ['app/models/role.py', 'app/models/user.py', 'db/fixtures/Role.yaml', 'db/fixtures/User.yaml']), ('webpack', ['assets', 'package.json', 'webpack']), ] if not ctx[option] ]) click.echo(f'Successfully created a new project at: {dest}')
python
def project(dest, app_bundle, force, dev, admin, api, celery, graphene, mail, oauth, security, session, sqlalchemy, webpack): if os.path.exists(dest) and os.listdir(dest) and not force: if not click.confirm(f'WARNING: Project directory {dest!r} exists and is ' f'not empty. It will be DELETED!!! Continue?'): click.echo(f'Exiting.') sys.exit(1) # build up a list of dependencies # IMPORTANT: keys here must match setup.py's `extra_requires` keys ctx = dict(dev=dev, admin=admin, api=api, celery=celery, graphene=graphene, mail=mail, oauth=oauth, security=security or oauth, session=security or session, sqlalchemy=security or sqlalchemy, webpack=webpack) ctx['requirements'] = [k for k, v in ctx.items() if v] # remaining ctx vars ctx['app_bundle_module_name'] = app_bundle # copy the project template into place copy_file_tree(PROJECT_TEMPLATE, dest, ctx, [ (option, files) for option, files in [('api', ['app/serializers']), ('celery', ['app/tasks', 'celery_app.py']), ('graphene', ['app/graphql']), ('mail', ['templates/email']), ('security', ['app/models/role.py', 'app/models/user.py', 'db/fixtures/Role.yaml', 'db/fixtures/User.yaml']), ('webpack', ['assets', 'package.json', 'webpack']), ] if not ctx[option] ]) click.echo(f'Successfully created a new project at: {dest}')
[ "def", "project", "(", "dest", ",", "app_bundle", ",", "force", ",", "dev", ",", "admin", ",", "api", ",", "celery", ",", "graphene", ",", "mail", ",", "oauth", ",", "security", ",", "session", ",", "sqlalchemy", ",", "webpack", ")", ":", "if", "os",...
Create a new Flask Unchained project.
[ "Create", "a", "new", "Flask", "Unchained", "project", "." ]
4d536cb90e2cc4829c1c05f2c74d3e22901a1399
https://github.com/briancappello/flask-unchained/blob/4d536cb90e2cc4829c1c05f2c74d3e22901a1399/flask_unchained/commands/new.py#L182-L224
25,852
ironfroggy/straight.plugin
straight/plugin/manager.py
PluginManager.produce
def produce(self, *args, **kwargs): """Produce a new set of plugins, treating the current set as plugin factories. """ new_plugins = [] for p in self._plugins: r = p(*args, **kwargs) new_plugins.append(r) return PluginManager(new_plugins)
python
def produce(self, *args, **kwargs): new_plugins = [] for p in self._plugins: r = p(*args, **kwargs) new_plugins.append(r) return PluginManager(new_plugins)
[ "def", "produce", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "new_plugins", "=", "[", "]", "for", "p", "in", "self", ".", "_plugins", ":", "r", "=", "p", "(", "*", "args", ",", "*", "*", "kwargs", ")", "new_plugins", ".",...
Produce a new set of plugins, treating the current set as plugin factories.
[ "Produce", "a", "new", "set", "of", "plugins", "treating", "the", "current", "set", "as", "plugin", "factories", "." ]
aaaf68db51b823d164cf714b1be2262a75ee2a79
https://github.com/ironfroggy/straight.plugin/blob/aaaf68db51b823d164cf714b1be2262a75ee2a79/straight/plugin/manager.py#L15-L24
25,853
ironfroggy/straight.plugin
straight/plugin/manager.py
PluginManager.call
def call(self, methodname, *args, **kwargs): """Call a common method on all the plugins, if it exists.""" for plugin in self._plugins: method = getattr(plugin, methodname, None) if method is None: continue yield method(*args, **kwargs)
python
def call(self, methodname, *args, **kwargs): for plugin in self._plugins: method = getattr(plugin, methodname, None) if method is None: continue yield method(*args, **kwargs)
[ "def", "call", "(", "self", ",", "methodname", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "for", "plugin", "in", "self", ".", "_plugins", ":", "method", "=", "getattr", "(", "plugin", ",", "methodname", ",", "None", ")", "if", "method", "...
Call a common method on all the plugins, if it exists.
[ "Call", "a", "common", "method", "on", "all", "the", "plugins", "if", "it", "exists", "." ]
aaaf68db51b823d164cf714b1be2262a75ee2a79
https://github.com/ironfroggy/straight.plugin/blob/aaaf68db51b823d164cf714b1be2262a75ee2a79/straight/plugin/manager.py#L26-L33
25,854
ironfroggy/straight.plugin
straight/plugin/manager.py
PluginManager.pipe
def pipe(self, methodname, first_arg, *args, **kwargs): """Call a common method on all the plugins, if it exists. The return value of each call becomes the replaces the first argument in the given argument list to pass to the next. Useful to utilize plugins as sets of filters. """ for plugin in self._plugins: method = getattr(plugin, methodname, None) if method is None: continue r = method(first_arg, *args, **kwargs) if r is not None: first_arg = r return r
python
def pipe(self, methodname, first_arg, *args, **kwargs): for plugin in self._plugins: method = getattr(plugin, methodname, None) if method is None: continue r = method(first_arg, *args, **kwargs) if r is not None: first_arg = r return r
[ "def", "pipe", "(", "self", ",", "methodname", ",", "first_arg", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "for", "plugin", "in", "self", ".", "_plugins", ":", "method", "=", "getattr", "(", "plugin", ",", "methodname", ",", "None", ")", ...
Call a common method on all the plugins, if it exists. The return value of each call becomes the replaces the first argument in the given argument list to pass to the next. Useful to utilize plugins as sets of filters.
[ "Call", "a", "common", "method", "on", "all", "the", "plugins", "if", "it", "exists", ".", "The", "return", "value", "of", "each", "call", "becomes", "the", "replaces", "the", "first", "argument", "in", "the", "given", "argument", "list", "to", "pass", "...
aaaf68db51b823d164cf714b1be2262a75ee2a79
https://github.com/ironfroggy/straight.plugin/blob/aaaf68db51b823d164cf714b1be2262a75ee2a79/straight/plugin/manager.py#L46-L61
25,855
ironfroggy/straight.plugin
straight/plugin/loaders.py
unified_load
def unified_load(namespace, subclasses=None, recurse=False): """Provides a unified interface to both the module and class loaders, finding modules by default or classes if given a ``subclasses`` parameter. """ if subclasses is not None: return ClassLoader(recurse=recurse).load(namespace, subclasses=subclasses) else: return ModuleLoader(recurse=recurse).load(namespace)
python
def unified_load(namespace, subclasses=None, recurse=False): if subclasses is not None: return ClassLoader(recurse=recurse).load(namespace, subclasses=subclasses) else: return ModuleLoader(recurse=recurse).load(namespace)
[ "def", "unified_load", "(", "namespace", ",", "subclasses", "=", "None", ",", "recurse", "=", "False", ")", ":", "if", "subclasses", "is", "not", "None", ":", "return", "ClassLoader", "(", "recurse", "=", "recurse", ")", ".", "load", "(", "namespace", ",...
Provides a unified interface to both the module and class loaders, finding modules by default or classes if given a ``subclasses`` parameter.
[ "Provides", "a", "unified", "interface", "to", "both", "the", "module", "and", "class", "loaders", "finding", "modules", "by", "default", "or", "classes", "if", "given", "a", "subclasses", "parameter", "." ]
aaaf68db51b823d164cf714b1be2262a75ee2a79
https://github.com/ironfroggy/straight.plugin/blob/aaaf68db51b823d164cf714b1be2262a75ee2a79/straight/plugin/loaders.py#L161-L169
25,856
ironfroggy/straight.plugin
straight/plugin/loaders.py
ModuleLoader._fill_cache
def _fill_cache(self, namespace): """Load all modules found in a namespace""" modules = self._findPluginModules(namespace) self._cache = list(modules)
python
def _fill_cache(self, namespace): modules = self._findPluginModules(namespace) self._cache = list(modules)
[ "def", "_fill_cache", "(", "self", ",", "namespace", ")", ":", "modules", "=", "self", ".", "_findPluginModules", "(", "namespace", ")", "self", ".", "_cache", "=", "list", "(", "modules", ")" ]
Load all modules found in a namespace
[ "Load", "all", "modules", "found", "in", "a", "namespace" ]
aaaf68db51b823d164cf714b1be2262a75ee2a79
https://github.com/ironfroggy/straight.plugin/blob/aaaf68db51b823d164cf714b1be2262a75ee2a79/straight/plugin/loaders.py#L111-L116
25,857
gisce/libComXML
libcomxml/core/__init__.py
XmlModel.build_tree
def build_tree(self): """Bulids the tree with all the fields converted to Elements """ if self.built: return self.doc_root = self.root.element() for key in self.sorted_fields(): if key not in self._fields: continue field = self._fields[key] if field != self.root: if isinstance(field, XmlModel): field.build_tree() if (self.drop_empty and field.drop_empty and len(field.doc_root) == 0): continue self.doc_root.append(field.doc_root) elif isinstance(field, list): # we just allow XmlFields and XmlModels # Also xml as str for memory management for item in field: if isinstance(item, XmlField): ele = item.element() if self.drop_empty and len(ele) == 0: continue self.doc_root.append(ele) elif isinstance(item, XmlModel): item.build_tree() if self.drop_empty and len(item.doc_root) == 0: continue self.doc_root.append(item.doc_root) elif isinstance(item, (six.text_type, six.string_types)): ele = etree.fromstring(clean_xml(item)) self.doc_root.append(ele) item = None elif (field.parent or self.root.name) == self.root.name: ele = field.element() if self.drop_empty and len(ele) == 0 and not ele.text: continue ele = field.element(parent=self.doc_root) else: nodes = [n for n in self.doc_root.iterdescendants( tag=field.parent)] if nodes: ele = field.element() if (self.drop_empty and len(ele) == 0 and not ele.text): continue ele = field.element(parent=nodes[0]) #else: # raise RuntimeError("No parent found!") self.built = True
python
def build_tree(self): if self.built: return self.doc_root = self.root.element() for key in self.sorted_fields(): if key not in self._fields: continue field = self._fields[key] if field != self.root: if isinstance(field, XmlModel): field.build_tree() if (self.drop_empty and field.drop_empty and len(field.doc_root) == 0): continue self.doc_root.append(field.doc_root) elif isinstance(field, list): # we just allow XmlFields and XmlModels # Also xml as str for memory management for item in field: if isinstance(item, XmlField): ele = item.element() if self.drop_empty and len(ele) == 0: continue self.doc_root.append(ele) elif isinstance(item, XmlModel): item.build_tree() if self.drop_empty and len(item.doc_root) == 0: continue self.doc_root.append(item.doc_root) elif isinstance(item, (six.text_type, six.string_types)): ele = etree.fromstring(clean_xml(item)) self.doc_root.append(ele) item = None elif (field.parent or self.root.name) == self.root.name: ele = field.element() if self.drop_empty and len(ele) == 0 and not ele.text: continue ele = field.element(parent=self.doc_root) else: nodes = [n for n in self.doc_root.iterdescendants( tag=field.parent)] if nodes: ele = field.element() if (self.drop_empty and len(ele) == 0 and not ele.text): continue ele = field.element(parent=nodes[0]) #else: # raise RuntimeError("No parent found!") self.built = True
[ "def", "build_tree", "(", "self", ")", ":", "if", "self", ".", "built", ":", "return", "self", ".", "doc_root", "=", "self", ".", "root", ".", "element", "(", ")", "for", "key", "in", "self", ".", "sorted_fields", "(", ")", ":", "if", "key", "not",...
Bulids the tree with all the fields converted to Elements
[ "Bulids", "the", "tree", "with", "all", "the", "fields", "converted", "to", "Elements" ]
0aab7fe8790e33484778ac7b1ec827f9094d81f7
https://github.com/gisce/libComXML/blob/0aab7fe8790e33484778ac7b1ec827f9094d81f7/libcomxml/core/__init__.py#L223-L273
25,858
timofurrer/observable
observable/property.py
_preserve_settings
def _preserve_settings(method: T.Callable) -> T.Callable: """Decorator that ensures ObservableProperty-specific attributes are kept when using methods to change deleter, getter or setter.""" @functools.wraps(method) def _wrapper( old: "ObservableProperty", handler: T.Callable ) -> "ObservableProperty": new = method(old, handler) # type: ObservableProperty new.event = old.event new.observable = old.observable return new return _wrapper
python
def _preserve_settings(method: T.Callable) -> T.Callable: @functools.wraps(method) def _wrapper( old: "ObservableProperty", handler: T.Callable ) -> "ObservableProperty": new = method(old, handler) # type: ObservableProperty new.event = old.event new.observable = old.observable return new return _wrapper
[ "def", "_preserve_settings", "(", "method", ":", "T", ".", "Callable", ")", "->", "T", ".", "Callable", ":", "@", "functools", ".", "wraps", "(", "method", ")", "def", "_wrapper", "(", "old", ":", "\"ObservableProperty\"", ",", "handler", ":", "T", ".", ...
Decorator that ensures ObservableProperty-specific attributes are kept when using methods to change deleter, getter or setter.
[ "Decorator", "that", "ensures", "ObservableProperty", "-", "specific", "attributes", "are", "kept", "when", "using", "methods", "to", "change", "deleter", "getter", "or", "setter", "." ]
a6a764efaf9408a334bdb1ddf4327d9dbc4b8eaa
https://github.com/timofurrer/observable/blob/a6a764efaf9408a334bdb1ddf4327d9dbc4b8eaa/observable/property.py#L15-L28
25,859
timofurrer/observable
observable/property.py
ObservableProperty._trigger_event
def _trigger_event( self, holder: T.Any, alt_name: str, action: str, *event_args: T.Any ) -> None: """Triggers an event on the associated Observable object. The Holder is the object this property is a member of, alt_name is used as the event name when self.event is not set, action is prepended to the event name and event_args are passed through to the registered event handlers.""" if isinstance(self.observable, Observable): observable = self.observable elif isinstance(self.observable, str): observable = getattr(holder, self.observable) elif isinstance(holder, Observable): observable = holder else: raise TypeError( "This ObservableProperty is no member of an Observable " "object. Specify where to find the Observable object for " "triggering events with the observable keyword argument " "when initializing the ObservableProperty." ) name = alt_name if self.event is None else self.event event = "{}_{}".format(action, name) observable.trigger(event, *event_args)
python
def _trigger_event( self, holder: T.Any, alt_name: str, action: str, *event_args: T.Any ) -> None: if isinstance(self.observable, Observable): observable = self.observable elif isinstance(self.observable, str): observable = getattr(holder, self.observable) elif isinstance(holder, Observable): observable = holder else: raise TypeError( "This ObservableProperty is no member of an Observable " "object. Specify where to find the Observable object for " "triggering events with the observable keyword argument " "when initializing the ObservableProperty." ) name = alt_name if self.event is None else self.event event = "{}_{}".format(action, name) observable.trigger(event, *event_args)
[ "def", "_trigger_event", "(", "self", ",", "holder", ":", "T", ".", "Any", ",", "alt_name", ":", "str", ",", "action", ":", "str", ",", "*", "event_args", ":", "T", ".", "Any", ")", "->", "None", ":", "if", "isinstance", "(", "self", ".", "observab...
Triggers an event on the associated Observable object. The Holder is the object this property is a member of, alt_name is used as the event name when self.event is not set, action is prepended to the event name and event_args are passed through to the registered event handlers.
[ "Triggers", "an", "event", "on", "the", "associated", "Observable", "object", ".", "The", "Holder", "is", "the", "object", "this", "property", "is", "a", "member", "of", "alt_name", "is", "used", "as", "the", "event", "name", "when", "self", ".", "event", ...
a6a764efaf9408a334bdb1ddf4327d9dbc4b8eaa
https://github.com/timofurrer/observable/blob/a6a764efaf9408a334bdb1ddf4327d9dbc4b8eaa/observable/property.py#L70-L95
25,860
timofurrer/observable
observable/property.py
ObservableProperty.create_with
def create_with( cls, event: str = None, observable: T.Union[str, Observable] = None ) -> T.Callable[..., "ObservableProperty"]: """Creates a partial application of ObservableProperty with event and observable preset.""" return functools.partial(cls, event=event, observable=observable)
python
def create_with( cls, event: str = None, observable: T.Union[str, Observable] = None ) -> T.Callable[..., "ObservableProperty"]: return functools.partial(cls, event=event, observable=observable)
[ "def", "create_with", "(", "cls", ",", "event", ":", "str", "=", "None", ",", "observable", ":", "T", ".", "Union", "[", "str", ",", "Observable", "]", "=", "None", ")", "->", "T", ".", "Callable", "[", "...", ",", "\"ObservableProperty\"", "]", ":",...
Creates a partial application of ObservableProperty with event and observable preset.
[ "Creates", "a", "partial", "application", "of", "ObservableProperty", "with", "event", "and", "observable", "preset", "." ]
a6a764efaf9408a334bdb1ddf4327d9dbc4b8eaa
https://github.com/timofurrer/observable/blob/a6a764efaf9408a334bdb1ddf4327d9dbc4b8eaa/observable/property.py#L102-L108
25,861
timofurrer/observable
observable/core.py
Observable.get_all_handlers
def get_all_handlers(self) -> T.Dict[str, T.List[T.Callable]]: """Returns a dict with event names as keys and lists of registered handlers as values.""" events = {} for event, handlers in self._events.items(): events[event] = list(handlers) return events
python
def get_all_handlers(self) -> T.Dict[str, T.List[T.Callable]]: events = {} for event, handlers in self._events.items(): events[event] = list(handlers) return events
[ "def", "get_all_handlers", "(", "self", ")", "->", "T", ".", "Dict", "[", "str", ",", "T", ".", "List", "[", "T", ".", "Callable", "]", "]", ":", "events", "=", "{", "}", "for", "event", ",", "handlers", "in", "self", ".", "_events", ".", "items"...
Returns a dict with event names as keys and lists of registered handlers as values.
[ "Returns", "a", "dict", "with", "event", "names", "as", "keys", "and", "lists", "of", "registered", "handlers", "as", "values", "." ]
a6a764efaf9408a334bdb1ddf4327d9dbc4b8eaa
https://github.com/timofurrer/observable/blob/a6a764efaf9408a334bdb1ddf4327d9dbc4b8eaa/observable/core.py#L39-L46
25,862
timofurrer/observable
observable/core.py
Observable.get_handlers
def get_handlers(self, event: str) -> T.List[T.Callable]: """Returns a list of handlers registered for the given event.""" return list(self._events.get(event, []))
python
def get_handlers(self, event: str) -> T.List[T.Callable]: return list(self._events.get(event, []))
[ "def", "get_handlers", "(", "self", ",", "event", ":", "str", ")", "->", "T", ".", "List", "[", "T", ".", "Callable", "]", ":", "return", "list", "(", "self", ".", "_events", ".", "get", "(", "event", ",", "[", "]", ")", ")" ]
Returns a list of handlers registered for the given event.
[ "Returns", "a", "list", "of", "handlers", "registered", "for", "the", "given", "event", "." ]
a6a764efaf9408a334bdb1ddf4327d9dbc4b8eaa
https://github.com/timofurrer/observable/blob/a6a764efaf9408a334bdb1ddf4327d9dbc4b8eaa/observable/core.py#L48-L51
25,863
timofurrer/observable
observable/core.py
Observable.is_registered
def is_registered(self, event: str, handler: T.Callable) -> bool: """Returns whether the given handler is registered for the given event.""" return handler in self._events.get(event, [])
python
def is_registered(self, event: str, handler: T.Callable) -> bool: return handler in self._events.get(event, [])
[ "def", "is_registered", "(", "self", ",", "event", ":", "str", ",", "handler", ":", "T", ".", "Callable", ")", "->", "bool", ":", "return", "handler", "in", "self", ".", "_events", ".", "get", "(", "event", ",", "[", "]", ")" ]
Returns whether the given handler is registered for the given event.
[ "Returns", "whether", "the", "given", "handler", "is", "registered", "for", "the", "given", "event", "." ]
a6a764efaf9408a334bdb1ddf4327d9dbc4b8eaa
https://github.com/timofurrer/observable/blob/a6a764efaf9408a334bdb1ddf4327d9dbc4b8eaa/observable/core.py#L53-L57
25,864
timofurrer/observable
observable/core.py
Observable.on
def on( # pylint: disable=invalid-name self, event: str, *handlers: T.Callable ) -> T.Callable: """Registers one or more handlers to a specified event. This method may as well be used as a decorator for the handler.""" def _on_wrapper(*handlers: T.Callable) -> T.Callable: """wrapper for on decorator""" self._events[event].extend(handlers) return handlers[0] if handlers: return _on_wrapper(*handlers) return _on_wrapper
python
def on( # pylint: disable=invalid-name self, event: str, *handlers: T.Callable ) -> T.Callable: def _on_wrapper(*handlers: T.Callable) -> T.Callable: """wrapper for on decorator""" self._events[event].extend(handlers) return handlers[0] if handlers: return _on_wrapper(*handlers) return _on_wrapper
[ "def", "on", "(", "# pylint: disable=invalid-name", "self", ",", "event", ":", "str", ",", "*", "handlers", ":", "T", ".", "Callable", ")", "->", "T", ".", "Callable", ":", "def", "_on_wrapper", "(", "*", "handlers", ":", "T", ".", "Callable", ")", "->...
Registers one or more handlers to a specified event. This method may as well be used as a decorator for the handler.
[ "Registers", "one", "or", "more", "handlers", "to", "a", "specified", "event", ".", "This", "method", "may", "as", "well", "be", "used", "as", "a", "decorator", "for", "the", "handler", "." ]
a6a764efaf9408a334bdb1ddf4327d9dbc4b8eaa
https://github.com/timofurrer/observable/blob/a6a764efaf9408a334bdb1ddf4327d9dbc4b8eaa/observable/core.py#L59-L72
25,865
timofurrer/observable
observable/core.py
Observable.once
def once(self, event: str, *handlers: T.Callable) -> T.Callable: """Registers one or more handlers to a specified event, but removes them when the event is first triggered. This method may as well be used as a decorator for the handler.""" def _once_wrapper(*handlers: T.Callable) -> T.Callable: """Wrapper for 'once' decorator""" def _wrapper(*args: T.Any, **kw: T.Any) -> None: """Wrapper that unregisters itself before executing the handlers""" self.off(event, _wrapper) for handler in handlers: handler(*args, **kw) return _wrapper if handlers: return self.on(event, _once_wrapper(*handlers)) return lambda x: self.on(event, _once_wrapper(x))
python
def once(self, event: str, *handlers: T.Callable) -> T.Callable: def _once_wrapper(*handlers: T.Callable) -> T.Callable: """Wrapper for 'once' decorator""" def _wrapper(*args: T.Any, **kw: T.Any) -> None: """Wrapper that unregisters itself before executing the handlers""" self.off(event, _wrapper) for handler in handlers: handler(*args, **kw) return _wrapper if handlers: return self.on(event, _once_wrapper(*handlers)) return lambda x: self.on(event, _once_wrapper(x))
[ "def", "once", "(", "self", ",", "event", ":", "str", ",", "*", "handlers", ":", "T", ".", "Callable", ")", "->", "T", ".", "Callable", ":", "def", "_once_wrapper", "(", "*", "handlers", ":", "T", ".", "Callable", ")", "->", "T", ".", "Callable", ...
Registers one or more handlers to a specified event, but removes them when the event is first triggered. This method may as well be used as a decorator for the handler.
[ "Registers", "one", "or", "more", "handlers", "to", "a", "specified", "event", "but", "removes", "them", "when", "the", "event", "is", "first", "triggered", ".", "This", "method", "may", "as", "well", "be", "used", "as", "a", "decorator", "for", "the", "...
a6a764efaf9408a334bdb1ddf4327d9dbc4b8eaa
https://github.com/timofurrer/observable/blob/a6a764efaf9408a334bdb1ddf4327d9dbc4b8eaa/observable/core.py#L100-L120
25,866
timofurrer/observable
observable/core.py
Observable.trigger
def trigger(self, event: str, *args: T.Any, **kw: T.Any) -> bool: """Triggers all handlers which are subscribed to an event. Returns True when there were callbacks to execute, False otherwise.""" callbacks = list(self._events.get(event, [])) if not callbacks: return False for callback in callbacks: callback(*args, **kw) return True
python
def trigger(self, event: str, *args: T.Any, **kw: T.Any) -> bool: callbacks = list(self._events.get(event, [])) if not callbacks: return False for callback in callbacks: callback(*args, **kw) return True
[ "def", "trigger", "(", "self", ",", "event", ":", "str", ",", "*", "args", ":", "T", ".", "Any", ",", "*", "*", "kw", ":", "T", ".", "Any", ")", "->", "bool", ":", "callbacks", "=", "list", "(", "self", ".", "_events", ".", "get", "(", "event...
Triggers all handlers which are subscribed to an event. Returns True when there were callbacks to execute, False otherwise.
[ "Triggers", "all", "handlers", "which", "are", "subscribed", "to", "an", "event", ".", "Returns", "True", "when", "there", "were", "callbacks", "to", "execute", "False", "otherwise", "." ]
a6a764efaf9408a334bdb1ddf4327d9dbc4b8eaa
https://github.com/timofurrer/observable/blob/a6a764efaf9408a334bdb1ddf4327d9dbc4b8eaa/observable/core.py#L122-L132
25,867
jacobtomlinson/datapoint-python
datapoint/__init__.py
connection
def connection(profile_name='default', api_key=None): """Connect to DataPoint with the given API key profile name.""" if api_key is None: profile_fname = datapoint.profile.API_profile_fname(profile_name) if not os.path.exists(profile_fname): raise ValueError('Profile not found in {}. Please install your API \n' 'key with datapoint.profile.install_API_key(' '"<YOUR-KEY>")'.format(profile_fname)) with open(profile_fname) as fh: api_key = fh.readlines() return Manager(api_key=api_key)
python
def connection(profile_name='default', api_key=None): if api_key is None: profile_fname = datapoint.profile.API_profile_fname(profile_name) if not os.path.exists(profile_fname): raise ValueError('Profile not found in {}. Please install your API \n' 'key with datapoint.profile.install_API_key(' '"<YOUR-KEY>")'.format(profile_fname)) with open(profile_fname) as fh: api_key = fh.readlines() return Manager(api_key=api_key)
[ "def", "connection", "(", "profile_name", "=", "'default'", ",", "api_key", "=", "None", ")", ":", "if", "api_key", "is", "None", ":", "profile_fname", "=", "datapoint", ".", "profile", ".", "API_profile_fname", "(", "profile_name", ")", "if", "not", "os", ...
Connect to DataPoint with the given API key profile name.
[ "Connect", "to", "DataPoint", "with", "the", "given", "API", "key", "profile", "name", "." ]
1d3f596f21975f42c1484f5a9c3ff057de0b47ae
https://github.com/jacobtomlinson/datapoint-python/blob/1d3f596f21975f42c1484f5a9c3ff057de0b47ae/datapoint/__init__.py#L12-L22
25,868
jacobtomlinson/datapoint-python
datapoint/Timestep.py
Timestep.elements
def elements(self): """Return a list of the elements which are not None""" elements = [] for el in ct: if isinstance(el[1], datapoint.Element.Element): elements.append(el[1]) return elements
python
def elements(self): elements = [] for el in ct: if isinstance(el[1], datapoint.Element.Element): elements.append(el[1]) return elements
[ "def", "elements", "(", "self", ")", ":", "elements", "=", "[", "]", "for", "el", "in", "ct", ":", "if", "isinstance", "(", "el", "[", "1", "]", ",", "datapoint", ".", "Element", ".", "Element", ")", ":", "elements", ".", "append", "(", "el", "["...
Return a list of the elements which are not None
[ "Return", "a", "list", "of", "the", "elements", "which", "are", "not", "None" ]
1d3f596f21975f42c1484f5a9c3ff057de0b47ae
https://github.com/jacobtomlinson/datapoint-python/blob/1d3f596f21975f42c1484f5a9c3ff057de0b47ae/datapoint/Timestep.py#L25-L34
25,869
jacobtomlinson/datapoint-python
datapoint/Manager.py
Manager.__retry_session
def __retry_session(self, retries=10, backoff_factor=0.3, status_forcelist=(500, 502, 504), session=None): """ Retry the connection using requests if it fails. Use this as a wrapper to request from datapoint """ # requests.Session allows finer control, which is needed to use the # retrying code the_session = session or requests.Session() # The Retry object manages the actual retrying retry = Retry(total=retries, read=retries, connect=retries, backoff_factor=backoff_factor, status_forcelist=status_forcelist) adapter = HTTPAdapter(max_retries=retry) the_session.mount('http://', adapter) the_session.mount('https://', adapter) return the_session
python
def __retry_session(self, retries=10, backoff_factor=0.3, status_forcelist=(500, 502, 504), session=None): # requests.Session allows finer control, which is needed to use the # retrying code the_session = session or requests.Session() # The Retry object manages the actual retrying retry = Retry(total=retries, read=retries, connect=retries, backoff_factor=backoff_factor, status_forcelist=status_forcelist) adapter = HTTPAdapter(max_retries=retry) the_session.mount('http://', adapter) the_session.mount('https://', adapter) return the_session
[ "def", "__retry_session", "(", "self", ",", "retries", "=", "10", ",", "backoff_factor", "=", "0.3", ",", "status_forcelist", "=", "(", "500", ",", "502", ",", "504", ")", ",", "session", "=", "None", ")", ":", "# requests.Session allows finer control, which i...
Retry the connection using requests if it fails. Use this as a wrapper to request from datapoint
[ "Retry", "the", "connection", "using", "requests", "if", "it", "fails", ".", "Use", "this", "as", "a", "wrapper", "to", "request", "from", "datapoint" ]
1d3f596f21975f42c1484f5a9c3ff057de0b47ae
https://github.com/jacobtomlinson/datapoint-python/blob/1d3f596f21975f42c1484f5a9c3ff057de0b47ae/datapoint/Manager.py#L109-L131
25,870
jacobtomlinson/datapoint-python
datapoint/Manager.py
Manager.__call_api
def __call_api(self, path, params=None, api_url=FORECAST_URL): """ Call the datapoint api using the requests module """ if not params: params = dict() payload = {'key': self.api_key} payload.update(params) url = "%s/%s" % (api_url, path) # Add a timeout to the request. # The value of 1 second is based on attempting 100 connections to # datapoint and taking ten times the mean connection time (rounded up). # Could expose to users in the functions which need to call the api. #req = requests.get(url, params=payload, timeout=1) # The wrapper function __retry_session returns a requests.Session # object. This has a .get() function like requests.get(), so the use # doesn't change here. sess = self.__retry_session() req = sess.get(url, params=payload, timeout=1) try: data = req.json() except ValueError: raise APIException("DataPoint has not returned any data, this could be due to an incorrect API key") self.call_response = data if req.status_code != 200: msg = [data[m] for m in ("message", "error_message", "status") \ if m in data][0] raise Exception(msg) return data
python
def __call_api(self, path, params=None, api_url=FORECAST_URL): if not params: params = dict() payload = {'key': self.api_key} payload.update(params) url = "%s/%s" % (api_url, path) # Add a timeout to the request. # The value of 1 second is based on attempting 100 connections to # datapoint and taking ten times the mean connection time (rounded up). # Could expose to users in the functions which need to call the api. #req = requests.get(url, params=payload, timeout=1) # The wrapper function __retry_session returns a requests.Session # object. This has a .get() function like requests.get(), so the use # doesn't change here. sess = self.__retry_session() req = sess.get(url, params=payload, timeout=1) try: data = req.json() except ValueError: raise APIException("DataPoint has not returned any data, this could be due to an incorrect API key") self.call_response = data if req.status_code != 200: msg = [data[m] for m in ("message", "error_message", "status") \ if m in data][0] raise Exception(msg) return data
[ "def", "__call_api", "(", "self", ",", "path", ",", "params", "=", "None", ",", "api_url", "=", "FORECAST_URL", ")", ":", "if", "not", "params", ":", "params", "=", "dict", "(", ")", "payload", "=", "{", "'key'", ":", "self", ".", "api_key", "}", "...
Call the datapoint api using the requests module
[ "Call", "the", "datapoint", "api", "using", "the", "requests", "module" ]
1d3f596f21975f42c1484f5a9c3ff057de0b47ae
https://github.com/jacobtomlinson/datapoint-python/blob/1d3f596f21975f42c1484f5a9c3ff057de0b47ae/datapoint/Manager.py#L133-L165
25,871
jacobtomlinson/datapoint-python
datapoint/Manager.py
Manager._get_wx_units
def _get_wx_units(self, params, name): """ Give the Wx array returned from datapoint and an element name and return the units for that element. """ units = "" for param in params: if str(name) == str(param['name']): units = param['units'] return units
python
def _get_wx_units(self, params, name): units = "" for param in params: if str(name) == str(param['name']): units = param['units'] return units
[ "def", "_get_wx_units", "(", "self", ",", "params", ",", "name", ")", ":", "units", "=", "\"\"", "for", "param", "in", "params", ":", "if", "str", "(", "name", ")", "==", "str", "(", "param", "[", "'name'", "]", ")", ":", "units", "=", "param", "...
Give the Wx array returned from datapoint and an element name and return the units for that element.
[ "Give", "the", "Wx", "array", "returned", "from", "datapoint", "and", "an", "element", "name", "and", "return", "the", "units", "for", "that", "element", "." ]
1d3f596f21975f42c1484f5a9c3ff057de0b47ae
https://github.com/jacobtomlinson/datapoint-python/blob/1d3f596f21975f42c1484f5a9c3ff057de0b47ae/datapoint/Manager.py#L188-L197
25,872
jacobtomlinson/datapoint-python
datapoint/Manager.py
Manager._visibility_to_text
def _visibility_to_text(self, distance): """ Convert observed visibility in metres to text used in forecast """ if not isinstance(distance, (int, long)): raise ValueError("Distance must be an integer not", type(distance)) if distance < 0: raise ValueError("Distance out of bounds, should be 0 or greater") if 0 <= distance < 1000: return 'VP' elif 1000 <= distance < 4000: return 'PO' elif 4000 <= distance < 10000: return 'MO' elif 10000 <= distance < 20000: return 'GO' elif 20000 <= distance < 40000: return 'VG' else: return 'EX'
python
def _visibility_to_text(self, distance): if not isinstance(distance, (int, long)): raise ValueError("Distance must be an integer not", type(distance)) if distance < 0: raise ValueError("Distance out of bounds, should be 0 or greater") if 0 <= distance < 1000: return 'VP' elif 1000 <= distance < 4000: return 'PO' elif 4000 <= distance < 10000: return 'MO' elif 10000 <= distance < 20000: return 'GO' elif 20000 <= distance < 40000: return 'VG' else: return 'EX'
[ "def", "_visibility_to_text", "(", "self", ",", "distance", ")", ":", "if", "not", "isinstance", "(", "distance", ",", "(", "int", ",", "long", ")", ")", ":", "raise", "ValueError", "(", "\"Distance must be an integer not\"", ",", "type", "(", "distance", ")...
Convert observed visibility in metres to text used in forecast
[ "Convert", "observed", "visibility", "in", "metres", "to", "text", "used", "in", "forecast" ]
1d3f596f21975f42c1484f5a9c3ff057de0b47ae
https://github.com/jacobtomlinson/datapoint-python/blob/1d3f596f21975f42c1484f5a9c3ff057de0b47ae/datapoint/Manager.py#L207-L228
25,873
jacobtomlinson/datapoint-python
datapoint/Manager.py
Manager.get_forecast_sites
def get_forecast_sites(self): """ This function returns a list of Site object. """ time_now = time() if (time_now - self.forecast_sites_last_update) > self.forecast_sites_update_time or self.forecast_sites_last_request is None: data = self.__call_api("sitelist/") sites = list() for jsoned in data['Locations']['Location']: site = Site() site.name = jsoned['name'] site.id = jsoned['id'] site.latitude = jsoned['latitude'] site.longitude = jsoned['longitude'] if 'region' in jsoned: site.region = jsoned['region'] if 'elevation' in jsoned: site.elevation = jsoned['elevation'] if 'unitaryAuthArea' in jsoned: site.unitaryAuthArea = jsoned['unitaryAuthArea'] if 'nationalPark' in jsoned: site.nationalPark = jsoned['nationalPark'] site.api_key = self.api_key sites.append(site) self.forecast_sites_last_request = sites # Only set self.sites_last_update once self.sites_last_request has # been set self.forecast_sites_last_update = time_now else: sites = self.forecast_sites_last_request return sites
python
def get_forecast_sites(self): time_now = time() if (time_now - self.forecast_sites_last_update) > self.forecast_sites_update_time or self.forecast_sites_last_request is None: data = self.__call_api("sitelist/") sites = list() for jsoned in data['Locations']['Location']: site = Site() site.name = jsoned['name'] site.id = jsoned['id'] site.latitude = jsoned['latitude'] site.longitude = jsoned['longitude'] if 'region' in jsoned: site.region = jsoned['region'] if 'elevation' in jsoned: site.elevation = jsoned['elevation'] if 'unitaryAuthArea' in jsoned: site.unitaryAuthArea = jsoned['unitaryAuthArea'] if 'nationalPark' in jsoned: site.nationalPark = jsoned['nationalPark'] site.api_key = self.api_key sites.append(site) self.forecast_sites_last_request = sites # Only set self.sites_last_update once self.sites_last_request has # been set self.forecast_sites_last_update = time_now else: sites = self.forecast_sites_last_request return sites
[ "def", "get_forecast_sites", "(", "self", ")", ":", "time_now", "=", "time", "(", ")", "if", "(", "time_now", "-", "self", ".", "forecast_sites_last_update", ")", ">", "self", ".", "forecast_sites_update_time", "or", "self", ".", "forecast_sites_last_request", "...
This function returns a list of Site object.
[ "This", "function", "returns", "a", "list", "of", "Site", "object", "." ]
1d3f596f21975f42c1484f5a9c3ff057de0b47ae
https://github.com/jacobtomlinson/datapoint-python/blob/1d3f596f21975f42c1484f5a9c3ff057de0b47ae/datapoint/Manager.py#L239-L278
25,874
jacobtomlinson/datapoint-python
datapoint/Manager.py
Manager.get_nearest_site
def get_nearest_site(self, latitude=None, longitude=None): """ Deprecated. This function returns nearest Site object to the specified coordinates. """ warning_message = 'This function is deprecated. Use get_nearest_forecast_site() instead' warn(warning_message, DeprecationWarning, stacklevel=2) return self.get_nearest_forecast_site(latitude, longitude)
python
def get_nearest_site(self, latitude=None, longitude=None): warning_message = 'This function is deprecated. Use get_nearest_forecast_site() instead' warn(warning_message, DeprecationWarning, stacklevel=2) return self.get_nearest_forecast_site(latitude, longitude)
[ "def", "get_nearest_site", "(", "self", ",", "latitude", "=", "None", ",", "longitude", "=", "None", ")", ":", "warning_message", "=", "'This function is deprecated. Use get_nearest_forecast_site() instead'", "warn", "(", "warning_message", ",", "DeprecationWarning", ",",...
Deprecated. This function returns nearest Site object to the specified coordinates.
[ "Deprecated", ".", "This", "function", "returns", "nearest", "Site", "object", "to", "the", "specified", "coordinates", "." ]
1d3f596f21975f42c1484f5a9c3ff057de0b47ae
https://github.com/jacobtomlinson/datapoint-python/blob/1d3f596f21975f42c1484f5a9c3ff057de0b47ae/datapoint/Manager.py#L280-L288
25,875
jacobtomlinson/datapoint-python
datapoint/Manager.py
Manager.get_nearest_forecast_site
def get_nearest_forecast_site(self, latitude=None, longitude=None): """ This function returns the nearest Site object to the specified coordinates. """ if longitude is None: print('ERROR: No latitude given.') return False if latitude is None: print('ERROR: No latitude given.') return False nearest = False distance = None sites = self.get_forecast_sites() # Sometimes there is a TypeError exception here: sites is None # So, sometimes self.get_all_sites() has returned None. for site in sites: new_distance = \ self._distance_between_coords( float(site.longitude), float(site.latitude), float(longitude), float(latitude)) if ((distance == None) or (new_distance < distance)): distance = new_distance nearest = site # If the nearest site is more than 30km away, raise an error if distance > 30: raise APIException("There is no site within 30km.") return nearest
python
def get_nearest_forecast_site(self, latitude=None, longitude=None): if longitude is None: print('ERROR: No latitude given.') return False if latitude is None: print('ERROR: No latitude given.') return False nearest = False distance = None sites = self.get_forecast_sites() # Sometimes there is a TypeError exception here: sites is None # So, sometimes self.get_all_sites() has returned None. for site in sites: new_distance = \ self._distance_between_coords( float(site.longitude), float(site.latitude), float(longitude), float(latitude)) if ((distance == None) or (new_distance < distance)): distance = new_distance nearest = site # If the nearest site is more than 30km away, raise an error if distance > 30: raise APIException("There is no site within 30km.") return nearest
[ "def", "get_nearest_forecast_site", "(", "self", ",", "latitude", "=", "None", ",", "longitude", "=", "None", ")", ":", "if", "longitude", "is", "None", ":", "print", "(", "'ERROR: No latitude given.'", ")", "return", "False", "if", "latitude", "is", "None", ...
This function returns the nearest Site object to the specified coordinates.
[ "This", "function", "returns", "the", "nearest", "Site", "object", "to", "the", "specified", "coordinates", "." ]
1d3f596f21975f42c1484f5a9c3ff057de0b47ae
https://github.com/jacobtomlinson/datapoint-python/blob/1d3f596f21975f42c1484f5a9c3ff057de0b47ae/datapoint/Manager.py#L290-L325
25,876
jacobtomlinson/datapoint-python
datapoint/Manager.py
Manager.get_observation_sites
def get_observation_sites(self): """ This function returns a list of Site objects for which observations are available. """ if (time() - self.observation_sites_last_update) > self.observation_sites_update_time: self.observation_sites_last_update = time() data = self.__call_api("sitelist/", None, OBSERVATION_URL) sites = list() for jsoned in data['Locations']['Location']: site = Site() site.name = jsoned['name'] site.id = jsoned['id'] site.latitude = jsoned['latitude'] site.longitude = jsoned['longitude'] if 'region' in jsoned: site.region = jsoned['region'] if 'elevation' in jsoned: site.elevation = jsoned['elevation'] if 'unitaryAuthArea' in jsoned: site.unitaryAuthArea = jsoned['unitaryAuthArea'] if 'nationalPark' in jsoned: site.nationalPark = jsoned['nationalPark'] site.api_key = self.api_key sites.append(site) self.observation_sites_last_request = sites else: sites = observation_self.sites_last_request return sites
python
def get_observation_sites(self): if (time() - self.observation_sites_last_update) > self.observation_sites_update_time: self.observation_sites_last_update = time() data = self.__call_api("sitelist/", None, OBSERVATION_URL) sites = list() for jsoned in data['Locations']['Location']: site = Site() site.name = jsoned['name'] site.id = jsoned['id'] site.latitude = jsoned['latitude'] site.longitude = jsoned['longitude'] if 'region' in jsoned: site.region = jsoned['region'] if 'elevation' in jsoned: site.elevation = jsoned['elevation'] if 'unitaryAuthArea' in jsoned: site.unitaryAuthArea = jsoned['unitaryAuthArea'] if 'nationalPark' in jsoned: site.nationalPark = jsoned['nationalPark'] site.api_key = self.api_key sites.append(site) self.observation_sites_last_request = sites else: sites = observation_self.sites_last_request return sites
[ "def", "get_observation_sites", "(", "self", ")", ":", "if", "(", "time", "(", ")", "-", "self", ".", "observation_sites_last_update", ")", ">", "self", ".", "observation_sites_update_time", ":", "self", ".", "observation_sites_last_update", "=", "time", "(", ")...
This function returns a list of Site objects for which observations are available.
[ "This", "function", "returns", "a", "list", "of", "Site", "objects", "for", "which", "observations", "are", "available", "." ]
1d3f596f21975f42c1484f5a9c3ff057de0b47ae
https://github.com/jacobtomlinson/datapoint-python/blob/1d3f596f21975f42c1484f5a9c3ff057de0b47ae/datapoint/Manager.py#L433-L467
25,877
jacobtomlinson/datapoint-python
datapoint/Manager.py
Manager.get_nearest_observation_site
def get_nearest_observation_site(self, latitude=None, longitude=None): """ This function returns the nearest Site to the specified coordinates that supports observations """ if longitude is None: print('ERROR: No longitude given.') return False if latitude is None: print('ERROR: No latitude given.') return False nearest = False distance = None sites = self.get_observation_sites() for site in sites: new_distance = \ self._distance_between_coords( float(site.longitude), float(site.latitude), float(longitude), float(latitude)) if ((distance == None) or (new_distance < distance)): distance = new_distance nearest = site # If the nearest site is more than 20km away, raise an error if distance > 20: raise APIException("There is no site within 30km.") return nearest
python
def get_nearest_observation_site(self, latitude=None, longitude=None): if longitude is None: print('ERROR: No longitude given.') return False if latitude is None: print('ERROR: No latitude given.') return False nearest = False distance = None sites = self.get_observation_sites() for site in sites: new_distance = \ self._distance_between_coords( float(site.longitude), float(site.latitude), float(longitude), float(latitude)) if ((distance == None) or (new_distance < distance)): distance = new_distance nearest = site # If the nearest site is more than 20km away, raise an error if distance > 20: raise APIException("There is no site within 30km.") return nearest
[ "def", "get_nearest_observation_site", "(", "self", ",", "latitude", "=", "None", ",", "longitude", "=", "None", ")", ":", "if", "longitude", "is", "None", ":", "print", "(", "'ERROR: No longitude given.'", ")", "return", "False", "if", "latitude", "is", "None...
This function returns the nearest Site to the specified coordinates that supports observations
[ "This", "function", "returns", "the", "nearest", "Site", "to", "the", "specified", "coordinates", "that", "supports", "observations" ]
1d3f596f21975f42c1484f5a9c3ff057de0b47ae
https://github.com/jacobtomlinson/datapoint-python/blob/1d3f596f21975f42c1484f5a9c3ff057de0b47ae/datapoint/Manager.py#L469-L501
25,878
jacobtomlinson/datapoint-python
datapoint/regions/RegionManager.py
RegionManager.call_api
def call_api(self, path, **kwargs): ''' Call datapoint api ''' if 'key' not in kwargs: kwargs['key'] = self.api_key req = requests.get('{0}{1}'.format(self.base_url, path), params=kwargs) if req.status_code != requests.codes.ok: req.raise_for_status() return req.json()
python
def call_api(self, path, **kwargs): ''' Call datapoint api ''' if 'key' not in kwargs: kwargs['key'] = self.api_key req = requests.get('{0}{1}'.format(self.base_url, path), params=kwargs) if req.status_code != requests.codes.ok: req.raise_for_status() return req.json()
[ "def", "call_api", "(", "self", ",", "path", ",", "*", "*", "kwargs", ")", ":", "if", "'key'", "not", "in", "kwargs", ":", "kwargs", "[", "'key'", "]", "=", "self", ".", "api_key", "req", "=", "requests", ".", "get", "(", "'{0}{1}'", ".", "format",...
Call datapoint api
[ "Call", "datapoint", "api" ]
1d3f596f21975f42c1484f5a9c3ff057de0b47ae
https://github.com/jacobtomlinson/datapoint-python/blob/1d3f596f21975f42c1484f5a9c3ff057de0b47ae/datapoint/regions/RegionManager.py#L27-L38
25,879
jacobtomlinson/datapoint-python
datapoint/regions/RegionManager.py
RegionManager.get_all_regions
def get_all_regions(self): ''' Request a list of regions from Datapoint. Returns each Region as a Site object. Regions rarely change, so we cache the response for one hour to minimise requests to API. ''' if (time() - self.regions_last_update) < self.regions_update_time: return self.regions_last_request response = self.call_api(self.all_regions_path) regions = [] for location in response['Locations']['Location']: region = Site() region.id = location['@id'] region.region = location['@name'] region.name = REGION_NAMES[location['@name']] regions.append(region) self.regions_last_update = time() self.regions_last_request = regions return regions
python
def get_all_regions(self): ''' Request a list of regions from Datapoint. Returns each Region as a Site object. Regions rarely change, so we cache the response for one hour to minimise requests to API. ''' if (time() - self.regions_last_update) < self.regions_update_time: return self.regions_last_request response = self.call_api(self.all_regions_path) regions = [] for location in response['Locations']['Location']: region = Site() region.id = location['@id'] region.region = location['@name'] region.name = REGION_NAMES[location['@name']] regions.append(region) self.regions_last_update = time() self.regions_last_request = regions return regions
[ "def", "get_all_regions", "(", "self", ")", ":", "if", "(", "time", "(", ")", "-", "self", ".", "regions_last_update", ")", "<", "self", ".", "regions_update_time", ":", "return", "self", ".", "regions_last_request", "response", "=", "self", ".", "call_api",...
Request a list of regions from Datapoint. Returns each Region as a Site object. Regions rarely change, so we cache the response for one hour to minimise requests to API.
[ "Request", "a", "list", "of", "regions", "from", "Datapoint", ".", "Returns", "each", "Region", "as", "a", "Site", "object", ".", "Regions", "rarely", "change", "so", "we", "cache", "the", "response", "for", "one", "hour", "to", "minimise", "requests", "to...
1d3f596f21975f42c1484f5a9c3ff057de0b47ae
https://github.com/jacobtomlinson/datapoint-python/blob/1d3f596f21975f42c1484f5a9c3ff057de0b47ae/datapoint/regions/RegionManager.py#L40-L60
25,880
jacobtomlinson/datapoint-python
datapoint/Forecast.py
Forecast.now
def now(self): """ Function to return just the current timestep from this forecast """ # From the comments in issue 19: forecast.days[0] is dated for the # previous day shortly after midnight now = None # Set the time now to be in the same time zone as the first timestep in # the forecast. This shouldn't cause problems with daylight savings as # the change is far enough after midnight. d = datetime.datetime.now(tz=self.days[0].date.tzinfo) # d is something like datetime.datetime(2019, 1, 19, 17, 5, 28, 337439) # d.replace(...) is datetime.datetime(2019, 1, 19, 0, 0) # for_total_seconds is then: datetime.timedelta(seconds=61528, # microseconds=337439) # In this example, this is (17*60*60) + (5*60) + 28 = 61528 # this is the number of seconds through the day for_total_seconds = d - \ d.replace(hour=0, minute=0, second=0, microsecond=0) # In the example time, # for_total_seconds.total_seconds() = 61528 + 0.337439 # This is the number of seconds after midnight # msm is then the number of minutes after midnight msm = for_total_seconds.total_seconds() / 60 # If the date now and the date in the forecast are the same, proceed if self.days[0].date.strftime("%Y-%m-%dZ") == d.strftime("%Y-%m-%dZ"): # We have determined that the date in the forecast and the date now # are the same. # # Now, test if timestep.name is larger than the number of minutes # since midnight for each timestep. # The timestep we keep is the one with the largest timestep.name # which is less than the number of minutes since midnight for timestep in self.days[0].timesteps: if timestep.name > msm: # break here stops the for loop break # now is assigned to the last timestep that did not break the # loop now = timestep return now # Bodge to get around problems near midnight: # Previous method does not account for the end of the month. The test # trying to be evaluated is that the absolute difference between the # last timestep of the first day and the current time is less than 4 # hours. 4 hours is because the final timestep of the previous day is # for 21:00 elif abs(self.days[0].timesteps[-1].date - d).total_seconds() < 14400: # This is verbose to check that the returned data makes sense timestep_to_return = self.days[0].timesteps[-1] return timestep_to_return else: return False
python
def now(self): # From the comments in issue 19: forecast.days[0] is dated for the # previous day shortly after midnight now = None # Set the time now to be in the same time zone as the first timestep in # the forecast. This shouldn't cause problems with daylight savings as # the change is far enough after midnight. d = datetime.datetime.now(tz=self.days[0].date.tzinfo) # d is something like datetime.datetime(2019, 1, 19, 17, 5, 28, 337439) # d.replace(...) is datetime.datetime(2019, 1, 19, 0, 0) # for_total_seconds is then: datetime.timedelta(seconds=61528, # microseconds=337439) # In this example, this is (17*60*60) + (5*60) + 28 = 61528 # this is the number of seconds through the day for_total_seconds = d - \ d.replace(hour=0, minute=0, second=0, microsecond=0) # In the example time, # for_total_seconds.total_seconds() = 61528 + 0.337439 # This is the number of seconds after midnight # msm is then the number of minutes after midnight msm = for_total_seconds.total_seconds() / 60 # If the date now and the date in the forecast are the same, proceed if self.days[0].date.strftime("%Y-%m-%dZ") == d.strftime("%Y-%m-%dZ"): # We have determined that the date in the forecast and the date now # are the same. # # Now, test if timestep.name is larger than the number of minutes # since midnight for each timestep. # The timestep we keep is the one with the largest timestep.name # which is less than the number of minutes since midnight for timestep in self.days[0].timesteps: if timestep.name > msm: # break here stops the for loop break # now is assigned to the last timestep that did not break the # loop now = timestep return now # Bodge to get around problems near midnight: # Previous method does not account for the end of the month. The test # trying to be evaluated is that the absolute difference between the # last timestep of the first day and the current time is less than 4 # hours. 4 hours is because the final timestep of the previous day is # for 21:00 elif abs(self.days[0].timesteps[-1].date - d).total_seconds() < 14400: # This is verbose to check that the returned data makes sense timestep_to_return = self.days[0].timesteps[-1] return timestep_to_return else: return False
[ "def", "now", "(", "self", ")", ":", "# From the comments in issue 19: forecast.days[0] is dated for the", "# previous day shortly after midnight", "now", "=", "None", "# Set the time now to be in the same time zone as the first timestep in", "# the forecast. This shouldn't cause problems wi...
Function to return just the current timestep from this forecast
[ "Function", "to", "return", "just", "the", "current", "timestep", "from", "this", "forecast" ]
1d3f596f21975f42c1484f5a9c3ff057de0b47ae
https://github.com/jacobtomlinson/datapoint-python/blob/1d3f596f21975f42c1484f5a9c3ff057de0b47ae/datapoint/Forecast.py#L22-L80
25,881
jacobtomlinson/datapoint-python
datapoint/Forecast.py
Forecast.future
def future(self,in_days=None,in_hours=None,in_minutes=None,in_seconds=None): """ Function to return a future timestep """ future = None # Initialize variables to 0 dd, hh, mm, ss = [0 for i in range(4)] if (in_days != None): dd = dd + in_days if (in_hours != None): hh = hh + in_hours if (in_minutes != None): mm = mm + in_minutes if (in_seconds != None): ss = ss + in_seconds # Set the hours, minutes and seconds from now (minus the days) dnow = datetime.datetime.utcnow() # Now d = dnow + \ datetime.timedelta(hours=hh, minutes=mm, seconds = ss) # Time from midnight for_total_seconds = d - \ d.replace(hour=0, minute=0, second=0, microsecond=0) # Convert into minutes since midnight try: msm = for_total_seconds.total_seconds()/60. except: # For versions before 2.7 msm = self.timedelta_total_seconds(for_total_seconds)/60. if (dd<len(self.days)): for timestep in self.days[dd].timesteps: if timestep.name >= msm: future = timestep return future else: print('ERROR: requested date is outside the forecast range selected,' + str(len(self.days))) return False
python
def future(self,in_days=None,in_hours=None,in_minutes=None,in_seconds=None): future = None # Initialize variables to 0 dd, hh, mm, ss = [0 for i in range(4)] if (in_days != None): dd = dd + in_days if (in_hours != None): hh = hh + in_hours if (in_minutes != None): mm = mm + in_minutes if (in_seconds != None): ss = ss + in_seconds # Set the hours, minutes and seconds from now (minus the days) dnow = datetime.datetime.utcnow() # Now d = dnow + \ datetime.timedelta(hours=hh, minutes=mm, seconds = ss) # Time from midnight for_total_seconds = d - \ d.replace(hour=0, minute=0, second=0, microsecond=0) # Convert into minutes since midnight try: msm = for_total_seconds.total_seconds()/60. except: # For versions before 2.7 msm = self.timedelta_total_seconds(for_total_seconds)/60. if (dd<len(self.days)): for timestep in self.days[dd].timesteps: if timestep.name >= msm: future = timestep return future else: print('ERROR: requested date is outside the forecast range selected,' + str(len(self.days))) return False
[ "def", "future", "(", "self", ",", "in_days", "=", "None", ",", "in_hours", "=", "None", ",", "in_minutes", "=", "None", ",", "in_seconds", "=", "None", ")", ":", "future", "=", "None", "# Initialize variables to 0", "dd", ",", "hh", ",", "mm", ",", "s...
Function to return a future timestep
[ "Function", "to", "return", "a", "future", "timestep" ]
1d3f596f21975f42c1484f5a9c3ff057de0b47ae
https://github.com/jacobtomlinson/datapoint-python/blob/1d3f596f21975f42c1484f5a9c3ff057de0b47ae/datapoint/Forecast.py#L82-L121
25,882
jacobtomlinson/datapoint-python
datapoint/profile.py
install_API_key
def install_API_key(api_key, profile_name='default'): """Put the given API key into the given profile name.""" fname = API_profile_fname(profile_name) if not os.path.isdir(os.path.dirname(fname)): os.makedirs(os.path.dirname(fname)) with open(fname, 'w') as fh: fh.write(api_key)
python
def install_API_key(api_key, profile_name='default'): fname = API_profile_fname(profile_name) if not os.path.isdir(os.path.dirname(fname)): os.makedirs(os.path.dirname(fname)) with open(fname, 'w') as fh: fh.write(api_key)
[ "def", "install_API_key", "(", "api_key", ",", "profile_name", "=", "'default'", ")", ":", "fname", "=", "API_profile_fname", "(", "profile_name", ")", "if", "not", "os", ".", "path", ".", "isdir", "(", "os", ".", "path", ".", "dirname", "(", "fname", ")...
Put the given API key into the given profile name.
[ "Put", "the", "given", "API", "key", "into", "the", "given", "profile", "name", "." ]
1d3f596f21975f42c1484f5a9c3ff057de0b47ae
https://github.com/jacobtomlinson/datapoint-python/blob/1d3f596f21975f42c1484f5a9c3ff057de0b47ae/datapoint/profile.py#L12-L18
25,883
ltworf/typedload
typedload/typechecks.py
is_namedtuple
def is_namedtuple(type_: Type[Any]) -> bool: ''' Generated with typing.NamedTuple ''' return _issubclass(type_, tuple) and hasattr(type_, '_field_types') and hasattr(type_, '_fields')
python
def is_namedtuple(type_: Type[Any]) -> bool: ''' Generated with typing.NamedTuple ''' return _issubclass(type_, tuple) and hasattr(type_, '_field_types') and hasattr(type_, '_fields')
[ "def", "is_namedtuple", "(", "type_", ":", "Type", "[", "Any", "]", ")", "->", "bool", ":", "return", "_issubclass", "(", "type_", ",", "tuple", ")", "and", "hasattr", "(", "type_", ",", "'_field_types'", ")", "and", "hasattr", "(", "type_", ",", "'_fi...
Generated with typing.NamedTuple
[ "Generated", "with", "typing", ".", "NamedTuple" ]
7fd130612963bfcec3242698463ef863ca4af927
https://github.com/ltworf/typedload/blob/7fd130612963bfcec3242698463ef863ca4af927/typedload/typechecks.py#L168-L172
25,884
ltworf/typedload
typedload/typechecks.py
uniontypes
def uniontypes(type_: Type[Any]) -> Set[Type[Any]]: ''' Returns the types of a Union. Raises ValueError if the argument is not a Union and AttributeError when running on an unsupported Python version. ''' if not is_union(type_): raise ValueError('Not a Union: ' + str(type_)) if hasattr(type_, '__args__'): return set(type_.__args__) elif hasattr(type_, '__union_params__'): return set(type_.__union_params__) raise AttributeError('The typing API for this Python version is unknown')
python
def uniontypes(type_: Type[Any]) -> Set[Type[Any]]: ''' Returns the types of a Union. Raises ValueError if the argument is not a Union and AttributeError when running on an unsupported Python version. ''' if not is_union(type_): raise ValueError('Not a Union: ' + str(type_)) if hasattr(type_, '__args__'): return set(type_.__args__) elif hasattr(type_, '__union_params__'): return set(type_.__union_params__) raise AttributeError('The typing API for this Python version is unknown')
[ "def", "uniontypes", "(", "type_", ":", "Type", "[", "Any", "]", ")", "->", "Set", "[", "Type", "[", "Any", "]", "]", ":", "if", "not", "is_union", "(", "type_", ")", ":", "raise", "ValueError", "(", "'Not a Union: '", "+", "str", "(", "type_", ")"...
Returns the types of a Union. Raises ValueError if the argument is not a Union and AttributeError when running on an unsupported Python version.
[ "Returns", "the", "types", "of", "a", "Union", "." ]
7fd130612963bfcec3242698463ef863ca4af927
https://github.com/ltworf/typedload/blob/7fd130612963bfcec3242698463ef863ca4af927/typedload/typechecks.py#L200-L215
25,885
ltworf/typedload
typedload/datadumper.py
Dumper.index
def index(self, value: Any) -> int: """ Returns the index in the handlers list that matches the given value. If no condition matches, ValueError is raised. """ for i, cond in ((j[0], j[1][0]) for j in enumerate(self.handlers)): try: match = cond(value) except: if self.raiseconditionerrors: raise match = False if match: return i raise TypedloadValueError('Unable to dump %s' % value, value=value)
python
def index(self, value: Any) -> int: for i, cond in ((j[0], j[1][0]) for j in enumerate(self.handlers)): try: match = cond(value) except: if self.raiseconditionerrors: raise match = False if match: return i raise TypedloadValueError('Unable to dump %s' % value, value=value)
[ "def", "index", "(", "self", ",", "value", ":", "Any", ")", "->", "int", ":", "for", "i", ",", "cond", "in", "(", "(", "j", "[", "0", "]", ",", "j", "[", "1", "]", "[", "0", "]", ")", "for", "j", "in", "enumerate", "(", "self", ".", "hand...
Returns the index in the handlers list that matches the given value. If no condition matches, ValueError is raised.
[ "Returns", "the", "index", "in", "the", "handlers", "list", "that", "matches", "the", "given", "value", "." ]
7fd130612963bfcec3242698463ef863ca4af927
https://github.com/ltworf/typedload/blob/7fd130612963bfcec3242698463ef863ca4af927/typedload/datadumper.py#L111-L127
25,886
ltworf/typedload
typedload/datadumper.py
Dumper.dump
def dump(self, value: Any) -> Any: """ Dump the typed data structure into its untyped equivalent. """ index = self.index(value) func = self.handlers[index][1] return func(self, value)
python
def dump(self, value: Any) -> Any: index = self.index(value) func = self.handlers[index][1] return func(self, value)
[ "def", "dump", "(", "self", ",", "value", ":", "Any", ")", "->", "Any", ":", "index", "=", "self", ".", "index", "(", "value", ")", "func", "=", "self", ".", "handlers", "[", "index", "]", "[", "1", "]", "return", "func", "(", "self", ",", "val...
Dump the typed data structure into its untyped equivalent.
[ "Dump", "the", "typed", "data", "structure", "into", "its", "untyped", "equivalent", "." ]
7fd130612963bfcec3242698463ef863ca4af927
https://github.com/ltworf/typedload/blob/7fd130612963bfcec3242698463ef863ca4af927/typedload/datadumper.py#L129-L136
25,887
ltworf/typedload
typedload/dataloader.py
_forwardrefload
def _forwardrefload(l: Loader, value: Any, type_: type) -> Any: """ This resolves a ForwardRef. It just looks up the type in the dictionary of known types and loads the value using that. """ if l.frefs is None: raise TypedloadException('ForwardRef resolving is disabled for the loader', value=value, type_=type_) tname = type_.__forward_arg__ # type: ignore t = l.frefs.get(tname) if t is None: raise TypedloadValueError( "ForwardRef '%s' unknown" % tname, value=value, type_=type_ ) return l.load(value, t, annotation=Annotation(AnnotationType.FORWARDREF, tname))
python
def _forwardrefload(l: Loader, value: Any, type_: type) -> Any: if l.frefs is None: raise TypedloadException('ForwardRef resolving is disabled for the loader', value=value, type_=type_) tname = type_.__forward_arg__ # type: ignore t = l.frefs.get(tname) if t is None: raise TypedloadValueError( "ForwardRef '%s' unknown" % tname, value=value, type_=type_ ) return l.load(value, t, annotation=Annotation(AnnotationType.FORWARDREF, tname))
[ "def", "_forwardrefload", "(", "l", ":", "Loader", ",", "value", ":", "Any", ",", "type_", ":", "type", ")", "->", "Any", ":", "if", "l", ".", "frefs", "is", "None", ":", "raise", "TypedloadException", "(", "'ForwardRef resolving is disabled for the loader'", ...
This resolves a ForwardRef. It just looks up the type in the dictionary of known types and loads the value using that.
[ "This", "resolves", "a", "ForwardRef", "." ]
7fd130612963bfcec3242698463ef863ca4af927
https://github.com/ltworf/typedload/blob/7fd130612963bfcec3242698463ef863ca4af927/typedload/dataloader.py#L223-L240
25,888
ltworf/typedload
typedload/dataloader.py
_basicload
def _basicload(l: Loader, value: Any, type_: type) -> Any: """ This converts a value into a basic type. In theory it does nothing, but it performs type checking and raises if conditions fail. It also attempts casting, if enabled. """ if type(value) != type_: if l.basiccast: try: return type_(value) except ValueError as e: raise TypedloadValueError(str(e), value=value, type_=type_) except TypeError as e: raise TypedloadTypeError(str(e), value=value, type_=type_) except Exception as e: raise TypedloadException(str(e), value=value, type_=type_) else: raise TypedloadValueError('Not of type %s' % type_, value=value, type_=type_) return value
python
def _basicload(l: Loader, value: Any, type_: type) -> Any: if type(value) != type_: if l.basiccast: try: return type_(value) except ValueError as e: raise TypedloadValueError(str(e), value=value, type_=type_) except TypeError as e: raise TypedloadTypeError(str(e), value=value, type_=type_) except Exception as e: raise TypedloadException(str(e), value=value, type_=type_) else: raise TypedloadValueError('Not of type %s' % type_, value=value, type_=type_) return value
[ "def", "_basicload", "(", "l", ":", "Loader", ",", "value", ":", "Any", ",", "type_", ":", "type", ")", "->", "Any", ":", "if", "type", "(", "value", ")", "!=", "type_", ":", "if", "l", ".", "basiccast", ":", "try", ":", "return", "type_", "(", ...
This converts a value into a basic type. In theory it does nothing, but it performs type checking and raises if conditions fail. It also attempts casting, if enabled.
[ "This", "converts", "a", "value", "into", "a", "basic", "type", "." ]
7fd130612963bfcec3242698463ef863ca4af927
https://github.com/ltworf/typedload/blob/7fd130612963bfcec3242698463ef863ca4af927/typedload/dataloader.py#L243-L265
25,889
ltworf/typedload
typedload/dataloader.py
_unionload
def _unionload(l: Loader, value, type_) -> Any: """ Loads a value into a union. Basically this iterates all the types inside the union, until one that doesn't raise an exception is found. If no suitable type is found, an exception is raised. """ try: args = uniontypes(type_) except AttributeError: raise TypedloadAttributeError('The typing API for this Python version is unknown') # Do not convert basic types, if possible if type(value) in args.intersection(l.basictypes): return value exceptions = [] # Try all types for t in args: try: return l.load(value, t, annotation=Annotation(AnnotationType.UNION, t)) except Exception as e: exceptions.append(e) raise TypedloadValueError( 'Value could not be loaded into %s' % type_, value=value, type_=type_, exceptions=exceptions )
python
def _unionload(l: Loader, value, type_) -> Any: try: args = uniontypes(type_) except AttributeError: raise TypedloadAttributeError('The typing API for this Python version is unknown') # Do not convert basic types, if possible if type(value) in args.intersection(l.basictypes): return value exceptions = [] # Try all types for t in args: try: return l.load(value, t, annotation=Annotation(AnnotationType.UNION, t)) except Exception as e: exceptions.append(e) raise TypedloadValueError( 'Value could not be loaded into %s' % type_, value=value, type_=type_, exceptions=exceptions )
[ "def", "_unionload", "(", "l", ":", "Loader", ",", "value", ",", "type_", ")", "->", "Any", ":", "try", ":", "args", "=", "uniontypes", "(", "type_", ")", "except", "AttributeError", ":", "raise", "TypedloadAttributeError", "(", "'The typing API for this Pytho...
Loads a value into a union. Basically this iterates all the types inside the union, until one that doesn't raise an exception is found. If no suitable type is found, an exception is raised.
[ "Loads", "a", "value", "into", "a", "union", "." ]
7fd130612963bfcec3242698463ef863ca4af927
https://github.com/ltworf/typedload/blob/7fd130612963bfcec3242698463ef863ca4af927/typedload/dataloader.py#L401-L433
25,890
ltworf/typedload
typedload/dataloader.py
_enumload
def _enumload(l: Loader, value, type_) -> Enum: """ This loads something into an Enum. It tries with basic types first. If that fails, it tries to look for type annotations inside the Enum, and tries to use those to load the value into something that is compatible with the Enum. Of course if that fails too, a ValueError is raised. """ try: # Try naïve conversion return type_(value) except: pass # Try with the typing hints for _, t in get_type_hints(type_).items(): try: return type_(l.load(value, t)) except: pass raise TypedloadValueError( 'Value could not be loaded into %s' % type_, value=value, type_=type_ )
python
def _enumload(l: Loader, value, type_) -> Enum: try: # Try naïve conversion return type_(value) except: pass # Try with the typing hints for _, t in get_type_hints(type_).items(): try: return type_(l.load(value, t)) except: pass raise TypedloadValueError( 'Value could not be loaded into %s' % type_, value=value, type_=type_ )
[ "def", "_enumload", "(", "l", ":", "Loader", ",", "value", ",", "type_", ")", "->", "Enum", ":", "try", ":", "# Try naïve conversion", "return", "type_", "(", "value", ")", "except", ":", "pass", "# Try with the typing hints", "for", "_", ",", "t", "in", ...
This loads something into an Enum. It tries with basic types first. If that fails, it tries to look for type annotations inside the Enum, and tries to use those to load the value into something that is compatible with the Enum. Of course if that fails too, a ValueError is raised.
[ "This", "loads", "something", "into", "an", "Enum", "." ]
7fd130612963bfcec3242698463ef863ca4af927
https://github.com/ltworf/typedload/blob/7fd130612963bfcec3242698463ef863ca4af927/typedload/dataloader.py#L436-L464
25,891
ltworf/typedload
typedload/dataloader.py
_noneload
def _noneload(l: Loader, value, type_) -> None: """ Loads a value that can only be None, so it fails if it isn't """ if value is None: return None raise TypedloadValueError('Not None', value=value, type_=type_)
python
def _noneload(l: Loader, value, type_) -> None: if value is None: return None raise TypedloadValueError('Not None', value=value, type_=type_)
[ "def", "_noneload", "(", "l", ":", "Loader", ",", "value", ",", "type_", ")", "->", "None", ":", "if", "value", "is", "None", ":", "return", "None", "raise", "TypedloadValueError", "(", "'Not None'", ",", "value", "=", "value", ",", "type_", "=", "type...
Loads a value that can only be None, so it fails if it isn't
[ "Loads", "a", "value", "that", "can", "only", "be", "None", "so", "it", "fails", "if", "it", "isn", "t" ]
7fd130612963bfcec3242698463ef863ca4af927
https://github.com/ltworf/typedload/blob/7fd130612963bfcec3242698463ef863ca4af927/typedload/dataloader.py#L467-L474
25,892
ltworf/typedload
typedload/dataloader.py
Loader.index
def index(self, type_: Type[T]) -> int: """ Returns the index in the handlers list that matches the given type. If no condition matches, ValueError is raised. """ for i, cond in ((q[0], q[1][0]) for q in enumerate(self.handlers)): try: match = cond(type_) except: if self.raiseconditionerrors: raise match = False if match: return i raise ValueError('No matching condition found')
python
def index(self, type_: Type[T]) -> int: for i, cond in ((q[0], q[1][0]) for q in enumerate(self.handlers)): try: match = cond(type_) except: if self.raiseconditionerrors: raise match = False if match: return i raise ValueError('No matching condition found')
[ "def", "index", "(", "self", ",", "type_", ":", "Type", "[", "T", "]", ")", "->", "int", ":", "for", "i", ",", "cond", "in", "(", "(", "q", "[", "0", "]", ",", "q", "[", "1", "]", "[", "0", "]", ")", "for", "q", "in", "enumerate", "(", ...
Returns the index in the handlers list that matches the given type. If no condition matches, ValueError is raised.
[ "Returns", "the", "index", "in", "the", "handlers", "list", "that", "matches", "the", "given", "type", "." ]
7fd130612963bfcec3242698463ef863ca4af927
https://github.com/ltworf/typedload/blob/7fd130612963bfcec3242698463ef863ca4af927/typedload/dataloader.py#L174-L190
25,893
ltworf/typedload
typedload/dataloader.py
Loader.load
def load(self, value: Any, type_: Type[T], *, annotation: Optional[Annotation] = None) -> T: """ Loads value into the typed data structure. TypeError is raised if there is no known way to treat type_, otherwise all errors raise a ValueError. """ try: index = self.index(type_) except ValueError: raise TypedloadTypeError( 'Cannot deal with value of type %s' % type_, value=value, type_=type_ ) # Add type to known types, to resolve ForwardRef later on if self.frefs is not None and hasattr(type_, '__name__'): tname = type_.__name__ if tname not in self.frefs: self.frefs[tname] = type_ func = self.handlers[index][1] try: return func(self, value, type_) except Exception as e: assert isinstance(e, TypedloadException) e.trace.insert(0, TraceItem(value, type_, annotation)) raise e
python
def load(self, value: Any, type_: Type[T], *, annotation: Optional[Annotation] = None) -> T: try: index = self.index(type_) except ValueError: raise TypedloadTypeError( 'Cannot deal with value of type %s' % type_, value=value, type_=type_ ) # Add type to known types, to resolve ForwardRef later on if self.frefs is not None and hasattr(type_, '__name__'): tname = type_.__name__ if tname not in self.frefs: self.frefs[tname] = type_ func = self.handlers[index][1] try: return func(self, value, type_) except Exception as e: assert isinstance(e, TypedloadException) e.trace.insert(0, TraceItem(value, type_, annotation)) raise e
[ "def", "load", "(", "self", ",", "value", ":", "Any", ",", "type_", ":", "Type", "[", "T", "]", ",", "*", ",", "annotation", ":", "Optional", "[", "Annotation", "]", "=", "None", ")", "->", "T", ":", "try", ":", "index", "=", "self", ".", "inde...
Loads value into the typed data structure. TypeError is raised if there is no known way to treat type_, otherwise all errors raise a ValueError.
[ "Loads", "value", "into", "the", "typed", "data", "structure", "." ]
7fd130612963bfcec3242698463ef863ca4af927
https://github.com/ltworf/typedload/blob/7fd130612963bfcec3242698463ef863ca4af927/typedload/dataloader.py#L192-L220
25,894
ltworf/typedload
example.py
get_data
def get_data(city: Optional[str]) -> Dict[str, Any]: """ Use the Yahoo weather API to get weather information """ req = urllib.request.Request(get_url(city)) with urllib.request.urlopen(req) as f: response = f.read() answer = response.decode('ascii') data = json.loads(answer) r = data['query']['results']['channel'] # Remove some useless nesting return r
python
def get_data(city: Optional[str]) -> Dict[str, Any]: req = urllib.request.Request(get_url(city)) with urllib.request.urlopen(req) as f: response = f.read() answer = response.decode('ascii') data = json.loads(answer) r = data['query']['results']['channel'] # Remove some useless nesting return r
[ "def", "get_data", "(", "city", ":", "Optional", "[", "str", "]", ")", "->", "Dict", "[", "str", ",", "Any", "]", ":", "req", "=", "urllib", ".", "request", ".", "Request", "(", "get_url", "(", "city", ")", ")", "with", "urllib", ".", "request", ...
Use the Yahoo weather API to get weather information
[ "Use", "the", "Yahoo", "weather", "API", "to", "get", "weather", "information" ]
7fd130612963bfcec3242698463ef863ca4af927
https://github.com/ltworf/typedload/blob/7fd130612963bfcec3242698463ef863ca4af927/example.py#L51-L61
25,895
ltworf/typedload
typedload/__init__.py
load
def load(value: Any, type_: Type[T], **kwargs) -> T: """ Quick function call to load data into a type. It is useful to avoid creating the Loader object, in case only the default parameters are used. """ from . import dataloader loader = dataloader.Loader(**kwargs) return loader.load(value, type_)
python
def load(value: Any, type_: Type[T], **kwargs) -> T: from . import dataloader loader = dataloader.Loader(**kwargs) return loader.load(value, type_)
[ "def", "load", "(", "value", ":", "Any", ",", "type_", ":", "Type", "[", "T", "]", ",", "*", "*", "kwargs", ")", "->", "T", ":", "from", ".", "import", "dataloader", "loader", "=", "dataloader", ".", "Loader", "(", "*", "*", "kwargs", ")", "retur...
Quick function call to load data into a type. It is useful to avoid creating the Loader object, in case only the default parameters are used.
[ "Quick", "function", "call", "to", "load", "data", "into", "a", "type", "." ]
7fd130612963bfcec3242698463ef863ca4af927
https://github.com/ltworf/typedload/blob/7fd130612963bfcec3242698463ef863ca4af927/typedload/__init__.py#L145-L154
25,896
ltworf/typedload
typedload/__init__.py
dump
def dump(value: Any, **kwargs) -> Any: """ Quick function to dump a data structure into something that is compatible with json or other programs and languages. It is useful to avoid creating the Dumper object, in case only the default parameters are used. """ from . import datadumper dumper = datadumper.Dumper(**kwargs) return dumper.dump(value)
python
def dump(value: Any, **kwargs) -> Any: from . import datadumper dumper = datadumper.Dumper(**kwargs) return dumper.dump(value)
[ "def", "dump", "(", "value", ":", "Any", ",", "*", "*", "kwargs", ")", "->", "Any", ":", "from", ".", "import", "datadumper", "dumper", "=", "datadumper", ".", "Dumper", "(", "*", "*", "kwargs", ")", "return", "dumper", ".", "dump", "(", "value", "...
Quick function to dump a data structure into something that is compatible with json or other programs and languages. It is useful to avoid creating the Dumper object, in case only the default parameters are used.
[ "Quick", "function", "to", "dump", "a", "data", "structure", "into", "something", "that", "is", "compatible", "with", "json", "or", "other", "programs", "and", "languages", "." ]
7fd130612963bfcec3242698463ef863ca4af927
https://github.com/ltworf/typedload/blob/7fd130612963bfcec3242698463ef863ca4af927/typedload/__init__.py#L157-L168
25,897
ltworf/typedload
typedload/__init__.py
attrload
def attrload(value: Any, type_: Type[T], **kwargs) -> T: """ Quick function call to load data supporting the "attr" module in addition to the default ones. """ from . import dataloader from .plugins import attrload as loadplugin loader = dataloader.Loader(**kwargs) loadplugin.add2loader(loader) return loader.load(value, type_)
python
def attrload(value: Any, type_: Type[T], **kwargs) -> T: from . import dataloader from .plugins import attrload as loadplugin loader = dataloader.Loader(**kwargs) loadplugin.add2loader(loader) return loader.load(value, type_)
[ "def", "attrload", "(", "value", ":", "Any", ",", "type_", ":", "Type", "[", "T", "]", ",", "*", "*", "kwargs", ")", "->", "T", ":", "from", ".", "import", "dataloader", "from", ".", "plugins", "import", "attrload", "as", "loadplugin", "loader", "=",...
Quick function call to load data supporting the "attr" module in addition to the default ones.
[ "Quick", "function", "call", "to", "load", "data", "supporting", "the", "attr", "module", "in", "addition", "to", "the", "default", "ones", "." ]
7fd130612963bfcec3242698463ef863ca4af927
https://github.com/ltworf/typedload/blob/7fd130612963bfcec3242698463ef863ca4af927/typedload/__init__.py#L171-L180
25,898
ltworf/typedload
typedload/__init__.py
attrdump
def attrdump(value: Any, **kwargs) -> Any: """ Quick function to do a dump that supports the "attr" module. """ from . import datadumper from .plugins import attrdump as dumpplugin dumper = datadumper.Dumper(**kwargs) dumpplugin.add2dumper(dumper) return dumper.dump(value)
python
def attrdump(value: Any, **kwargs) -> Any: from . import datadumper from .plugins import attrdump as dumpplugin dumper = datadumper.Dumper(**kwargs) dumpplugin.add2dumper(dumper) return dumper.dump(value)
[ "def", "attrdump", "(", "value", ":", "Any", ",", "*", "*", "kwargs", ")", "->", "Any", ":", "from", ".", "import", "datadumper", "from", ".", "plugins", "import", "attrdump", "as", "dumpplugin", "dumper", "=", "datadumper", ".", "Dumper", "(", "*", "*...
Quick function to do a dump that supports the "attr" module.
[ "Quick", "function", "to", "do", "a", "dump", "that", "supports", "the", "attr", "module", "." ]
7fd130612963bfcec3242698463ef863ca4af927
https://github.com/ltworf/typedload/blob/7fd130612963bfcec3242698463ef863ca4af927/typedload/__init__.py#L183-L192
25,899
rgalanakis/goless
goless/__init__.py
on_panic
def on_panic(etype, value, tb): """ Called when there is an unhandled error in a goroutine. By default, logs and exits the process. """ _logging.critical(_traceback.format_exception(etype, value, tb)) _be.propagate_exc(SystemExit, 1)
python
def on_panic(etype, value, tb): _logging.critical(_traceback.format_exception(etype, value, tb)) _be.propagate_exc(SystemExit, 1)
[ "def", "on_panic", "(", "etype", ",", "value", ",", "tb", ")", ":", "_logging", ".", "critical", "(", "_traceback", ".", "format_exception", "(", "etype", ",", "value", ",", "tb", ")", ")", "_be", ".", "propagate_exc", "(", "SystemExit", ",", "1", ")" ...
Called when there is an unhandled error in a goroutine. By default, logs and exits the process.
[ "Called", "when", "there", "is", "an", "unhandled", "error", "in", "a", "goroutine", ".", "By", "default", "logs", "and", "exits", "the", "process", "." ]
286cd69482ae5a56c899a0c0d5d895772d96e83d
https://github.com/rgalanakis/goless/blob/286cd69482ae5a56c899a0c0d5d895772d96e83d/goless/__init__.py#L35-L41