code stringlengths 66 870k | docstring stringlengths 19 26.7k | func_name stringlengths 1 138 | language stringclasses 1
value | repo stringlengths 7 68 | path stringlengths 5 324 | url stringlengths 46 389 | license stringclasses 7
values |
|---|---|---|---|---|---|---|---|
def get_overridable_template_name(name, plugin, core_prefix='', plugin_prefix=''):
"""Return template names for templates that may be overridden in a plugin.
:param name: the name of the template
:param plugin: the :class:`IndicoPlugin` that may override it (can be none)
:param core_prefix: the path pr... | Return template names for templates that may be overridden in a plugin.
:param name: the name of the template
:param plugin: the :class:`IndicoPlugin` that may override it (can be none)
:param core_prefix: the path prefix of the template in the core
:param plugin_prefix: the path prefix of the template... | get_overridable_template_name | python | indico/indico | indico/web/flask/templating.py | https://github.com/indico/indico/blob/master/indico/web/flask/templating.py | MIT |
def get_template_module(template_name_or_list, **context):
"""Return the python module of a template.
This allows you to call e.g. macros inside it from Python code.
"""
current_app.update_template_context(context)
tpl = current_app.jinja_env.get_or_select_template(template_name_or_list)
return... | Return the python module of a template.
This allows you to call e.g. macros inside it from Python code.
| get_template_module | python | indico/indico | indico/web/flask/templating.py | https://github.com/indico/indico/blob/master/indico/web/flask/templating.py | MIT |
def register_template_hook(name, receiver, priority=50, markup=True, plugin=None):
"""Register a function to be called when a template hook is invoked.
The receiver function should always support arbitrary ``**kwargs``
to prevent breakage in future Indico versions which might add new
arguments to a hoo... | Register a function to be called when a template hook is invoked.
The receiver function should always support arbitrary ``**kwargs``
to prevent breakage in future Indico versions which might add new
arguments to a hook::
def receiver(something, **kwargs):
return do_stuff(something)
... | register_template_hook | python | indico/indico | indico/web/flask/templating.py | https://github.com/indico/indico/blob/master/indico/web/flask/templating.py | MIT |
def call_template_hook(*name, **kwargs):
"""Template function to let plugins add their own data to a template.
:param name: The name of the hook. Only accepts one argument.
:param as_list: Return a list instead of a concatenated string
:param kwargs: Data to pass to the signal receivers.
"""
i... | Template function to let plugins add their own data to a template.
:param name: The name of the hook. Only accepts one argument.
:param as_list: Return a list instead of a concatenated string
:param kwargs: Data to pass to the signal receivers.
| call_template_hook | python | indico/indico | indico/web/flask/templating.py | https://github.com/indico/indico/blob/master/indico/web/flask/templating.py | MIT |
def discover_blueprints():
"""Discover all blueprints inside the indico package.
Only blueprints in a ``blueprint.py`` module or inside a
``blueprints`` package are loaded. Any other files are not touched
or even imported.
:return: a ``blueprints, compat_blueprints`` tuple containing two
... | Discover all blueprints inside the indico package.
Only blueprints in a ``blueprint.py`` module or inside a
``blueprints`` package are loaded. Any other files are not touched
or even imported.
:return: a ``blueprints, compat_blueprints`` tuple containing two
sets of blueprints
| discover_blueprints | python | indico/indico | indico/web/flask/util.py | https://github.com/indico/indico/blob/master/indico/web/flask/util.py | MIT |
def make_view_func(obj):
"""Turn an object in to a view function.
This function is called on each view_func passed to IndicoBlueprint.add_url_route().
It handles RH classes and normal functions.
"""
if inspect.isclass(obj):
# Some class
if hasattr(obj, 'process'):
# Indi... | Turn an object in to a view function.
This function is called on each view_func passed to IndicoBlueprint.add_url_route().
It handles RH classes and normal functions.
| make_view_func | python | indico/indico | indico/web/flask/util.py | https://github.com/indico/indico/blob/master/indico/web/flask/util.py | MIT |
def redirect_view(endpoint, code=302):
"""Create a view function that redirects to the given endpoint."""
def _redirect(**kwargs):
params = request.args.to_dict() | kwargs
return redirect(_url_for(endpoint, **params), code=code)
return _redirect | Create a view function that redirects to the given endpoint. | redirect_view | python | indico/indico | indico/web/flask/util.py | https://github.com/indico/indico/blob/master/indico/web/flask/util.py | MIT |
def url_for(endpoint, *targets, **values):
"""Wrapper for Flask's ``url_for`` function.
The `target` argument allows you to pass some object having a `locator` property returning a dict.
For details on Flask's url_for, please see its documentation.
The important special arguments you can put in `value... | Wrapper for Flask's ``url_for`` function.
The `target` argument allows you to pass some object having a `locator` property returning a dict.
For details on Flask's url_for, please see its documentation.
The important special arguments you can put in `values` are:
_external: if set to `True`, an absol... | url_for | python | indico/indico | indico/web/flask/util.py | https://github.com/indico/indico/blob/master/indico/web/flask/util.py | MIT |
def url_rule_to_js(endpoint):
"""Convert the rule(s) of an endpoint to a JavaScript object.
Use this if you need to build an URL in JavaScript, but only if
you really have to do that instead of e.g. building the URL on
the server and storing it in a data attribute.
JS usage::
var urlTempl... | Convert the rule(s) of an endpoint to a JavaScript object.
Use this if you need to build an URL in JavaScript, but only if
you really have to do that instead of e.g. building the URL on
the server and storing it in a data attribute.
JS usage::
var urlTemplate = {{ url_rule_to_js('blueprint.en... | url_rule_to_js | python | indico/indico | indico/web/flask/util.py | https://github.com/indico/indico/blob/master/indico/web/flask/util.py | MIT |
def redirect_or_jsonify(location, flash=True, **json_data):
"""Return a redirect or json response.
If the request was an XHR we return JSON, otherwise we redirect.
Unless set to another value, the JSON data includes `success=True`
:param location: the redirect target
:param flash: if the json data... | Return a redirect or json response.
If the request was an XHR we return JSON, otherwise we redirect.
Unless set to another value, the JSON data includes `success=True`
:param location: the redirect target
:param flash: if the json data should contain flashed messages
:param json_data: the data to ... | redirect_or_jsonify | python | indico/indico | indico/web/flask/util.py | https://github.com/indico/indico/blob/master/indico/web/flask/util.py | MIT |
def send_file(name, path_or_fd, mimetype, *, last_modified=None, no_cache=True, inline=None,
max_age=86400, conditional=False, safe=True, **kwargs):
"""Send a file to the user.
`name` is required and should be the filename visible to the user.
`path_or_fd` is either the physical path to the f... | Send a file to the user.
`name` is required and should be the filename visible to the user.
`path_or_fd` is either the physical path to the file or a file-like object (e.g. a StringIO).
`mimetype` SHOULD be a proper MIME type such as image/png. It may also be an indico-style file type such as JPG.
`las... | send_file | python | indico/indico | indico/web/flask/util.py | https://github.com/indico/indico/blob/master/indico/web/flask/util.py | MIT |
def bearer_token(self):
"""Bearer token included in the request, if any."""
auth_header = request.headers.get('Authorization')
if not auth_header:
return None
m = AUTH_BEARER_RE.match(auth_header)
return m.group(1) if m else None | Bearer token included in the request, if any. | bearer_token | python | indico/indico | indico/web/flask/wrappers.py | https://github.com/indico/indico/blob/master/indico/web/flask/wrappers.py | MIT |
def add_prefixed_rules(self, prefix, default_prefix=''):
"""Create prefixed rules in addition to the normal ones.
When specifying a default_prefix, too, the normally "unprefixed" rules
are prefixed with it.
"""
assert self.__prefix is None and not self.__default_prefix
s... | Create prefixed rules in addition to the normal ones.
When specifying a default_prefix, too, the normally "unprefixed" rules
are prefixed with it.
| add_prefixed_rules | python | indico/indico | indico/web/flask/wrappers.py | https://github.com/indico/indico/blob/master/indico/web/flask/wrappers.py | MIT |
def post_validate(self):
"""Called after the form was successfully validated.
This method is a good place e.g. to override the data of fields in
certain cases without going through the hassle of generated_data.
""" | Called after the form was successfully validated.
This method is a good place e.g. to override the data of fields in
certain cases without going through the hassle of generated_data.
| post_validate | python | indico/indico | indico/web/forms/base.py | https://github.com/indico/indico/blob/master/indico/web/forms/base.py | MIT |
def populate_obj(self, obj, fields=None, skip=None, existing_only=False):
"""Populate the given object with form data.
If `fields` is set, only fields from that list are populated.
If `skip` is set, fields in that list are skipped.
If `existing_only` is True, only attributes that alread... | Populate the given object with form data.
If `fields` is set, only fields from that list are populated.
If `skip` is set, fields in that list are skipped.
If `existing_only` is True, only attributes that already exist on `obj` are populated.
Attributes starting with ``ext__`` are alway... | populate_obj | python | indico/indico | indico/web/forms/base.py | https://github.com/indico/indico/blob/master/indico/web/forms/base.py | MIT |
def error_list(self):
"""A list containing all errors, prefixed with the field's label."""
all_errors = []
for field_name, errors in self.errors.items():
for error in errors:
if isinstance(error, dict) and isinstance(self[field_name], FieldList):
f... | A list containing all errors, prefixed with the field's label. | error_list | python | indico/indico | indico/web/forms/base.py | https://github.com/indico/indico/blob/master/indico/web/forms/base.py | MIT |
def generated_data(self):
"""Return a dict containing all generated data."""
cls = type(self)
return {field: getattr(self, field).data
for field in dir(cls)
if isinstance(getattr(cls, field), generated_data)} | Return a dict containing all generated data. | generated_data | python | indico/indico | indico/web/forms/base.py | https://github.com/indico/indico/blob/master/indico/web/forms/base.py | MIT |
def data(self):
"""Extend form.data with generated data from properties."""
data = {k: v
for k, v in super().data.items()
if k != self.meta.csrf_field_name and not k.startswith('ext__')}
data.update(self.generated_data)
return data | Extend form.data with generated data from properties. | data | python | indico/indico | indico/web/forms/base.py | https://github.com/indico/indico/blob/master/indico/web/forms/base.py | MIT |
def __valid_attr(self, name):
"""Check if an attr may be retrieved from the object."""
if self.__obj is None:
return False
if self.__obj_attrs is not None and name not in self.__obj_attrs:
return False
if self.__obj_attrs_skip is not None and name in self.__obj_at... | Check if an attr may be retrieved from the object. | __valid_attr | python | indico/indico | indico/web/forms/base.py | https://github.com/indico/indico/blob/master/indico/web/forms/base.py | MIT |
def get_role_colors():
"""Get the list of colors available for event/category roles."""
return ['005272', '007cac', '5d95ea',
'af0000', 'a76766',
'999999', '555555', '777777',
'67a766', '6cc644',
'9c793b', 'e99e18',
'b14300', 'e25300',
'6e5... | Get the list of colors available for event/category roles. | get_role_colors | python | indico/indico | indico/web/forms/colors.py | https://github.com/indico/indico/blob/master/indico/web/forms/colors.py | MIT |
def render_field(field, widget_attrs, disabled=None):
"""Render a WTForms field, taking into account validators."""
if not widget_attrs.get('placeholder'):
widget_attrs = dict(widget_attrs)
widget_attrs.pop('placeholder', None)
args = _attrs_for_validators(field, field.validators)
args['... | Render a WTForms field, taking into account validators. | render_field | python | indico/indico | indico/web/forms/jinja_helpers.py | https://github.com/indico/indico/blob/master/indico/web/forms/jinja_helpers.py | MIT |
def iter_form_fields(form, fields=None, skip=None, hidden_fields=False):
"""Iterate over the fields in a WTForm.
:param fields: If specified only fields that are in this list are
yielded. This also overrides the field order.
:param skip: If specified, only fields NOT in this set/list are... | Iterate over the fields in a WTForm.
:param fields: If specified only fields that are in this list are
yielded. This also overrides the field order.
:param skip: If specified, only fields NOT in this set/list are
yielded.
:param hidden_fields: How to handle hidden fields... | iter_form_fields | python | indico/indico | indico/web/forms/jinja_helpers.py | https://github.com/indico/indico/blob/master/indico/web/forms/jinja_helpers.py | MIT |
def get_form_field_names(form_class):
"""Return the list of field names of a WTForm.
:param form_class: A `Form` subclass
"""
unbound_fields = form_class._unbound_fields
if unbound_fields:
return [f[0] for f in unbound_fields]
field_names = []
# the following logic has been taken fr... | Return the list of field names of a WTForm.
:param form_class: A `Form` subclass
| get_form_field_names | python | indico/indico | indico/web/forms/util.py | https://github.com/indico/indico/blob/master/indico/web/forms/util.py | MIT |
def inject_validators(form, field_name, validators, early=False):
"""Add extra validators to a form field.
This function may be called from the ``__init__`` method of a
form before the ``super().__init__()`` call or on a form class.
When using a Form class note that this will modify the class, so
a... | Add extra validators to a form field.
This function may be called from the ``__init__`` method of a
form before the ``super().__init__()`` call or on a form class.
When using a Form class note that this will modify the class, so
all new instances of it will be affected!
:param form: the `Form` ins... | inject_validators | python | indico/indico | indico/web/forms/util.py | https://github.com/indico/indico/blob/master/indico/web/forms/util.py | MIT |
def best_unit(self):
"""Return the largest unit that covers the current timedelta."""
if self.data is None:
return None
seconds = int(self.data.total_seconds())
for unit, magnitude in self.magnitudes.items():
if not seconds % magnitude:
return unit... | Return the largest unit that covers the current timedelta. | best_unit | python | indico/indico | indico/web/forms/fields/datetime.py | https://github.com/indico/indico/blob/master/indico/web/forms/fields/datetime.py | MIT |
def get_overridden_value(self, row, name):
"""Utility for the widget to get the entered value for an editable field."""
key = self.get_row_key(row)
return self._value().get(key, {}).get(name, '') | Utility for the widget to get the entered value for an editable field. | get_overridden_value | python | indico/indico | indico/web/forms/fields/itemlists.py | https://github.com/indico/indico/blob/master/indico/web/forms/fields/itemlists.py | MIT |
def normalizeQuery(path, query, remove=('signature',), separate=False):
"""Normalize request path and query so it can be used for caching and signing.
Returns a string consisting of path and sorted query string.
Dynamic arguments like signature and timestamp are removed from the query string.
"""
q... | Normalize request path and query so it can be used for caching and signing.
Returns a string consisting of path and sorted query string.
Dynamic arguments like signature and timestamp are removed from the query string.
| normalizeQuery | python | indico/indico | indico/web/http_api/handlers.py | https://github.com/indico/indico/blob/master/indico/web/http_api/handlers.py | MIT |
def parseRequest(cls, path, queryParams):
"""Parse a request path and return a hook and the requested data type."""
path = unquote(path)
hooks = cls.HOOK_LIST
for expCls in hooks:
Logger.get('HTTPAPIHook.parseRequest').debug(expCls)
m = expCls._matchPath(path)
... | Parse a request path and return a hook and the requested data type. | parseRequest | python | indico/indico | indico/web/http_api/hooks/base.py | https://github.com/indico/indico/blob/master/indico/web/http_api/hooks/base.py | MIT |
def register(hook_cls):
"""Register a hook.
To use it, simply decorate the hook class with this method.
"""
assert hook_cls.RE is not None
HTTPAPIHook.HOOK_LIST.append(hook_cls)
return hook_cls | Register a hook.
To use it, simply decorate the hook class with this method.
| register | python | indico/indico | indico/web/http_api/hooks/base.py | https://github.com/indico/indico/blob/master/indico/web/http_api/hooks/base.py | MIT |
def _parseDateTime(cls, dateTime, allowNegativeOffset):
"""Parse a date/time string.
Accepted formats:
* ISO 8601 subset - YYYY-MM-DD[THH:MM]
* 'today', 'yesterday', 'tomorrow' and 'now'
* days in the future/past: '[+/-]DdHHhMMm'
'ctx' means that the date will chang... | Parse a date/time string.
Accepted formats:
* ISO 8601 subset - YYYY-MM-DD[THH:MM]
* 'today', 'yesterday', 'tomorrow' and 'now'
* days in the future/past: '[+/-]DdHHhMMm'
'ctx' means that the date will change according to its function
('from' or 'to')
| _parseDateTime | python | indico/indico | indico/web/http_api/hooks/base.py | https://github.com/indico/indico/blob/master/indico/web/http_api/hooks/base.py | MIT |
def main():
"""Inference demo for Real-ESRGAN.
It mainly for restoring anime videos.
"""
parser = argparse.ArgumentParser()
parser.add_argument('-i', '--input', type=str, default='inputs', help='Input video, image or folder')
parser.add_argument(
'-n',
'--model_name',
ty... | Inference demo for Real-ESRGAN.
It mainly for restoring anime videos.
| main | python | xinntao/Real-ESRGAN | inference_realesrgan_video.py | https://github.com/xinntao/Real-ESRGAN/blob/master/inference_realesrgan_video.py | BSD-3-Clause |
def main(args):
"""A multi-thread tool to crop large images to sub-images for faster IO.
opt (dict): Configuration dict. It contains:
n_thread (int): Thread number.
compression_level (int): CV_IMWRITE_PNG_COMPRESSION from 0 to 9. A higher value means a smaller size
and longer compr... | A multi-thread tool to crop large images to sub-images for faster IO.
opt (dict): Configuration dict. It contains:
n_thread (int): Thread number.
compression_level (int): CV_IMWRITE_PNG_COMPRESSION from 0 to 9. A higher value means a smaller size
and longer compression time. Use 0 for ... | main | python | xinntao/Real-ESRGAN | scripts/extract_subimages.py | https://github.com/xinntao/Real-ESRGAN/blob/master/scripts/extract_subimages.py | BSD-3-Clause |
def worker(path, opt):
"""Worker for each process.
Args:
path (str): Image path.
opt (dict): Configuration dict. It contains:
crop_size (int): Crop size.
step (int): Step for overlapped sliding window.
thresh_size (int): Threshold size. Patches whose size is ... | Worker for each process.
Args:
path (str): Image path.
opt (dict): Configuration dict. It contains:
crop_size (int): Crop size.
step (int): Step for overlapped sliding window.
thresh_size (int): Threshold size. Patches whose size is lower than thresh_size will be... | worker | python | xinntao/Real-ESRGAN | scripts/extract_subimages.py | https://github.com/xinntao/Real-ESRGAN/blob/master/scripts/extract_subimages.py | BSD-3-Clause |
def get_db_session_for_app_config(app_config):
"""
Refactor: This helper function is designed to help fixtures yield a database
session for a particular app_config.
It needs the app_config in order to fetch the database engine that's owned
by the config.
"""
# TODO: We possibly accept 2 in... |
Refactor: This helper function is designed to help fixtures yield a database
session for a particular app_config.
It needs the app_config in order to fetch the database engine that's owned
by the config.
| get_db_session_for_app_config | python | pypi/warehouse | tests/conftest.py | https://github.com/pypi/warehouse/blob/master/tests/conftest.py | Apache-2.0 |
def webtest(app_config_dbsession_from_env, tm):
"""
This fixture yields a test app with an alternative Pyramid configuration,
injecting the database session and transaction manager into the app.
This is because the Warehouse app normally manages its own database session.
After the fixture has yiel... |
This fixture yields a test app with an alternative Pyramid configuration,
injecting the database session and transaction manager into the app.
This is because the Warehouse app normally manages its own database session.
After the fixture has yielded the app, the transaction is rolled back and
the... | webtest | python | pypi/warehouse | tests/conftest.py | https://github.com/pypi/warehouse/blob/master/tests/conftest.py | Apache-2.0 |
def gitlab_provenance() -> Provenance:
"""
Provenance from
https://test.pypi.org/integrity/pep740-sampleproject/1.0.0/pep740_sampleproject-1.0.0.tar.gz/provenance
"""
return Provenance.model_validate_json(
(_FIXTURES / "pep740-sampleproject-1.0.0.tar.gz.provenance").read_text()
) |
Provenance from
https://test.pypi.org/integrity/pep740-sampleproject/1.0.0/pep740_sampleproject-1.0.0.tar.gz/provenance
| gitlab_provenance | python | pypi/warehouse | tests/conftest.py | https://github.com/pypi/warehouse/blob/master/tests/conftest.py | Apache-2.0 |
def github_provenance() -> Provenance:
"""
Provenance from
https://pypi.org/integrity/sampleproject/4.0.0/sampleproject-4.0.0.tar.gz/provenance
"""
return Provenance.model_validate_json(
(_FIXTURES / "sampleproject-4.0.0.tar.gz.provenance").read_text()
) |
Provenance from
https://pypi.org/integrity/sampleproject/4.0.0/sampleproject-4.0.0.tar.gz/provenance
| github_provenance | python | pypi/warehouse | tests/conftest.py | https://github.com/pypi/warehouse/blob/master/tests/conftest.py | Apache-2.0 |
def test_unauthed_user(self, webtest):
"""
Test that locale changes are reflected in the response
"""
# The default locale is set to English
resp = webtest.get("/", status=HTTPStatus.OK)
assert LOCALE_ATTR not in resp.headers.getall("Set-Cookie")
assert resp.html.... |
Test that locale changes are reflected in the response
| test_unauthed_user | python | pypi/warehouse | tests/functional/test_notifications.py | https://github.com/pypi/warehouse/blob/master/tests/functional/test_notifications.py | Apache-2.0 |
def test_templates_for_empty_titles(template: Path):
"""
Test if all HTML templates have defined the title block. See
https://github.com/pypi/warehouse/issues/784
"""
dir_name = Path(warehouse.__path__[0]) / "templates"
env = Environment(
loader=FileSystemLoader(dir_name),
exten... |
Test if all HTML templates have defined the title block. See
https://github.com/pypi/warehouse/issues/784
| test_templates_for_empty_titles | python | pypi/warehouse | tests/functional/test_templates.py | https://github.com/pypi/warehouse/blob/master/tests/functional/test_templates.py | Apache-2.0 |
def test_render_templates(template):
"""
Test if all HTML templates are rendered without Jinja exceptions.
see https://github.com/pypi/warehouse/issues/6634
"""
dir_name = Path(warehouse.__path__[0]) / "templates"
env = Environment(
loader=FileSystemLoader(dir_name),
extensions=... |
Test if all HTML templates are rendered without Jinja exceptions.
see https://github.com/pypi/warehouse/issues/6634
| test_render_templates | python | pypi/warehouse | tests/functional/test_templates.py | https://github.com/pypi/warehouse/blob/master/tests/functional/test_templates.py | Apache-2.0 |
def test_email_subjects_for_multiple_lines(template: Path):
"""
Test if all email subject templates don't contain new lines. See
https://github.com/pypi/warehouse/issues/13216
"""
with template.open("r") as f:
match = SUBJECT_BLOCK_EXPRESSION.search(f.read())
# There should be a sub... |
Test if all email subject templates don't contain new lines. See
https://github.com/pypi/warehouse/issues/13216
| test_email_subjects_for_multiple_lines | python | pypi/warehouse | tests/functional/test_templates.py | https://github.com/pypi/warehouse/blob/master/tests/functional/test_templates.py | Apache-2.0 |
def test_user_profile(webtest):
"""
This test is maintained as a POC for future tests that want to add data to
the database and test HTTP endpoints afterwards.
The trick is to use the ``webtest`` fixture which will create a special
instance of the Warehouse WSGI app, sharing the same DB session as ... |
This test is maintained as a POC for future tests that want to add data to
the database and test HTTP endpoints afterwards.
The trick is to use the ``webtest`` fixture which will create a special
instance of the Warehouse WSGI app, sharing the same DB session as is active
in pytest.
| test_user_profile | python | pypi/warehouse | tests/functional/test_user_profile.py | https://github.com/pypi/warehouse/blob/master/tests/functional/test_user_profile.py | Apache-2.0 |
def test_includeme_development():
"""
Tests for development-centric CSP settings.
Not as extensive as the production tests.
"""
config = pretend.stub(
register_service_factory=pretend.call_recorder(lambda fact, name: None),
add_settings=pretend.call_recorder(lambda settings: None),
... |
Tests for development-centric CSP settings.
Not as extensive as the production tests.
| test_includeme_development | python | pypi/warehouse | tests/unit/test_csp.py | https://github.com/pypi/warehouse/blob/master/tests/unit/test_csp.py | Apache-2.0 |
def _no_deliverability_check(monkeypatch):
"""
Prevents the email_validator library from checking deliverability of email
"""
original_validate_email = email_validator.validate_email # recursion prevention
def mock_validate_email(email, check_deliverability=True, *args, **kwargs):
return o... |
Prevents the email_validator library from checking deliverability of email
| _no_deliverability_check | python | pypi/warehouse | tests/unit/accounts/test_forms.py | https://github.com/pypi/warehouse/blob/master/tests/unit/accounts/test_forms.py | Apache-2.0 |
def test_noops(self):
"""Basically, anything that isn't `identity()` is a no-op."""
policy = security_policy.BasicAuthSecurityPolicy()
with pytest.raises(NotImplementedError):
policy.authenticated_userid(pretend.stub())
with pytest.raises(NotImplementedError):
pol... | Basically, anything that isn't `identity()` is a no-op. | test_noops | python | pypi/warehouse | tests/unit/accounts/test_security_policy.py | https://github.com/pypi/warehouse/blob/master/tests/unit/accounts/test_security_policy.py | Apache-2.0 |
def test_check_password_updates(self, user_service, password):
"""
This test confirms passlib is actually working,
see https://github.com/pypi/warehouse/issues/15454
"""
user = UserFactory.create(password=password)
assert user_service.check_password(user.id, "password")
... |
This test confirms passlib is actually working,
see https://github.com/pypi/warehouse/issues/15454
| test_check_password_updates | python | pypi/warehouse | tests/unit/accounts/test_services.py | https://github.com/pypi/warehouse/blob/master/tests/unit/accounts/test_services.py | Apache-2.0 |
def test_update_email_domain_status(db_request, domain_status_service, mocker):
"""
Test that the batch update performs the correct queries and updates
"""
never_checked = EmailFactory.create(
email="me@never-checked.com", domain_last_checked=None
)
over_threshold = EmailFactory.create(
... |
Test that the batch update performs the correct queries and updates
| test_update_email_domain_status | python | pypi/warehouse | tests/unit/accounts/test_tasks.py | https://github.com/pypi/warehouse/blob/master/tests/unit/accounts/test_tasks.py | Apache-2.0 |
def test_unverify_emails_with_expired_domains(db_request, user_service):
"""
Test that the unverify_emails_with_expired_domains task works as expected.
"""
# ensure an admin user exists
admin_user = UserFactory.create(username="admin")
expired_email = EmailFactory.create(domain_last_status=["un... |
Test that the unverify_emails_with_expired_domains task works as expected.
| test_unverify_emails_with_expired_domains | python | pypi/warehouse | tests/unit/accounts/test_tasks.py | https://github.com/pypi/warehouse/blob/master/tests/unit/accounts/test_tasks.py | Apache-2.0 |
def test_two_factor_and_totp_validate_redirect_to_account_login(
self,
db_request,
token_service,
user_service,
):
"""
Checks redirect to the login page if the 2fa login got expired.
Given there's user in the database and has a token signed before last_login ... |
Checks redirect to the login page if the 2fa login got expired.
Given there's user in the database and has a token signed before last_login date
When the user calls accounts.two-factor view
Then the user is redirected to account/login page
... warning::
This test h... | test_two_factor_and_totp_validate_redirect_to_account_login | python | pypi/warehouse | tests/unit/accounts/test_views.py | https://github.com/pypi/warehouse/blob/master/tests/unit/accounts/test_views.py | Apache-2.0 |
def banner_data():
"""Fixture with minimal required data to create a banner"""
return {
"name": "Sample Banner",
"text": "This should be the correct text",
"link_url": "https://samplebanner.com",
"end": (datetime.date.today() + datetime.timedelta(days=2)).isoformat(),
} | Fixture with minimal required data to create a banner | banner_data | python | pypi/warehouse | tests/unit/admin/views/test_banners.py | https://github.com/pypi/warehouse/blob/master/tests/unit/admin/views/test_banners.py | Apache-2.0 |
def test_dashboard_with_permission_and_observation(self, db_request):
"""Test that the dashboard view returns the correct data when the user has the
required permission and there are multiple Observations in the database."""
ProjectObservationFactory.create(kind="is_malware")
ProjectObse... | Test that the dashboard view returns the correct data when the user has the
required permission and there are multiple Observations in the database. | test_dashboard_with_permission_and_observation | python | pypi/warehouse | tests/unit/admin/views/test_core.py | https://github.com/pypi/warehouse/blob/master/tests/unit/admin/views/test_core.py | Apache-2.0 |
def raw_token():
"""
A valid macaroon token string, without a database object.
Intentionally split across lines to prevent false-positive detection by
scanners, as it's only used for testing.
"""
return (
"py"
"pi-AgEIcHlwaS5vcmcCJGQ0ZDhhNzA2LTUxYTEtNDg0NC1hNDlmLTEyZDRiYzNkYjZmOQ... |
A valid macaroon token string, without a database object.
Intentionally split across lines to prevent false-positive detection by
scanners, as it's only used for testing.
| raw_token | python | pypi/warehouse | tests/unit/admin/views/test_macaroons.py | https://github.com/pypi/warehouse/blob/master/tests/unit/admin/views/test_macaroons.py | Apache-2.0 |
def test_defaults_text_html(self, header):
"""
Ensures that, at least until we want to change the default, that we
default to text/html.
"""
request = DummyRequest(accept=header)
assert simple._select_content_type(request) == simple.MIME_TEXT_HTML |
Ensures that, at least until we want to change the default, that we
default to text/html.
| test_defaults_text_html | python | pypi/warehouse | tests/unit/api/test_simple.py | https://github.com/pypi/warehouse/blob/master/tests/unit/api/test_simple.py | Apache-2.0 |
def session_resetting_request():
"""A pretend request object with a requests.Session that is reset between tests."""
return pretend.stub(
# returning a real requests.Session object because responses is responsible
# for mocking that out
http=requests.Session(),
registry=pretend.s... | A pretend request object with a requests.Session that is reset between tests. | session_resetting_request | python | pypi/warehouse | tests/unit/captcha/test_recaptcha.py | https://github.com/pypi/warehouse/blob/master/tests/unit/captcha/test_recaptcha.py | Apache-2.0 |
def test_plain(self, monkeypatch):
"""Neither bpython nor ipython are installed."""
monkeypatch.setitem(sys.modules, "bpython", None)
monkeypatch.setitem(sys.modules, "IPython", None)
assert shell.autodetect() == "plain" | Neither bpython nor ipython are installed. | test_plain | python | pypi/warehouse | tests/unit/cli/test_shell.py | https://github.com/pypi/warehouse/blob/master/tests/unit/cli/test_shell.py | Apache-2.0 |
def test_display_output(self, test_input, expected):
"""Create a GeoIPInfo object and test the display method."""
dataklazz = GeoIPInfo(**test_input)
assert dataklazz.display() == expected | Create a GeoIPInfo object and test the display method. | test_display_output | python | pypi/warehouse | tests/unit/events/test_models.py | https://github.com/pypi/warehouse/blob/master/tests/unit/events/test_models.py | Apache-2.0 |
def test_display_output(self, test_input, expected):
"""Create a UserAgentInfo object and test the display method."""
dataklazz = UserAgentInfo(**test_input)
assert dataklazz.display() == expected | Create a UserAgentInfo object and test the display method. | test_display_output | python | pypi/warehouse | tests/unit/events/test_models.py | https://github.com/pypi/warehouse/blob/master/tests/unit/events/test_models.py | Apache-2.0 |
def test_equivalent_version_one_release(self, pyramid_config, db_request):
"""
Test that if a release with a version like '1.0' exists, that a future
upload with an equivalent version like '1.0.0' will not make a second
release
"""
user = UserFactory.create()
Ema... |
Test that if a release with a version like '1.0' exists, that a future
upload with an equivalent version like '1.0.0' will not make a second
release
| test_equivalent_version_one_release | python | pypi/warehouse | tests/unit/forklift/test_legacy.py | https://github.com/pypi/warehouse/blob/master/tests/unit/forklift/test_legacy.py | Apache-2.0 |
def test_equivalent_canonical_versions(self, pyramid_config, db_request):
"""
Test that if more than one release with equivalent canonical versions
exists, we use the one that is an exact match
"""
user = UserFactory.create()
EmailFactory.create(user=user)
projec... |
Test that if more than one release with equivalent canonical versions
exists, we use the one that is an exact match
| test_equivalent_canonical_versions | python | pypi/warehouse | tests/unit/forklift/test_legacy.py | https://github.com/pypi/warehouse/blob/master/tests/unit/forklift/test_legacy.py | Apache-2.0 |
def test_valid_dynamic_but_missing_from_our_enum(self, monkeypatch):
"""
Handles the case where there are new metadata fields that pypa/packaging
considers to be valid, but don't exist in our enum and would otherwise fail
when inserting them into the database
"""
monkeypa... |
Handles the case where there are new metadata fields that pypa/packaging
considers to be valid, but don't exist in our enum and would otherwise fail
when inserting them into the database
| test_valid_dynamic_but_missing_from_our_enum | python | pypi/warehouse | tests/unit/forklift/test_metadata.py | https://github.com/pypi/warehouse/blob/master/tests/unit/forklift/test_metadata.py | Apache-2.0 |
def test_all_releases_yanked(self, monkeypatch, db_request):
"""
If all releases are yanked, the endpoint should return the same release as
if none of the releases are yanked.
"""
project = ProjectFactory.create()
ReleaseFactory.create(project=project, version="1.0", ya... |
If all releases are yanked, the endpoint should return the same release as
if none of the releases are yanked.
| test_all_releases_yanked | python | pypi/warehouse | tests/unit/legacy/api/test_json.py | https://github.com/pypi/warehouse/blob/master/tests/unit/legacy/api/test_json.py | Apache-2.0 |
def test_latest_release_yanked(self, monkeypatch, db_request):
"""
If the latest version is yanked, the endpoint should fall back on the
latest non-prerelease version that is not yanked, if one is available.
"""
project = ProjectFactory.create()
ReleaseFactory.create(pr... |
If the latest version is yanked, the endpoint should fall back on the
latest non-prerelease version that is not yanked, if one is available.
| test_latest_release_yanked | python | pypi/warehouse | tests/unit/legacy/api/test_json.py | https://github.com/pypi/warehouse/blob/master/tests/unit/legacy/api/test_json.py | Apache-2.0 |
def test_all_non_prereleases_yanked(self, monkeypatch, db_request):
"""
If all non-prerelease versions are yanked, the endpoint should return the
latest prerelease version that is not yanked.
"""
project = ProjectFactory.create()
ReleaseFactory.create(project=project, v... |
If all non-prerelease versions are yanked, the endpoint should return the
latest prerelease version that is not yanked.
| test_all_non_prereleases_yanked | python | pypi/warehouse | tests/unit/legacy/api/test_json.py | https://github.com/pypi/warehouse/blob/master/tests/unit/legacy/api/test_json.py | Apache-2.0 |
def test_prohibited_mx_domain_error(
self,
monkeypatch,
db_request,
email_address,
mx_record_domain,
prohibited_domain,
):
"""
Similar to `test_prohibited_email_error()`, checking the MX domain.
"""
mock_deliverability_info = {"mx": [(1... |
Similar to `test_prohibited_email_error()`, checking the MX domain.
| test_prohibited_mx_domain_error | python | pypi/warehouse | tests/unit/manage/test_forms.py | https://github.com/pypi/warehouse/blob/master/tests/unit/manage/test_forms.py | Apache-2.0 |
def test_prohibited_mx_domain_passes(
self,
monkeypatch,
db_request,
email_address,
mx_record_domain,
prohibited_domain,
):
"""
Similar to `test_prohibited_email_error()`, allowing if:
- the `registered_domain` part of the email address is **... |
Similar to `test_prohibited_email_error()`, allowing if:
- the `registered_domain` part of the email address is **not** prohibited
- the `registered_domain` part of the MX record is prohibited
This is to allow for cases where the email address that shares MX records with a
... | test_prohibited_mx_domain_passes | python | pypi/warehouse | tests/unit/manage/test_forms.py | https://github.com/pypi/warehouse/blob/master/tests/unit/manage/test_forms.py | Apache-2.0 |
def test_quarantines_project(self, db_request, notification_service, monkeypatch):
"""
Satisfies criteria for auto-quarantine:
- 2 observations
- from different observers
- one of which is an Observer
"""
dummy_task = pretend.stub(name="dummy_task")
user =... |
Satisfies criteria for auto-quarantine:
- 2 observations
- from different observers
- one of which is an Observer
| test_quarantines_project | python | pypi/warehouse | tests/unit/observations/test_tasks.py | https://github.com/pypi/warehouse/blob/master/tests/unit/observations/test_tasks.py | Apache-2.0 |
def test_record_event_with_geoip(self, db_request):
"""
Test to cover condition when record_event is called with geoip_info as
part of the inbound request.
Possibly could be removed once more comprehensive tests are in place,
but nothing explicitly covers `HasEvents.record_event`... |
Test to cover condition when record_event is called with geoip_info as
part of the inbound request.
Possibly could be removed once more comprehensive tests are in place,
but nothing explicitly covers `HasEvents.record_event`
| test_record_event_with_geoip | python | pypi/warehouse | tests/unit/organizations/test_models.py | https://github.com/pypi/warehouse/blob/master/tests/unit/organizations/test_models.py | Apache-2.0 |
def test_acl_for_quarantined_project(self, db_session):
"""
If a Project is quarantined, the Project ACL should disallow any modifications.
"""
project = DBProjectFactory.create(lifecycle_status="quarantine-enter")
owner1 = DBRoleFactory.create(project=project)
owner2 = D... |
If a Project is quarantined, the Project ACL should disallow any modifications.
| test_acl_for_quarantined_project | python | pypi/warehouse | tests/unit/packaging/test_models.py | https://github.com/pypi/warehouse/blob/master/tests/unit/packaging/test_models.py | Apache-2.0 |
def test_acl_for_archived_project(self, db_session):
"""
If a Project is archived, the Project ACL should disallow uploads.
"""
project = DBProjectFactory.create(lifecycle_status="archived")
owner1 = DBRoleFactory.create(project=project)
owner2 = DBRoleFactory.create(proj... |
If a Project is archived, the Project ACL should disallow uploads.
| test_acl_for_archived_project | python | pypi/warehouse | tests/unit/packaging/test_models.py | https://github.com/pypi/warehouse/blob/master/tests/unit/packaging/test_models.py | Apache-2.0 |
def test_deletion_with_trusted_publisher(self, db_session):
"""
When we remove a Project, ensure that we also remove the related
Publisher Association, but not the Publisher itself.
"""
project = DBProjectFactory.create()
publisher = GitHubPublisherFactory.create(projects... |
When we remove a Project, ensure that we also remove the related
Publisher Association, but not the Publisher itself.
| test_deletion_with_trusted_publisher | python | pypi/warehouse | tests/unit/packaging/test_models.py | https://github.com/pypi/warehouse/blob/master/tests/unit/packaging/test_models.py | Apache-2.0 |
def test_deletion_project_with_macaroon_warning(self, db_session, macaroon_service):
"""
When we remove a Project, ensure that we also remove any related
warnings about the use of API tokens from the ProjectMacaroonWarningAssociation
table
"""
project = DBProjectFactory.c... |
When we remove a Project, ensure that we also remove any related
warnings about the use of API tokens from the ProjectMacaroonWarningAssociation
table
| test_deletion_project_with_macaroon_warning | python | pypi/warehouse | tests/unit/packaging/test_models.py | https://github.com/pypi/warehouse/blob/master/tests/unit/packaging/test_models.py | Apache-2.0 |
def test_deletion_macaroon_with_macaroon_warning(
self, db_session, macaroon_service
):
"""
When we remove a Macaroon, ensure that we also remove any related
warnings about the use of API tokens from the ProjectMacaroonWarningAssociation
table
"""
project = DB... |
When we remove a Macaroon, ensure that we also remove any related
warnings about the use of API tokens from the ProjectMacaroonWarningAssociation
table
| test_deletion_macaroon_with_macaroon_warning | python | pypi/warehouse | tests/unit/packaging/test_models.py | https://github.com/pypi/warehouse/blob/master/tests/unit/packaging/test_models.py | Apache-2.0 |
def test_description_relationship(self, db_request):
"""When a Release is deleted, the Description is also deleted."""
release = DBReleaseFactory.create() # also creates a Description
description = release.description
db_request.db.delete(release)
assert release in db_request.... | When a Release is deleted, the Description is also deleted. | test_description_relationship | python | pypi/warehouse | tests/unit/packaging/test_models.py | https://github.com/pypi/warehouse/blob/master/tests/unit/packaging/test_models.py | Apache-2.0 |
def test_requires_python(self, db_session):
"""
Attempt to write a File by setting requires_python directly, which
should fail to validate (it should only be set in Release).
"""
project = DBProjectFactory.create()
release = DBReleaseFactory.create(project=project)
... |
Attempt to write a File by setting requires_python directly, which
should fail to validate (it should only be set in Release).
| test_requires_python | python | pypi/warehouse | tests/unit/packaging/test_models.py | https://github.com/pypi/warehouse/blob/master/tests/unit/packaging/test_models.py | Apache-2.0 |
def test_detail_renders_files_natural_sort(self, db_request):
"""Tests that when a release has multiple versions of Python,
the sort order is most recent Python version first."""
project = ProjectFactory.create()
release = ReleaseFactory.create(project=project, version="3.0")
fil... | Tests that when a release has multiple versions of Python,
the sort order is most recent Python version first. | test_detail_renders_files_natural_sort | python | pypi/warehouse | tests/unit/packaging/test_views.py | https://github.com/pypi/warehouse/blob/master/tests/unit/packaging/test_views.py | Apache-2.0 |
def maybe_set_redis(settings, name, envvar, coercer=None, default=None, db=None):
"""
Note on our DB numbering:
- General purpose caches and temporary storage should go in 1-9
- Celery queues, results, and schedulers should use 10-15
- By default Redis only allows use of 0-15, so db should be ... |
Note on our DB numbering:
- General purpose caches and temporary storage should go in 1-9
- Celery queues, results, and schedulers should use 10-15
- By default Redis only allows use of 0-15, so db should be <16
| maybe_set_redis | python | pypi/warehouse | warehouse/config.py | https://github.com/pypi/warehouse/blob/master/warehouse/config.py | Apache-2.0 |
def format_email(metadata_email: str) -> tuple[str, str]:
"""
Return the name and email address from a metadata RFC-822 string.
Use Jinja's `first` and `last` to access each part in a template.
TODO: Support more than one email address, per RFC-822.
"""
emails = []
for name, email in getaddr... |
Return the name and email address from a metadata RFC-822 string.
Use Jinja's `first` and `last` to access each part in a template.
TODO: Support more than one email address, per RFC-822.
| format_email | python | pypi/warehouse | warehouse/filters.py | https://github.com/pypi/warehouse/blob/master/warehouse/filters.py | Apache-2.0 |
def __call__(self, context: Organization | Team, request):
"""Check organizations are enabled globally and this organization is active.
1. `AdminFlagValue.DISABLE_ORGANIZATIONS` flag is off.
2. `Organization.is_active` is true.
3. `Organization.active_subscription` exists if organizatio... | Check organizations are enabled globally and this organization is active.
1. `AdminFlagValue.DISABLE_ORGANIZATIONS` flag is off.
2. `Organization.is_active` is true.
3. `Organization.active_subscription` exists if organization is a company.
| __call__ | python | pypi/warehouse | warehouse/predicates.py | https://github.com/pypi/warehouse/blob/master/warehouse/predicates.py | Apache-2.0 |
def __new__(cls, *args, **kwargs) -> WarehouseTask:
"""
Override to wrap the `run` method of the task with a new method that
will handle exceptions from the task and retry them if they're retryable.
"""
obj = super().__new__(cls, *args, **kwargs)
if getattr(obj, "__header... |
Override to wrap the `run` method of the task with a new method that
will handle exceptions from the task and retry them if they're retryable.
| __new__ | python | pypi/warehouse | warehouse/tasks.py | https://github.com/pypi/warehouse/blob/master/warehouse/tasks.py | Apache-2.0 |
def get_request(self) -> Request:
"""
Get a request object to use for this task.
This will either return the request object that was injected into the
task when it was called, or it will create a new request object to use
for the task.
Note: The `type: ignore` comments ... |
Get a request object to use for this task.
This will either return the request object that was injected into the
task when it was called, or it will create a new request object to use
for the task.
Note: The `type: ignore` comments are necessary because the `pyramid_env`
... | get_request | python | pypi/warehouse | warehouse/tasks.py | https://github.com/pypi/warehouse/blob/master/warehouse/tasks.py | Apache-2.0 |
def after_return(self, status, retval, task_id, args, kwargs, einfo):
"""
Called after the task has returned. This is where we'll clean up the
request object that we injected into the task.
"""
if hasattr(self.request, "pyramid_env"):
pyramid_env = self.request.pyrami... |
Called after the task has returned. This is where we'll clean up the
request object that we injected into the task.
| after_return | python | pypi/warehouse | warehouse/tasks.py | https://github.com/pypi/warehouse/blob/master/warehouse/tasks.py | Apache-2.0 |
def retry(self, *args, **kwargs):
"""
Override the retry method to increment a metric when a task is retried.
This is necessary because the `retry` method is called when a task is
retried, and we want to track how many times a task has been retried.
"""
request = get_cur... |
Override the retry method to increment a metric when a task is retried.
This is necessary because the `retry` method is called when a task is
retried, and we want to track how many times a task has been retried.
| retry | python | pypi/warehouse | warehouse/tasks.py | https://github.com/pypi/warehouse/blob/master/warehouse/tasks.py | Apache-2.0 |
def task(**kwargs):
"""
A decorator that can be used to define a Celery task.
A thin wrapper around Celery's `task` decorator that allows us to attach
the task to the Celery app when the configuration is scanned during the
application startup.
This decorator also sets the `shared` option to `F... |
A decorator that can be used to define a Celery task.
A thin wrapper around Celery's `task` decorator that allows us to attach
the task to the Celery app when the configuration is scanned during the
application startup.
This decorator also sets the `shared` option to `False` by default. This
... | task | python | pypi/warehouse | warehouse/tasks.py | https://github.com/pypi/warehouse/blob/master/warehouse/tasks.py | Apache-2.0 |
def favicon(request: Request) -> FileResponse:
"""
Return static favicon.ico file
The favicon path is not known, static files are compressed into a dist/ directory.
"""
favicon_filename = Path(
request.static_path("warehouse:static/dist/images/favicon.ico")
).name
favicon_path = (
... |
Return static favicon.ico file
The favicon path is not known, static files are compressed into a dist/ directory.
| favicon | python | pypi/warehouse | warehouse/views.py | https://github.com/pypi/warehouse/blob/master/warehouse/views.py | Apache-2.0 |
def form_filters_tree(split_list):
"""
Takes a list of lists, each of them containing a filter and
one of its children.
Returns a dictionary, each key being a filter and each value being
the filter's children.
"""
d: dict[str, dict] = {}
for list_ in split... |
Takes a list of lists, each of them containing a filter and
one of its children.
Returns a dictionary, each key being a filter and each value being
the filter's children.
| form_filters_tree | python | pypi/warehouse | warehouse/views.py | https://github.com/pypi/warehouse/blob/master/warehouse/views.py | Apache-2.0 |
def process_available_filters():
"""
Processes available filters and returns a list of dictionaries.
The value of a key in the dictionary represents its children
"""
sorted_filters = sorted(available_filters.items(), key=filter_key)
output = []
for f in sorted_fil... |
Processes available filters and returns a list of dictionaries.
The value of a key in the dictionary represents its children
| process_available_filters | python | pypi/warehouse | warehouse/views.py | https://github.com/pypi/warehouse/blob/master/warehouse/views.py | Apache-2.0 |
def validate_username_or_email(self, field):
"""
Check if the input is structurally correct, i.e. either a string or email.
Further validation happens in the View.
"""
if "@" in field.data:
# Additional checks for the validity of the address
try:
... |
Check if the input is structurally correct, i.e. either a string or email.
Further validation happens in the View.
| validate_username_or_email | python | pypi/warehouse | warehouse/accounts/forms.py | https://github.com/pypi/warehouse/blob/master/warehouse/accounts/forms.py | Apache-2.0 |
def get_user(user_id):
"""
Return the user object that represents the given userid, or None if
there is no user for that ID.
""" |
Return the user object that represents the given userid, or None if
there is no user for that ID.
| get_user | python | pypi/warehouse | warehouse/accounts/interfaces.py | https://github.com/pypi/warehouse/blob/master/warehouse/accounts/interfaces.py | Apache-2.0 |
def get_user_by_username(username):
"""
Return the user object corresponding with the given username, or None
if there is no user with that username.
""" |
Return the user object corresponding with the given username, or None
if there is no user with that username.
| get_user_by_username | python | pypi/warehouse | warehouse/accounts/interfaces.py | https://github.com/pypi/warehouse/blob/master/warehouse/accounts/interfaces.py | Apache-2.0 |
def get_user_by_email(email):
"""
Return the user object corresponding with the given email, or None
if there is no user with that email.
""" |
Return the user object corresponding with the given email, or None
if there is no user with that email.
| get_user_by_email | python | pypi/warehouse | warehouse/accounts/interfaces.py | https://github.com/pypi/warehouse/blob/master/warehouse/accounts/interfaces.py | Apache-2.0 |
def get_users_by_prefix(prefix: str) -> list:
"""
Return a list of user objects that match the given prefix.
""" |
Return a list of user objects that match the given prefix.
| get_users_by_prefix | python | pypi/warehouse | warehouse/accounts/interfaces.py | https://github.com/pypi/warehouse/blob/master/warehouse/accounts/interfaces.py | Apache-2.0 |
def find_userid(username):
"""
Find the unique user identifier for the given username or None if there
is no user with the given username.
""" |
Find the unique user identifier for the given username or None if there
is no user with the given username.
| find_userid | python | pypi/warehouse | warehouse/accounts/interfaces.py | https://github.com/pypi/warehouse/blob/master/warehouse/accounts/interfaces.py | Apache-2.0 |
def check_password(user_id, password, *, tags=None):
"""
Returns a boolean representing whether the given password is valid for
the given userid.
May have an optional list of tags, which allows identifying the purpose of
checking the password.
""" |
Returns a boolean representing whether the given password is valid for
the given userid.
May have an optional list of tags, which allows identifying the purpose of
checking the password.
| check_password | python | pypi/warehouse | warehouse/accounts/interfaces.py | https://github.com/pypi/warehouse/blob/master/warehouse/accounts/interfaces.py | Apache-2.0 |
def create_user(username, name, password):
"""
Accepts a user object, and attempts to create a user with those
attributes.
A UserAlreadyExists Exception is raised if the user already exists.
""" |
Accepts a user object, and attempts to create a user with those
attributes.
A UserAlreadyExists Exception is raised if the user already exists.
| create_user | python | pypi/warehouse | warehouse/accounts/interfaces.py | https://github.com/pypi/warehouse/blob/master/warehouse/accounts/interfaces.py | Apache-2.0 |
def add_email(user_id, email_address, primary=False, verified=False, public=False):
"""
Adds an email for the provided user_id
""" |
Adds an email for the provided user_id
| add_email | python | pypi/warehouse | warehouse/accounts/interfaces.py | https://github.com/pypi/warehouse/blob/master/warehouse/accounts/interfaces.py | Apache-2.0 |
def disable_password(user_id, request, reason=None):
"""
Disables the given user's password, preventing further login until the user
resets their password. If a reason was given, this will be persisted and reset
when the user is re-enabled.
""" |
Disables the given user's password, preventing further login until the user
resets their password. If a reason was given, this will be persisted and reset
when the user is re-enabled.
| disable_password | python | pypi/warehouse | warehouse/accounts/interfaces.py | https://github.com/pypi/warehouse/blob/master/warehouse/accounts/interfaces.py | Apache-2.0 |
def is_disabled(user_id):
"""
Checks if a user has been disabled, and returns a tuple of
(IsDisabled: bool, Reason: Optional[DisableReason])
""" |
Checks if a user has been disabled, and returns a tuple of
(IsDisabled: bool, Reason: Optional[DisableReason])
| is_disabled | python | pypi/warehouse | warehouse/accounts/interfaces.py | https://github.com/pypi/warehouse/blob/master/warehouse/accounts/interfaces.py | Apache-2.0 |
def has_two_factor(user_id):
"""
Returns True if the user has any form of two factor
authentication and is allowed to use it.
""" |
Returns True if the user has any form of two factor
authentication and is allowed to use it.
| has_two_factor | python | pypi/warehouse | warehouse/accounts/interfaces.py | https://github.com/pypi/warehouse/blob/master/warehouse/accounts/interfaces.py | Apache-2.0 |
def has_totp(user_id):
"""
Returns True if the user has a TOTP device provisioned.
""" |
Returns True if the user has a TOTP device provisioned.
| has_totp | python | pypi/warehouse | warehouse/accounts/interfaces.py | https://github.com/pypi/warehouse/blob/master/warehouse/accounts/interfaces.py | Apache-2.0 |
def has_webauthn(user_id):
"""
Returns True if the user has a security key provisioned.
""" |
Returns True if the user has a security key provisioned.
| has_webauthn | python | pypi/warehouse | warehouse/accounts/interfaces.py | https://github.com/pypi/warehouse/blob/master/warehouse/accounts/interfaces.py | Apache-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.