prompt_id int64 0 941 | project stringclasses 24
values | module stringlengths 7 49 | class stringlengths 0 32 | method stringlengths 2 37 | focal_method_txt stringlengths 43 41.5k | focal_method_lines listlengths 2 2 | in_stack bool 2
classes | globals listlengths 0 16 | type_context stringlengths 79 41.9k | has_branch bool 2
classes | total_branches int64 0 3 |
|---|---|---|---|---|---|---|---|---|---|---|---|
445 | pysnooper | pysnooper.variables | BaseVariable | __init__ | def __init__(self, source, exclude=()):
self.source = source
self.exclude = utils.ensure_tuple(exclude)
self.code = compile(source, '<variable>', 'eval')
if needs_parentheses(source):
self.unambiguous_source = '({})'.format(source)
else:
self.unambiguo... | [
20,
27
] | false | [] | import itertools
import abc
from copy import deepcopy
from . import utils
from . import pycompat
class BaseVariable(pycompat.ABC):
def __init__(self, source, exclude=()):
self.source = source
self.exclude = utils.ensure_tuple(exclude)
self.code = compile(source, '<variable>', 'eval')
... | true | 2 |
446 | pysnooper | pysnooper.variables | BaseVariable | items | def items(self, frame, normalize=False):
try:
main_value = eval(self.code, frame.f_globals or {}, frame.f_locals)
except Exception:
return ()
return self._items(main_value, normalize) | [
29,
34
] | false | [] | import itertools
import abc
from copy import deepcopy
from . import utils
from . import pycompat
class BaseVariable(pycompat.ABC):
def __init__(self, source, exclude=()):
self.source = source
self.exclude = utils.ensure_tuple(exclude)
self.code = compile(source, '<variable>', 'eval')
... | false | 0 |
447 | pysnooper | pysnooper.variables | BaseVariable | __eq__ | def __eq__(self, other):
return (isinstance(other, BaseVariable) and
self._fingerprint == other._fingerprint) | [
47,
48
] | false | [] | import itertools
import abc
from copy import deepcopy
from . import utils
from . import pycompat
class BaseVariable(pycompat.ABC):
def __init__(self, source, exclude=()):
self.source = source
self.exclude = utils.ensure_tuple(exclude)
self.code = compile(source, '<variable>', 'eval')
... | false | 0 |
448 | pysnooper | pysnooper.variables | Indices | __getitem__ | def __getitem__(self, item):
assert isinstance(item, slice)
result = deepcopy(self)
result._slice = item
return result | [
116,
120
] | false | [] | import itertools
import abc
from copy import deepcopy
from . import utils
from . import pycompat
class Indices(Keys):
_slice = slice(None)
def __getitem__(self, item):
assert isinstance(item, slice)
result = deepcopy(self)
result._slice = item
return result | false | 0 |
449 | pytutils | pytutils.env | parse_env_file_contents | def parse_env_file_contents(lines: typing.Iterable[str] = None) -> typing.Generator[typing.Tuple[str, str], None, None]:
"""
Parses env file content.
From honcho.
>>> lines = ['TEST=${HOME}/yeee', 'THISIS=~/a/test', 'YOLO=~/swaggins/$NONEXISTENT_VAR_THAT_DOES_NOT_EXIST']
>>> load_env_file(lines, w... | [
12,
40
] | true | [] | import collections
import os
import re
import typing
def parse_env_file_contents(lines: typing.Iterable[str] = None) -> typing.Generator[typing.Tuple[str, str], None, None]:
"""
Parses env file content.
From honcho.
>>> lines = ['TEST=${HOME}/yeee', 'THISIS=~/a/test', 'YOLO=~/swaggins/$NONEXISTENT_... | true | 2 | |
450 | pytutils | pytutils.env | load_env_file | def load_env_file(lines: typing.Iterable[str], write_environ: typing.MutableMapping = os.environ) -> collections.OrderedDict:
"""
Loads (and returns) an env file specified by `filename` into the mapping `environ`.
>>> lines = ['TEST=${HOME}/yeee-$PATH', 'THISIS=~/a/test', 'YOLO=~/swaggins/$NONEXISTENT_VAR_... | [
43,
66
] | true | [] | import collections
import os
import re
import typing
def load_env_file(lines: typing.Iterable[str], write_environ: typing.MutableMapping = os.environ) -> collections.OrderedDict:
"""
Loads (and returns) an env file specified by `filename` into the mapping `environ`.
>>> lines = ['TEST=${HOME}/yeee-$PATH... | true | 2 | |
451 | pytutils | pytutils.files | islurp | def islurp(filename, mode='r', iter_by=LINEMODE, allow_stdin=True, expanduser=True, expandvars=True):
"""
Read [expanded] `filename` and yield each (line | chunk).
:param str filename: File path
:param str mode: Use this mode to open `filename`, ala `r` for text (default), `rb` for binary, etc.
:pa... | [
11,
45
] | true | [
"LINEMODE",
"islurp",
"slurp"
] | import os
import sys
import functools
islurp.LINEMODE = LINEMODE
islurp.LINEMODE = LINEMODE
slurp = islurp
def islurp(filename, mode='r', iter_by=LINEMODE, allow_stdin=True, expanduser=True, expandvars=True):
"""
Read [expanded] `filename` and yield each (line | chunk).
:param str filename: File path
... | true | 2 | |
452 | pytutils | pytutils.files | burp | def burp(filename, contents, mode='w', allow_stdout=True, expanduser=True, expandvars=True):
"""
Write `contents` to `filename`.
"""
if filename == '-' and allow_stdout:
sys.stdout.write(contents)
else:
if expanduser:
filename = os.path.expanduser(filename)
if exp... | [
54,
67
] | true | [
"LINEMODE",
"islurp",
"slurp"
] | import os
import sys
import functools
islurp.LINEMODE = LINEMODE
islurp.LINEMODE = LINEMODE
slurp = islurp
def burp(filename, contents, mode='w', allow_stdout=True, expanduser=True, expandvars=True):
"""
Write `contents` to `filename`.
"""
if filename == '-' and allow_stdout:
sys.stdout.write(... | true | 2 | |
453 | pytutils | pytutils.lazy.lazy_import | IllegalUseOfScopeReplacer | __unicode__ | def __unicode__(self):
u = self._format()
if isinstance(u, str):
# Try decoding the str using the default encoding.
u = unicode(u)
elif not isinstance(u, unicode):
# Try to make a unicode object from it, because __unicode__ must
# return a unic... | [
84,
93
] | true | [] |
class IllegalUseOfScopeReplacer(Exception):
_fmt = ("ScopeReplacer object %(name)r was used incorrectly:"
" %(msg)s%(extra)s")
def __init__(self, name, msg, extra=None):
self.name = name
self.msg = msg
if extra:
self.extra = ': ' + str(extra)
else:
... | true | 2 |
454 | pytutils | pytutils.lazy.lazy_import | IllegalUseOfScopeReplacer | __str__ | def __str__(self):
s = self._format()
if isinstance(s, unicode):
s = s.encode('utf8')
else:
# __str__ must return a str.
s = str(s)
return s | [
95,
102
] | true | [] |
class IllegalUseOfScopeReplacer(Exception):
_fmt = ("ScopeReplacer object %(name)r was used incorrectly:"
" %(msg)s%(extra)s")
def __init__(self, name, msg, extra=None):
self.name = name
self.msg = msg
if extra:
self.extra = ': ' + str(extra)
else:
... | true | 2 |
455 | pytutils | pytutils.lazy.lazy_import | IllegalUseOfScopeReplacer | __eq__ | def __eq__(self, other):
if self.__class__ is not other.__class__:
return NotImplemented
return self.__dict__ == other.__dict__ | [
114,
117
] | true | [] |
class IllegalUseOfScopeReplacer(Exception):
_fmt = ("ScopeReplacer object %(name)r was used incorrectly:"
" %(msg)s%(extra)s")
def __init__(self, name, msg, extra=None):
self.name = name
self.msg = msg
if extra:
self.extra = ': ' + str(extra)
else:
... | true | 2 |
456 | pytutils | pytutils.lazy.lazy_import | ScopeReplacer | __getattribute__ | def __getattribute__(self, attr):
obj = object.__getattribute__(self, '_resolve')()
return getattr(obj, attr) | [
180,
182
] | true | [] |
class ScopeReplacer(object):
__slots__ = ('_scope', '_factory', '_name', '_real_obj')
_should_proxy = True
def __init__(self, scope, factory, name):
"""Create a temporary object in the specified scope.
Once used, a real object will be placed in the scope.
:param scope: The sc... | false | 0 |
457 | pytutils | pytutils.lazy.lazy_import | ScopeReplacer | __setattr__ | def __setattr__(self, attr, value):
obj = object.__getattribute__(self, '_resolve')()
return setattr(obj, attr, value) | [
184,
186
] | true | [] |
class ScopeReplacer(object):
__slots__ = ('_scope', '_factory', '_name', '_real_obj')
_should_proxy = True
def __init__(self, scope, factory, name):
"""Create a temporary object in the specified scope.
Once used, a real object will be placed in the scope.
:param scope: The sc... | false | 0 |
458 | pytutils | pytutils.lazy.lazy_import | ScopeReplacer | __call__ | def __call__(self, *args, **kwargs):
obj = object.__getattribute__(self, '_resolve')()
return obj(*args, **kwargs) | [
188,
190
] | true | [] |
class ScopeReplacer(object):
__slots__ = ('_scope', '_factory', '_name', '_real_obj')
_should_proxy = True
def __init__(self, scope, factory, name):
"""Create a temporary object in the specified scope.
Once used, a real object will be placed in the scope.
:param scope: The sc... | false | 0 |
459 | pytutils | pytutils.lazy.lazy_regex | InvalidPattern | __unicode__ | def __unicode__(self):
u = self._format()
if isinstance(u, str):
# Try decoding the str using the default encoding.
u = unicode(u)
elif not isinstance(u, unicode):
# Try to make a unicode object from it, because __unicode__ must
# return a unic... | [
61,
70
] | true | [
"_real_re_compile"
] | import re
_real_re_compile = re.compile
class InvalidPattern(ValueError):
_fmt = ('Invalid pattern(s) found. %(msg)s')
def __init__(self, msg):
self.msg = msg
def __unicode__(self):
u = self._format()
if isinstance(u, str):
# Try decoding the str using the default en... | true | 2 |
460 | pytutils | pytutils.lazy.lazy_regex | InvalidPattern | __str__ | def __str__(self):
s = self._format()
if isinstance(s, unicode):
s = s.encode('utf8')
else:
# __str__ must return a str.
s = str(s)
return s | [
72,
79
] | true | [
"_real_re_compile"
] | import re
_real_re_compile = re.compile
class InvalidPattern(ValueError):
_fmt = ('Invalid pattern(s) found. %(msg)s')
def __init__(self, msg):
self.msg = msg
def __str__(self):
s = self._format()
if isinstance(s, unicode):
s = s.encode('utf8')
else:
... | true | 2 |
461 | pytutils | pytutils.lazy.lazy_regex | LazyRegex | __setstate__ | def __setstate__(self, dict):
"""Restore from a pickled state."""
self._real_regex = None
setattr(self, "_regex_args", dict["args"])
setattr(self, "_regex_kwargs", dict["kwargs"]) | [
146,
150
] | true | [
"_real_re_compile"
] | import re
_real_re_compile = re.compile
class LazyRegex(object):
_regex_attributes_to_copy = [
'__copy__', '__deepcopy__', 'findall', 'finditer', 'match',
'scanner', 'search', 'split', 'sub', 'subn'
]
__slots__ = ['_real_regex', '_regex_args', '_regex_kwarg... | false | 0 |
462 | pytutils | pytutils.lazy.lazy_regex | LazyRegex | __getattr__ | def __getattr__(self, attr):
"""Return a member from the proxied regex object.
If the regex hasn't been compiled yet, compile it
"""
if self._real_regex is None:
self._compile_and_collapse()
# Once we have compiled, the only time we should come here
# is ... | [
152,
161
] | true | [
"_real_re_compile"
] | import re
_real_re_compile = re.compile
class LazyRegex(object):
_regex_attributes_to_copy = [
'__copy__', '__deepcopy__', 'findall', 'finditer', 'match',
'scanner', 'search', 'split', 'sub', 'subn'
]
__slots__ = ['_real_regex', '_regex_args', '_regex_kwarg... | true | 2 |
463 | pytutils | pytutils.lazy.simple_import | make_lazy | def make_lazy(module_path):
"""
Mark that this module should not be imported until an
attribute is needed off of it.
"""
sys_modules = sys.modules # cache in the locals
# store our 'instance' data in the closure.
module = NonLocal(None)
class LazyModule(_LazyModuleMarker):
"""... | [
23,
60
] | true | [] | import sys
from types import ModuleType
class NonLocal(object):
__slots__ = ['value']
def __init__(self, value):
self.value = value
def make_lazy(module_path):
"""
Mark that this module should not be imported until an
attribute is needed off of it.
"""
sys_modules = sys.modules... | true | 2 | |
464 | pytutils | pytutils.log | configure | def configure(config=None, env_var='LOGGING', default=DEFAULT_CONFIG):
"""
>>> log = logging.getLogger(__name__)
>>> configure()
>>> log.info('test')
"""
cfg = get_config(config, env_var, default)
try:
logging.config.dictConfig(cfg)
except TypeError as exc:
try:
... | [
80,
96
] | true | [
"DEFAULT_CONFIG",
"_CONFIGURED",
"getLogger"
] | import logging
import logging.config
import inspect
import sys
import os
from contextlib import contextmanager
DEFAULT_CONFIG = dict(
version=1,
disable_existing_loggers=False,
formatters={
'colored': {
'()': 'colorlog.ColoredFormatter',
'format':
'%(bg_black... | false | 0 | |
465 | pytutils | pytutils.log | get_config | def get_config(given=None, env_var=None, default=None):
config = given
if not config and env_var:
config = os.environ.get(env_var)
if not config and default:
config = default
if config is None:
raise ValueError('Invalid logging config: %s' % config)
if isinstance(config, ... | [
99,
127
] | true | [
"DEFAULT_CONFIG",
"_CONFIGURED",
"getLogger"
] | import logging
import logging.config
import inspect
import sys
import os
from contextlib import contextmanager
DEFAULT_CONFIG = dict(
version=1,
disable_existing_loggers=False,
formatters={
'colored': {
'()': 'colorlog.ColoredFormatter',
'format':
'%(bg_black... | true | 2 | |
466 | pytutils | pytutils.path | join_each | def join_each(parent, iterable):
for p in iterable:
yield os.path.join(parent, p) | [
3,
5
] | true | [] | import os
def join_each(parent, iterable):
for p in iterable:
yield os.path.join(parent, p) | true | 2 | |
467 | pytutils | pytutils.props | lazyperclassproperty | def lazyperclassproperty(fn):
"""
Lazy/Cached class property that stores separate instances per class/inheritor so there's no overlap.
"""
@classproperty
def _lazyclassprop(cls):
attr_name = '_%s_lazy_%s' % (cls.__name__, fn.__name__)
if not hasattr(cls, attr_name):
seta... | [
24,
36
] | true | [
"classproperty"
] |
classproperty = roclassproperty
def lazyperclassproperty(fn):
"""
Lazy/Cached class property that stores separate instances per class/inheritor so there's no overlap.
"""
@classproperty
def _lazyclassprop(cls):
attr_name = '_%s_lazy_%s' % (cls.__name__, fn.__name__)
if not hasatt... | true | 2 | |
468 | pytutils | pytutils.props | lazyclassproperty | def lazyclassproperty(fn):
"""
Lazy/Cached class property.
"""
attr_name = '_lazy_' + fn.__name__
@classproperty
def _lazyclassprop(cls):
if not hasattr(cls, attr_name):
setattr(cls, attr_name, fn(cls))
return getattr(cls, attr_name)
return _lazyclassprop | [
39,
51
] | true | [
"classproperty"
] |
classproperty = roclassproperty
def lazyclassproperty(fn):
"""
Lazy/Cached class property.
"""
attr_name = '_lazy_' + fn.__name__
@classproperty
def _lazyclassprop(cls):
if not hasattr(cls, attr_name):
setattr(cls, attr_name, fn(cls))
return getattr(cls, attr_name... | true | 2 | |
469 | pytutils | pytutils.trees | get_tree_node | def get_tree_node(mapping, key, default=_sentinel, parent=False):
"""
Fetch arbitrary node from a tree-like mapping structure with traversal help:
Dimension can be specified via ':'
Arguments:
mapping collections.Mapping: Mapping to fetch from
key str|unicode: Key to lookup, allowing fo... | [
5,
35
] | true | [
"_sentinel"
] | import collections
_sentinel = object()
def get_tree_node(mapping, key, default=_sentinel, parent=False):
"""
Fetch arbitrary node from a tree-like mapping structure with traversal help:
Dimension can be specified via ':'
Arguments:
mapping collections.Mapping: Mapping to fetch from
k... | true | 2 | |
470 | pytutils | pytutils.trees | set_tree_node | def set_tree_node(mapping, key, value):
"""
Set arbitrary node on a tree-like mapping structure, allowing for : notation to signify dimension.
Arguments:
mapping collections.Mapping: Mapping to fetch from
key str|unicode: Key to set, allowing for : notation
value str|unicode: Value ... | [
38,
55
] | true | [
"_sentinel"
] | import collections
_sentinel = object()
def set_tree_node(mapping, key, value):
"""
Set arbitrary node on a tree-like mapping structure, allowing for : notation to signify dimension.
Arguments:
mapping collections.Mapping: Mapping to fetch from
key str|unicode: Key to set, allowing for : ... | false | 0 | |
471 | pytutils | pytutils.trees | Tree | __init__ | def __init__(self, initial=None, namespace='', initial_is_ref=False):
if initial is not None and initial_is_ref:
self.data = initial_is_ref
self.namespace = namespace
super(Tree, self).__init__(self.__class__)
if initial is not None:
self.update(initial) | [
71,
77
] | true | [
"_sentinel"
] | import collections
_sentinel = object()
class Tree(collections.defaultdict):
namespace = None
get = __getitem__
def __init__(self, initial=None, namespace='', initial_is_ref=False):
if initial is not None and initial_is_ref:
self.data = initial_is_ref
self.namespace = namesp... | true | 2 |
472 | pytutils | pytutils.urls | update_query_params | def update_query_params(url, params, doseq=True):
"""
Update and/or insert query parameters in a URL.
>>> update_query_params('http://example.com?foo=bar&biz=baz', dict(foo='stuff'))
'http://example.com?...foo=stuff...'
:param url: URL
:type url: str
:param kwargs: Query parameters
:ty... | [
8,
30
] | true | [] |
def update_query_params(url, params, doseq=True):
"""
Update and/or insert query parameters in a URL.
>>> update_query_params('http://example.com?foo=bar&biz=baz', dict(foo='stuff'))
'http://example.com?...foo=stuff...'
:param url: URL
:type url: str
:param kwargs: Query parameters
... | false | 0 | |
473 | sanic | sanic.blueprint_group | BlueprintGroup | __init__ | def __init__(self, url_prefix=None, version=None, strict_slashes=None):
"""
Create a new Blueprint Group
:param url_prefix: URL: to be prefixed before all the Blueprint Prefix
:param version: API Version for the blueprint group. This will be
inherited by each of the Blue... | [
58,
70
] | false | [] | from collections.abc import MutableSequence
from typing import List, Optional, Union
import sanic
class BlueprintGroup(MutableSequence):
__slots__ = ("_blueprints", "_url_prefix", "_version", "_strict_slashes")
def __init__(self, url_prefix=None, version=None, strict_slashes=None):
"""
Crea... | false | 0 |
474 | sanic | sanic.blueprint_group | BlueprintGroup | __iter__ | def __iter__(self):
"""
Tun the class Blueprint Group into an Iterable item
"""
return iter(self._blueprints) | [
109,
113
] | false | [] | from collections.abc import MutableSequence
from typing import List, Optional, Union
import sanic
class BlueprintGroup(MutableSequence):
__slots__ = ("_blueprints", "_url_prefix", "_version", "_strict_slashes")
def __init__(self, url_prefix=None, version=None, strict_slashes=None):
"""
Crea... | false | 0 |
475 | sanic | sanic.blueprint_group | BlueprintGroup | __getitem__ | def __getitem__(self, item):
"""
This method returns a blueprint inside the group specified by
an index value. This will enable indexing, splice and slicing
of the blueprint group like we can do with regular list/tuple.
This method is provided to ensure backward compatibilit... | [
115,
127
] | false | [] | from collections.abc import MutableSequence
from typing import List, Optional, Union
import sanic
class BlueprintGroup(MutableSequence):
__slots__ = ("_blueprints", "_url_prefix", "_version", "_strict_slashes")
def __init__(self, url_prefix=None, version=None, strict_slashes=None):
"""
Crea... | false | 0 |
476 | sanic | sanic.blueprint_group | BlueprintGroup | __setitem__ | def __setitem__(self, index, item) -> None:
"""
Abstract method implemented to turn the `BlueprintGroup` class
into a list like object to support all the existing behavior.
This method is used to perform the list's indexed setter operation.
:param index: Index to use for in... | [
129,
140
] | false | [] | from collections.abc import MutableSequence
from typing import List, Optional, Union
import sanic
class BlueprintGroup(MutableSequence):
__slots__ = ("_blueprints", "_url_prefix", "_version", "_strict_slashes")
def __init__(self, url_prefix=None, version=None, strict_slashes=None):
"""
Crea... | false | 0 |
477 | sanic | sanic.blueprint_group | BlueprintGroup | __delitem__ | def __delitem__(self, index) -> None:
"""
Abstract method implemented to turn the `BlueprintGroup` class
into a list like object to support all the existing behavior.
This method is used to delete an item from the list of blueprint
groups like it can be done on a regular lis... | [
142,
153
] | false | [] | from collections.abc import MutableSequence
from typing import List, Optional, Union
import sanic
class BlueprintGroup(MutableSequence):
__slots__ = ("_blueprints", "_url_prefix", "_version", "_strict_slashes")
def __init__(self, url_prefix=None, version=None, strict_slashes=None):
"""
Crea... | false | 0 |
478 | sanic | sanic.blueprint_group | BlueprintGroup | __len__ | def __len__(self) -> int:
"""
Get the Length of the blueprint group object.
:return: Length of Blueprint group object
"""
return len(self._blueprints) | [
155,
161
] | false | [] | from collections.abc import MutableSequence
from typing import List, Optional, Union
import sanic
class BlueprintGroup(MutableSequence):
__slots__ = ("_blueprints", "_url_prefix", "_version", "_strict_slashes")
def __init__(self, url_prefix=None, version=None, strict_slashes=None):
"""
Crea... | false | 0 |
479 | sanic | sanic.blueprint_group | BlueprintGroup | append | def append(self, value: "sanic.Blueprint") -> None:
"""
The Abstract class `MutableSequence` leverages this append method to
perform the `BlueprintGroup.append` operation.
:param value: New `Blueprint` object.
:return: None
"""
self._blueprints.append(self._sa... | [
181,
188
] | false | [] | from collections.abc import MutableSequence
from typing import List, Optional, Union
import sanic
class BlueprintGroup(MutableSequence):
__slots__ = ("_blueprints", "_url_prefix", "_version", "_strict_slashes")
def __init__(self, url_prefix=None, version=None, strict_slashes=None):
"""
Crea... | false | 0 |
480 | sanic | sanic.blueprint_group | BlueprintGroup | insert | def insert(self, index: int, item: "sanic.Blueprint") -> None:
"""
The Abstract class `MutableSequence` leverages this insert method to
perform the `BlueprintGroup.append` operation.
:param index: Index to use for removing a new Blueprint item
:param item: New `Blueprint` ob... | [
190,
199
] | false | [] | from collections.abc import MutableSequence
from typing import List, Optional, Union
import sanic
class BlueprintGroup(MutableSequence):
__slots__ = ("_blueprints", "_url_prefix", "_version", "_strict_slashes")
def __init__(self, url_prefix=None, version=None, strict_slashes=None):
"""
Crea... | false | 0 |
481 | sanic | sanic.blueprint_group | BlueprintGroup | middleware | def middleware(self, *args, **kwargs):
"""
A decorator that can be used to implement a Middleware plugin to
all of the Blueprints that belongs to this specific Blueprint Group.
In case of nested Blueprint Groups, the same middleware is applied
across each of the Blueprints r... | [
201,
222
] | false | [] | from collections.abc import MutableSequence
from typing import List, Optional, Union
import sanic
class BlueprintGroup(MutableSequence):
__slots__ = ("_blueprints", "_url_prefix", "_version", "_strict_slashes")
def __init__(self, url_prefix=None, version=None, strict_slashes=None):
"""
Crea... | true | 2 |
482 | sanic | sanic.cookies | CookieJar | __setitem__ | def __setitem__(self, key, value):
# If this cookie doesn't exist, add it to the header keys
if not self.cookie_headers.get(key):
cookie = Cookie(key, value)
cookie["path"] = "/"
self.cookie_headers[key] = self.header_key
self.headers.add(self.header_k... | [
56,
65
] | false | [
"DEFAULT_MAX_AGE",
"_LegalChars",
"_UnescapedChars",
"_Translator",
"_is_legal_key"
] | import re
import string
from datetime import datetime
from typing import Dict
DEFAULT_MAX_AGE = 0
_LegalChars = string.ascii_letters + string.digits + "!#$%&'*+-.^_`|~:"
_UnescapedChars = _LegalChars + " ()/<=>?@[]{}"
_Translator = {
n: "\\%03o" % n for n in set(range(256)) - set(map(ord, _UnescapedChars))
}
_is_l... | true | 2 |
483 | sanic | sanic.cookies | CookieJar | __delitem__ | def __delitem__(self, key):
if key not in self.cookie_headers:
self[key] = ""
self[key]["max-age"] = 0
else:
cookie_header = self.cookie_headers[key]
# remove it from header
cookies = self.headers.popall(cookie_header)
for cooki... | [
67,
79
] | false | [
"DEFAULT_MAX_AGE",
"_LegalChars",
"_UnescapedChars",
"_Translator",
"_is_legal_key"
] | import re
import string
from datetime import datetime
from typing import Dict
DEFAULT_MAX_AGE = 0
_LegalChars = string.ascii_letters + string.digits + "!#$%&'*+-.^_`|~:"
_UnescapedChars = _LegalChars + " ()/<=>?@[]{}"
_Translator = {
n: "\\%03o" % n for n in set(range(256)) - set(map(ord, _UnescapedChars))
}
_is_l... | true | 2 |
484 | sanic | sanic.cookies | Cookie | __setitem__ | def __setitem__(self, key, value):
if key not in self._keys:
raise KeyError("Unknown cookie property")
if value is not False:
if key.lower() == "max-age":
if not str(value).isdigit():
raise ValueError("Cookie max-age must be an integer")
... | [
107,
119
] | false | [
"DEFAULT_MAX_AGE",
"_LegalChars",
"_UnescapedChars",
"_Translator",
"_is_legal_key"
] | import re
import string
from datetime import datetime
from typing import Dict
DEFAULT_MAX_AGE = 0
_LegalChars = string.ascii_letters + string.digits + "!#$%&'*+-.^_`|~:"
_UnescapedChars = _LegalChars + " ()/<=>?@[]{}"
_Translator = {
n: "\\%03o" % n for n in set(range(256)) - set(map(ord, _UnescapedChars))
}
_is_l... | true | 2 |
485 | sanic | sanic.cookies | Cookie | encode | def encode(self, encoding):
"""
Encode the cookie content in a specific type of encoding instructed
by the developer. Leverages the :func:`str.encode` method provided
by python.
This method can be used to encode and embed ``utf-8`` content into
the cookies.
... | [
121,
134
] | false | [
"DEFAULT_MAX_AGE",
"_LegalChars",
"_UnescapedChars",
"_Translator",
"_is_legal_key"
] | import re
import string
from datetime import datetime
from typing import Dict
DEFAULT_MAX_AGE = 0
_LegalChars = string.ascii_letters + string.digits + "!#$%&'*+-.^_`|~:"
_UnescapedChars = _LegalChars + " ()/<=>?@[]{}"
_Translator = {
n: "\\%03o" % n for n in set(range(256)) - set(map(ord, _UnescapedChars))
}
_is_l... | false | 0 |
486 | sanic | sanic.cookies | Cookie | __str__ | def __str__(self):
"""Format as a Set-Cookie header value."""
output = ["%s=%s" % (self.key, _quote(self.value))]
for key, value in self.items():
if key == "max-age":
try:
output.append("%s=%d" % (self._keys[key], value))
except... | [
136,
155
] | false | [
"DEFAULT_MAX_AGE",
"_LegalChars",
"_UnescapedChars",
"_Translator",
"_is_legal_key"
] | import re
import string
from datetime import datetime
from typing import Dict
DEFAULT_MAX_AGE = 0
_LegalChars = string.ascii_letters + string.digits + "!#$%&'*+-.^_`|~:"
_UnescapedChars = _LegalChars + " ()/<=>?@[]{}"
_Translator = {
n: "\\%03o" % n for n in set(range(256)) - set(map(ord, _UnescapedChars))
}
_is_l... | true | 2 |
487 | sanic | sanic.exceptions | add_status_code | def add_status_code(code, quiet=None):
"""
Decorator used for adding exceptions to :class:`SanicException`.
"""
def class_decorator(cls):
cls.status_code = code
if quiet or quiet is None and code != 500:
cls.quiet = True
_sanic_exceptions[code] = cls
return c... | [
8,
20
] | false | [
"_sanic_exceptions"
] | from typing import Optional, Union
from sanic.helpers import STATUS_CODES
_sanic_exceptions = {}
class SanicException(Exception):
def __init__(self, message, status_code=None, quiet=None):
super().__init__(message)
if status_code is not None:
self.status_code = status_code
#... | true | 2 | |
488 | sanic | sanic.exceptions | abort | def abort(status_code: int, message: Optional[Union[str, bytes]] = None):
"""
Raise an exception based on SanicException. Returns the HTTP response
message appropriate for the given status code, unless provided.
STATUS_CODES from sanic.helpers for the given status code.
:param status_code: The HTT... | [
233,
248
] | false | [
"_sanic_exceptions"
] | from typing import Optional, Union
from sanic.helpers import STATUS_CODES
_sanic_exceptions = {}
class SanicException(Exception):
def __init__(self, message, status_code=None, quiet=None):
super().__init__(message)
if status_code is not None:
self.status_code = status_code
#... | true | 2 | |
489 | sanic | sanic.headers | parse_content_header | def parse_content_header(value: str) -> Tuple[str, Options]:
"""Parse content-type and content-disposition header values.
E.g. 'form-data; name=upload; filename=\"file.txt\"' to
('form-data', {'name': 'upload', 'filename': 'file.txt'})
Mostly identical to cgi.parse_header and werkzeug.parse_options_he... | [
32,
51
] | false | [
"HeaderIterable",
"HeaderBytesIterable",
"Options",
"OptionsIterable",
"_token",
"_quoted",
"_param",
"_firefox_quote_escape",
"_ipv6",
"_ipv6_re",
"_host_re",
"_rparam",
"_HTTP1_STATUSLINES"
] | import re
from typing import Any, Dict, Iterable, List, Optional, Tuple, Union
from urllib.parse import unquote
from sanic.helpers import STATUS_CODES
HeaderIterable = Iterable[Tuple[str, Any]]
HeaderBytesIterable = Iterable[Tuple[bytes, bytes]]
Options = Dict[str, Union[int, str]]
OptionsIterable = Iterable[Tuple[str... | true | 2 | |
490 | sanic | sanic.headers | parse_forwarded | def parse_forwarded(headers, config) -> Optional[Options]:
"""Parse RFC 7239 Forwarded headers.
The value of `by` or `secret` must match `config.FORWARDED_SECRET`
:return: dict with keys and values, or None if nothing matched
"""
header = headers.getall("forwarded", None)
secret = config.FORWARD... | [
62,
97
] | false | [
"HeaderIterable",
"HeaderBytesIterable",
"Options",
"OptionsIterable",
"_token",
"_quoted",
"_param",
"_firefox_quote_escape",
"_ipv6",
"_ipv6_re",
"_host_re",
"_rparam",
"_HTTP1_STATUSLINES"
] | import re
from typing import Any, Dict, Iterable, List, Optional, Tuple, Union
from urllib.parse import unquote
from sanic.helpers import STATUS_CODES
HeaderIterable = Iterable[Tuple[str, Any]]
HeaderBytesIterable = Iterable[Tuple[bytes, bytes]]
Options = Dict[str, Union[int, str]]
OptionsIterable = Iterable[Tuple[str... | true | 2 | |
491 | sanic | sanic.headers | parse_xforwarded | def parse_xforwarded(headers, config) -> Optional[Options]:
"""Parse traditional proxy headers."""
real_ip_header = config.REAL_IP_HEADER
proxies_count = config.PROXIES_COUNT
addr = real_ip_header and headers.get(real_ip_header)
if not addr and proxies_count:
assert proxies_count > 0
... | [
100,
135
] | false | [
"HeaderIterable",
"HeaderBytesIterable",
"Options",
"OptionsIterable",
"_token",
"_quoted",
"_param",
"_firefox_quote_escape",
"_ipv6",
"_ipv6_re",
"_host_re",
"_rparam",
"_HTTP1_STATUSLINES"
] | import re
from typing import Any, Dict, Iterable, List, Optional, Tuple, Union
from urllib.parse import unquote
from sanic.helpers import STATUS_CODES
HeaderIterable = Iterable[Tuple[str, Any]]
HeaderBytesIterable = Iterable[Tuple[bytes, bytes]]
Options = Dict[str, Union[int, str]]
OptionsIterable = Iterable[Tuple[str... | true | 2 | |
492 | sanic | sanic.headers | fwd_normalize | def fwd_normalize(fwd: OptionsIterable) -> Options:
"""Normalize and convert values extracted from forwarded headers."""
ret: Dict[str, Union[int, str]] = {}
for key, val in fwd:
if val is not None:
try:
if key in ("by", "for"):
ret[key] = fwd_normaliz... | [
138,
156
] | false | [
"HeaderIterable",
"HeaderBytesIterable",
"Options",
"OptionsIterable",
"_token",
"_quoted",
"_param",
"_firefox_quote_escape",
"_ipv6",
"_ipv6_re",
"_host_re",
"_rparam",
"_HTTP1_STATUSLINES"
] | import re
from typing import Any, Dict, Iterable, List, Optional, Tuple, Union
from urllib.parse import unquote
from sanic.helpers import STATUS_CODES
HeaderIterable = Iterable[Tuple[str, Any]]
HeaderBytesIterable = Iterable[Tuple[bytes, bytes]]
Options = Dict[str, Union[int, str]]
OptionsIterable = Iterable[Tuple[str... | true | 2 | |
493 | sanic | sanic.headers | fwd_normalize_address | def fwd_normalize_address(addr: str) -> str:
"""Normalize address fields of proxy headers."""
if addr == "unknown":
raise ValueError() # omit unknown value identifiers
if addr.startswith("_"):
return addr # do not lower-case obfuscated strings
if _ipv6_re.fullmatch(addr):
addr ... | [
159,
167
] | false | [
"HeaderIterable",
"HeaderBytesIterable",
"Options",
"OptionsIterable",
"_token",
"_quoted",
"_param",
"_firefox_quote_escape",
"_ipv6",
"_ipv6_re",
"_host_re",
"_rparam",
"_HTTP1_STATUSLINES"
] | import re
from typing import Any, Dict, Iterable, List, Optional, Tuple, Union
from urllib.parse import unquote
from sanic.helpers import STATUS_CODES
HeaderIterable = Iterable[Tuple[str, Any]]
HeaderBytesIterable = Iterable[Tuple[bytes, bytes]]
Options = Dict[str, Union[int, str]]
OptionsIterable = Iterable[Tuple[str... | true | 2 | |
494 | sanic | sanic.headers | parse_host | def parse_host(host: str) -> Tuple[Optional[str], Optional[int]]:
"""Split host:port into hostname and port.
:return: None in place of missing elements
"""
m = _host_re.fullmatch(host)
if not m:
return None, None
host, port = m.groups()
return host.lower(), int(port) if port is not N... | [
170,
178
] | false | [
"HeaderIterable",
"HeaderBytesIterable",
"Options",
"OptionsIterable",
"_token",
"_quoted",
"_param",
"_firefox_quote_escape",
"_ipv6",
"_ipv6_re",
"_host_re",
"_rparam",
"_HTTP1_STATUSLINES"
] | import re
from typing import Any, Dict, Iterable, List, Optional, Tuple, Union
from urllib.parse import unquote
from sanic.helpers import STATUS_CODES
HeaderIterable = Iterable[Tuple[str, Any]]
HeaderBytesIterable = Iterable[Tuple[bytes, bytes]]
Options = Dict[str, Union[int, str]]
OptionsIterable = Iterable[Tuple[str... | true | 2 | |
495 | sanic | sanic.helpers | has_message_body | def has_message_body(status):
"""
According to the following RFC message body and length SHOULD NOT
be included in responses status 1XX, 204 and 304.
https://tools.ietf.org/html/rfc2616#section-4.4
https://tools.ietf.org/html/rfc2616#section-4.3
"""
return status not in (204, 304) and not (1... | [
102,
109
] | false | [
"STATUS_CODES",
"_ENTITY_HEADERS",
"_HOP_BY_HOP_HEADERS"
] | from importlib import import_module
from inspect import ismodule
from typing import Dict
STATUS_CODES: Dict[int, bytes] = {
100: b"Continue",
101: b"Switching Protocols",
102: b"Processing",
103: b"Early Hints",
200: b"OK",
201: b"Created",
202: b"Accepted",
203: b"Non-Authoritative Inf... | false | 0 | |
496 | sanic | sanic.helpers | remove_entity_headers | def remove_entity_headers(headers, allowed=("content-location", "expires")):
"""
Removes all the entity headers present in the headers given.
According to RFC 2616 Section 10.3.5,
Content-Location and Expires are allowed as for the
"strong cache validator".
https://tools.ietf.org/html/rfc2616#se... | [
122,
138
] | false | [
"STATUS_CODES",
"_ENTITY_HEADERS",
"_HOP_BY_HOP_HEADERS"
] | from importlib import import_module
from inspect import ismodule
from typing import Dict
STATUS_CODES: Dict[int, bytes] = {
100: b"Continue",
101: b"Switching Protocols",
102: b"Processing",
103: b"Early Hints",
200: b"OK",
201: b"Created",
202: b"Accepted",
203: b"Non-Authoritative Inf... | false | 0 | |
497 | sanic | sanic.helpers | import_string | def import_string(module_name, package=None):
"""
import a module or class by string path.
:module_name: str with path of module or path to import and
instanciate a class
:returns: a module object or one instance from class if
module_name is a valid path to class
"""
module, klass = mo... | [
141,
156
] | false | [
"STATUS_CODES",
"_ENTITY_HEADERS",
"_HOP_BY_HOP_HEADERS"
] | from importlib import import_module
from inspect import ismodule
from typing import Dict
STATUS_CODES: Dict[int, bytes] = {
100: b"Continue",
101: b"Switching Protocols",
102: b"Processing",
103: b"Early Hints",
200: b"OK",
201: b"Created",
202: b"Accepted",
203: b"Non-Authoritative Inf... | true | 2 | |
498 | sanic | sanic.mixins.exceptions | ExceptionMixin | exception | def exception(self, *exceptions, apply=True):
"""
This method enables the process of creating a global exception
handler for the current blueprint under question.
:param args: List of Python exceptions to be caught by the handler
:param kwargs: Additional optional arguments ... | [
12,
38
] | false | [] | from typing import Set
from sanic.models.futures import FutureException
class ExceptionMixin:
def __init__(self, *args, **kwargs) -> None:
self._future_exceptions: Set[FutureException] = set()
def exception(self, *exceptions, apply=True):
"""
This method enables the process of creat... | true | 2 |
499 | sanic | sanic.mixins.middleware | MiddlewareMixin | middleware | def middleware(
self, middleware_or_request, attach_to="request", apply=True
):
"""
Decorate and register middleware to be called before a request.
Can either be called as *@app.middleware* or
*@app.middleware('request')*
`See user guide re: middleware
<h... | [
13,
43
] | false | [] | from functools import partial
from typing import List
from sanic.models.futures import FutureMiddleware
class MiddlewareMixin:
def __init__(self, *args, **kwargs) -> None:
self._future_middleware: List[FutureMiddleware] = []
def middleware(
self, middleware_or_request, attach_to="request", ... | true | 2 |
500 | sanic | sanic.mixins.middleware | MiddlewareMixin | on_request | def on_request(self, middleware=None):
if callable(middleware):
return self.middleware(middleware, "request")
else:
return partial(self.middleware, attach_to="request") | [
47,
51
] | false | [] | from functools import partial
from typing import List
from sanic.models.futures import FutureMiddleware
class MiddlewareMixin:
def __init__(self, *args, **kwargs) -> None:
self._future_middleware: List[FutureMiddleware] = []
def on_request(self, middleware=None):
if callable(middleware):
... | true | 2 |
501 | sanic | sanic.mixins.middleware | MiddlewareMixin | on_response | def on_response(self, middleware=None):
if callable(middleware):
return self.middleware(middleware, "response")
else:
return partial(self.middleware, attach_to="response") | [
53,
57
] | false | [] | from functools import partial
from typing import List
from sanic.models.futures import FutureMiddleware
class MiddlewareMixin:
def __init__(self, *args, **kwargs) -> None:
self._future_middleware: List[FutureMiddleware] = []
def on_response(self, middleware=None):
if callable(middleware):
... | true | 2 |
502 | sanic | sanic.mixins.routes | RouteMixin | route | def route(
self,
uri: str,
methods: Optional[Iterable[str]] = None,
host: Optional[str] = None,
strict_slashes: Optional[bool] = None,
stream: bool = False,
version: Optional[int] = None,
name: Optional[str] = None,
ignore_body: bool = False,
... | [
40,
158
] | false | [] | from functools import partial, wraps
from inspect import signature
from mimetypes import guess_type
from os import path
from pathlib import PurePath
from re import sub
from time import gmtime, strftime
from typing import Iterable, List, Optional, Set, Union
from urllib.parse import unquote
from sanic_routing.route impo... | true | 2 |
503 | sanic | sanic.mixins.routes | RouteMixin | add_route | def add_route(
self,
handler,
uri: str,
methods: Iterable[str] = frozenset({"GET"}),
host: Optional[str] = None,
strict_slashes: Optional[bool] = None,
version: Optional[int] = None,
name: Optional[str] = None,
stream: bool = False,
):
... | [
160,
217
] | false | [] | from functools import partial, wraps
from inspect import signature
from mimetypes import guess_type
from os import path
from pathlib import PurePath
from re import sub
from time import gmtime, strftime
from typing import Iterable, List, Optional, Set, Union
from urllib.parse import unquote
from sanic_routing.route impo... | true | 2 |
504 | sanic | sanic.mixins.routes | RouteMixin | static | def static(
self,
uri,
file_or_directory: Union[str, bytes, PurePath],
pattern=r"/?.+",
use_modified_since=True,
use_content_range=False,
stream_large_files=False,
name="static",
host=None,
strict_slashes=None,
content_type=None... | [
526,
592
] | false | [] | from functools import partial, wraps
from inspect import signature
from mimetypes import guess_type
from os import path
from pathlib import PurePath
from re import sub
from time import gmtime, strftime
from typing import Iterable, List, Optional, Set, Union
from urllib.parse import unquote
from sanic_routing.route impo... | true | 2 |
505 | sanic | sanic.response | json | def json(
body: Any,
status: int = 200,
headers: Optional[Dict[str, str]] = None,
content_type: str = "application/json",
dumps: Optional[Callable[..., str]] = None,
**kwargs,
) -> HTTPResponse:
"""
Returns response object with body in json format.
:param body: Response data to be s... | [
250,
268
] | false | [
"StreamingFunction"
] | from functools import partial
from mimetypes import guess_type
from os import path
from pathlib import PurePath
from typing import (
Any,
AnyStr,
Callable,
Coroutine,
Dict,
Iterator,
Optional,
Tuple,
Union,
)
from urllib.parse import quote_plus
from warnings import warn
from sanic.co... | true | 2 | |
506 | sanic | sanic.response | text | def text(
body: str,
status: int = 200,
headers: Optional[Dict[str, str]] = None,
content_type: str = "text/plain; charset=utf-8",
) -> HTTPResponse:
"""
Returns response object with body in text format.
:param body: Response data to be encoded.
:param status: Response code.
:param ... | [
276,
295
] | false | [
"StreamingFunction"
] | from functools import partial
from mimetypes import guess_type
from os import path
from pathlib import PurePath
from typing import (
Any,
AnyStr,
Callable,
Coroutine,
Dict,
Iterator,
Optional,
Tuple,
Union,
)
from urllib.parse import quote_plus
from warnings import warn
from sanic.co... | true | 2 | |
507 | sanic | sanic.response | html | def html(
body: Union[str, bytes, HTMLProtocol],
status: int = 200,
headers: Optional[Dict[str, str]] = None,
) -> HTTPResponse:
"""
Returns response object with body in html format.
:param body: str or bytes-ish, or an object with __html__ or _repr_html_.
:param status: Response code.
... | [
322,
340
] | false | [
"StreamingFunction"
] | from functools import partial
from mimetypes import guess_type
from os import path
from pathlib import PurePath
from typing import (
Any,
AnyStr,
Callable,
Coroutine,
Dict,
Iterator,
Optional,
Tuple,
Union,
)
from urllib.parse import quote_plus
from warnings import warn
from sanic.co... | true | 2 | |
508 | sanic | sanic.response | file | async def file(
location: Union[str, PurePath],
status: int = 200,
mime_type: Optional[str] = None,
headers: Optional[Dict[str, str]] = None,
filename: Optional[str] = None,
_range: Optional[Range] = None,
) -> HTTPResponse:
"""Return a response object with file data.
:param location: L... | [
348,
383
] | false | [
"StreamingFunction"
] | from functools import partial
from mimetypes import guess_type
from os import path
from pathlib import PurePath
from typing import (
Any,
AnyStr,
Callable,
Coroutine,
Dict,
Iterator,
Optional,
Tuple,
Union,
)
from urllib.parse import quote_plus
from warnings import warn
from sanic.co... | true | 2 | |
509 | sanic | sanic.response | file_stream | async def file_stream(
location: Union[str, PurePath],
status: int = 200,
chunk_size: int = 4096,
mime_type: Optional[str] = None,
headers: Optional[Dict[str, str]] = None,
filename: Optional[str] = None,
chunked="deprecated",
_range: Optional[Range] = None,
) -> StreamingHTTPResponse:
... | [
391,
450
] | false | [
"StreamingFunction"
] | from functools import partial
from mimetypes import guess_type
from os import path
from pathlib import PurePath
from typing import (
Any,
AnyStr,
Callable,
Coroutine,
Dict,
Iterator,
Optional,
Tuple,
Union,
)
from urllib.parse import quote_plus
from warnings import warn
from sanic.co... | true | 2 | |
510 | sanic | sanic.response | stream | def stream(
streaming_fn: StreamingFunction,
status: int = 200,
headers: Optional[Dict[str, str]] = None,
content_type: str = "text/plain; charset=utf-8",
chunked="deprecated",
):
"""Accepts an coroutine `streaming_fn` which can be used to
write chunks to a streaming response. Returns a `Str... | [
458,
490
] | false | [
"StreamingFunction"
] | from functools import partial
from mimetypes import guess_type
from os import path
from pathlib import PurePath
from typing import (
Any,
AnyStr,
Callable,
Coroutine,
Dict,
Iterator,
Optional,
Tuple,
Union,
)
from urllib.parse import quote_plus
from warnings import warn
from sanic.co... | true | 2 | |
511 | sanic | sanic.response | BaseHTTPResponse | send | async def send(
self,
data: Optional[Union[AnyStr]] = None,
end_stream: Optional[bool] = None,
) -> None:
"""
Send any pending response headers and the given data as body.
:param data: str or bytes to be written
:param end_stream: whether to close the str... | [
101,
121
] | false | [
"StreamingFunction"
] | from functools import partial
from mimetypes import guess_type
from os import path
from pathlib import PurePath
from typing import (
Any,
AnyStr,
Callable,
Coroutine,
Dict,
Iterator,
Optional,
Tuple,
Union,
)
from urllib.parse import quote_plus
from warnings import warn
from sanic.co... | true | 2 |
512 | sanic | sanic.response | StreamingHTTPResponse | __init__ | def __init__(
self,
streaming_fn: StreamingFunction,
status: int = 200,
headers: Optional[Union[Header, Dict[str, str]]] = None,
content_type: str = "text/plain; charset=utf-8",
chunked="deprecated",
):
if chunked != "deprecated":
warn(
... | [
170,
190
] | false | [
"StreamingFunction"
] | from functools import partial
from mimetypes import guess_type
from os import path
from pathlib import PurePath
from typing import (
Any,
AnyStr,
Callable,
Coroutine,
Dict,
Iterator,
Optional,
Tuple,
Union,
)
from urllib.parse import quote_plus
from warnings import warn
from sanic.co... | true | 2 |
513 | sanic | sanic.response | StreamingHTTPResponse | write | async def write(self, data):
"""Writes a chunk of data to the streaming response.
:param data: str or bytes-ish data to be written.
"""
await super().send(self._encode_body(data)) | [
192,
197
] | false | [
"StreamingFunction"
] | from functools import partial
from mimetypes import guess_type
from os import path
from pathlib import PurePath
from typing import (
Any,
AnyStr,
Callable,
Coroutine,
Dict,
Iterator,
Optional,
Tuple,
Union,
)
from urllib.parse import quote_plus
from warnings import warn
from sanic.co... | false | 0 |
514 | sanic | sanic.response | StreamingHTTPResponse | send | async def send(self, *args, **kwargs):
if self.streaming_fn is not None:
await self.streaming_fn(self)
self.streaming_fn = None
await super().send(*args, **kwargs) | [
199,
203
] | false | [
"StreamingFunction"
] | from functools import partial
from mimetypes import guess_type
from os import path
from pathlib import PurePath
from typing import (
Any,
AnyStr,
Callable,
Coroutine,
Dict,
Iterator,
Optional,
Tuple,
Union,
)
from urllib.parse import quote_plus
from warnings import warn
from sanic.co... | true | 2 |
515 | sanic | sanic.router | Router | add | def add( # type: ignore
self,
uri: str,
methods: Iterable[str],
handler: RouteHandler,
host: Optional[Union[str, Iterable[str]]] = None,
strict_slashes: bool = False,
stream: bool = False,
ignore_body: bool = False,
version: Union[str, float, ... | [
62,
137
] | false | [
"ROUTER_CACHE_SIZE",
"ALLOWED_LABELS"
] | from functools import lru_cache
from typing import Any, Dict, Iterable, List, Optional, Tuple, Union
from sanic_routing import BaseRouter
from sanic_routing.exceptions import NoMethod
from sanic_routing.exceptions import (
NotFound as RoutingNotFound, # type: ignore
)
from sanic_routing.route import Route
from san... | true | 2 |
516 | sanic | sanic.router | Router | finalize | def finalize(self, *args, **kwargs):
super().finalize(*args, **kwargs)
for route in self.dynamic_routes.values():
if any(
label.startswith("__") and label not in ALLOWED_LABELS
for label in route.labels
):
raise SanicException(... | [
177,
185
] | false | [
"ROUTER_CACHE_SIZE",
"ALLOWED_LABELS"
] | from functools import lru_cache
from typing import Any, Dict, Iterable, List, Optional, Tuple, Union
from sanic_routing import BaseRouter
from sanic_routing.exceptions import NoMethod
from sanic_routing.exceptions import (
NotFound as RoutingNotFound, # type: ignore
)
from sanic_routing.route import Route
from san... | true | 2 |
517 | sanic | sanic.utils | str_to_bool | def str_to_bool(val: str) -> bool:
"""Takes string and tries to turn it into bool as human would do.
If val is in case insensitive (
"y", "yes", "yep", "yup", "t",
"true", "on", "enable", "enabled", "1"
) returns True.
If val is in case insensitive (
"n", "no", "f", "false", "of... | [
12,
41
] | false | [] | import types
from importlib.util import module_from_spec, spec_from_file_location
from os import environ as os_environ
from pathlib import Path
from re import findall as re_findall
from typing import Union
from sanic.exceptions import LoadFileException, PyFileError
from sanic.helpers import import_string
def str_to_... | true | 2 | |
518 | sanic | sanic.utils | load_module_from_file_location | def load_module_from_file_location(
location: Union[bytes, str, Path], encoding: str = "utf8", *args, **kwargs
): # noqa
"""Returns loaded module provided as a file path.
:param args:
Coresponds to importlib.util.spec_from_file_location location
parameters,but with this differences:
... | [
44,
130
] | false | [] | import types
from importlib.util import module_from_spec, spec_from_file_location
from os import environ as os_environ
from pathlib import Path
from re import findall as re_findall
from typing import Union
from sanic.exceptions import LoadFileException, PyFileError
from sanic.helpers import import_string
def load_mo... | false | 0 | |
519 | semantic_release | semantic_release.ci_checks | checker | def checker(func: Callable) -> Callable:
"""
A decorator that will convert AssertionErrors into
CiVerificationError.
:param func: A function that will raise AssertionError
:return: The given function wrapped to raise a CiVerificationError on AssertionError
"""
def func_wrapper(*args, **kwa... | [
8,
26
] | false | [] | import os
from typing import Callable
from semantic_release.errors import CiVerificationError
def checker(func: Callable) -> Callable:
"""
A decorator that will convert AssertionErrors into
CiVerificationError.
:param func: A function that will raise AssertionError
:return: The given function wr... | false | 0 | |
520 | semantic_release | semantic_release.ci_checks | check | def check(branch: str = "master"):
"""
Detects the current CI environment, if any, and performs necessary
environment checks.
:param branch: The branch that should be the current branch.
"""
if os.environ.get("TRAVIS") == "true":
travis(branch)
elif os.environ.get("SEMAPHORE") == "t... | [
117,
137
] | false | [] | import os
from typing import Callable
from semantic_release.errors import CiVerificationError
def check(branch: str = "master"):
"""
Detects the current CI environment, if any, and performs necessary
environment checks.
:param branch: The branch that should be the current branch.
"""
if os.e... | true | 2 | |
521 | semantic_release | semantic_release.dist | should_build | def should_build():
upload_pypi = config.get("upload_to_pypi")
upload_release = config.get("upload_to_release")
build_command = config.get("build_command")
build_command = build_command if build_command != "false" else False
return bool(build_command and (upload_pypi or upload_release)) | [
11,
16
] | false | [
"logger"
] | import logging
from invoke import run
from .settings import config
logger = logging.getLogger(__name__)
def should_build():
upload_pypi = config.get("upload_to_pypi")
upload_release = config.get("upload_to_release")
build_command = config.get("build_command")
build_command = build_command if build_com... | false | 0 | |
522 | semantic_release | semantic_release.dist | should_remove_dist | def should_remove_dist():
remove_dist = config.get("remove_dist")
return bool(remove_dist and should_build()) | [
19,
21
] | false | [
"logger"
] | import logging
from invoke import run
from .settings import config
logger = logging.getLogger(__name__)
def should_remove_dist():
remove_dist = config.get("remove_dist")
return bool(remove_dist and should_build()) | false | 0 | |
523 | semantic_release | semantic_release.helpers | build_requests_session | def build_requests_session(
raise_for_status=True, retry: Union[bool, int, Retry] = True
) -> Session:
"""
Create a requests session.
:param raise_for_status: If True, a hook to invoke raise_for_status be installed
:param retry: If true, it will use default Retry configuration. if an integer, it wil... | [
15,
38
] | false | [] | import functools
from typing import Union
from requests import Session
from requests.adapters import HTTPAdapter
from requests.packages.urllib3.util.retry import Retry
def build_requests_session(
raise_for_status=True, retry: Union[bool, int, Retry] = True
) -> Session:
"""
Create a requests session.
... | true | 2 | |
524 | semantic_release | semantic_release.helpers | LoggedFunction | __call__ | def __call__(self, func):
@functools.wraps(func)
def logged_func(*args, **kwargs):
# Log function name and arguments
self.logger.debug(
"{function}({args}{kwargs})".format(
function=func.__name__,
args=", ".join([format_... | [
54,
76
] | false | [] | import functools
from typing import Union
from requests import Session
from requests.adapters import HTTPAdapter
from requests.packages.urllib3.util.retry import Retry
class LoggedFunction:
def __init__(self, logger):
self.logger = logger
def __call__(self, func):
@functools.wraps(func)
... | true | 2 |
525 | semantic_release | semantic_release.hvcs | TokenAuth | __call__ | def __call__(self, r):
r.headers["Authorization"] = f"token {self.token}"
return r | [
84,
86
] | false | [
"logger"
] | import logging
import mimetypes
import os
from typing import Optional, Union
import gitlab
from requests import HTTPError, Session
from requests.auth import AuthBase
from urllib3 import Retry
from .errors import ImproperConfigurationError
from .helpers import LoggedFunction, build_requests_session
from .settings import... | false | 0 |
526 | semantic_release | semantic_release.hvcs | Github | domain | @staticmethod
def domain() -> str:
"""Github domain property
:return: The Github domain
"""
hvcs_domain = config.get("hvcs_domain")
domain = hvcs_domain if hvcs_domain else Github.DEFAULT_DOMAIN
return domain | [
96,
103
] | false | [
"logger"
] | import logging
import mimetypes
import os
from typing import Optional, Union
import gitlab
from requests import HTTPError, Session
from requests.auth import AuthBase
from urllib3 import Retry
from .errors import ImproperConfigurationError
from .helpers import LoggedFunction, build_requests_session
from .settings import... | false | 0 |
527 | semantic_release | semantic_release.hvcs | Github | api_url | @staticmethod
def api_url() -> str:
"""Github api_url property
:return: The Github API URL
"""
# not necessarily prefixed with api in the case of a custom domain, so
# can't just default DEFAULT_DOMAIN to github.com
hvcs_domain = config.get("hvcs_domain")
... | [
106,
115
] | false | [
"logger"
] | import logging
import mimetypes
import os
from typing import Optional, Union
import gitlab
from requests import HTTPError, Session
from requests.auth import AuthBase
from urllib3 import Retry
from .errors import ImproperConfigurationError
from .helpers import LoggedFunction, build_requests_session
from .settings import... | false | 0 |
528 | semantic_release | semantic_release.hvcs | Github | auth | @staticmethod
def auth() -> Optional[TokenAuth]:
"""Github token property
:return: The Github token environment variable (GH_TOKEN) value
"""
token = Github.token()
if not token:
return None
return TokenAuth(token) | [
126,
134
] | false | [
"logger"
] | import logging
import mimetypes
import os
from typing import Optional, Union
import gitlab
from requests import HTTPError, Session
from requests.auth import AuthBase
from urllib3 import Retry
from .errors import ImproperConfigurationError
from .helpers import LoggedFunction, build_requests_session
from .settings import... | true | 2 |
529 | semantic_release | semantic_release.hvcs | Github | check_build_status | @staticmethod
@LoggedFunction(logger)
def check_build_status(owner: str, repo: str, ref: str) -> bool:
"""Check build status
https://docs.github.com/rest/reference/repos#get-the-combined-status-for-a-specific-reference
:param owner: The owner namespace of the repository
:pa... | [
146,
165
] | false | [
"logger"
] | import logging
import mimetypes
import os
from typing import Optional, Union
import gitlab
from requests import HTTPError, Session
from requests.auth import AuthBase
from urllib3 import Retry
from .errors import ImproperConfigurationError
from .helpers import LoggedFunction, build_requests_session
from .settings import... | false | 0 |
530 | semantic_release | semantic_release.hvcs | Gitlab | domain | @staticmethod
def domain() -> str:
"""Gitlab domain property
:return: The Gitlab instance domain
"""
domain = config.get("hvcs_domain", os.environ.get("CI_SERVER_HOST"))
return domain if domain else "gitlab.com" | [
348,
354
] | false | [
"logger"
] | import logging
import mimetypes
import os
from typing import Optional, Union
import gitlab
from requests import HTTPError, Session
from requests.auth import AuthBase
from urllib3 import Retry
from .errors import ImproperConfigurationError
from .helpers import LoggedFunction, build_requests_session
from .settings import... | false | 0 |
531 | semantic_release | semantic_release.hvcs | Gitlab | check_build_status | @staticmethod
@LoggedFunction(logger)
def check_build_status(owner: str, repo: str, ref: str) -> bool:
"""Check last build status
:param owner: The owner namespace of the repository. It includes all groups and subgroups.
:param repo: The repository name
:param ref: The sha1 ... | [
374,
396
] | false | [
"logger"
] | import logging
import mimetypes
import os
from typing import Optional, Union
import gitlab
from requests import HTTPError, Session
from requests.auth import AuthBase
from urllib3 import Retry
from .errors import ImproperConfigurationError
from .helpers import LoggedFunction, build_requests_session
from .settings import... | true | 2 |
532 | semantic_release | semantic_release.settings | current_commit_parser | def current_commit_parser() -> Callable:
"""Get the currently-configured commit parser
:raises ImproperConfigurationError: if ImportError or AttributeError is raised
:returns: Commit parser
"""
try:
# All except the last part is the import path
parts = config.get("commit_parser").s... | [
79,
93
] | false | [
"logger",
"config"
] | import configparser
import importlib
import logging
import os
from collections import UserDict
from functools import wraps
from os import getcwd
from typing import Callable, List
import tomlkit
from tomlkit.exceptions import TOMLKitError
from .errors import ImproperConfigurationError
logger = logging.getLogger(__name_... | false | 0 | |
533 | semantic_release | semantic_release.settings | current_changelog_components | def current_changelog_components() -> List[Callable]:
"""Get the currently-configured changelog components
:raises ImproperConfigurationError: if ImportError or AttributeError is raised
:returns: List of component functions
"""
component_paths = config.get("changelog_components").split(",")
com... | [
96,
117
] | false | [
"logger",
"config"
] | import configparser
import importlib
import logging
import os
from collections import UserDict
from functools import wraps
from os import getcwd
from typing import Callable, List
import tomlkit
from tomlkit.exceptions import TOMLKitError
from .errors import ImproperConfigurationError
logger = logging.getLogger(__name_... | true | 2 | |
534 | semantic_release | semantic_release.settings | overload_configuration | def overload_configuration(func):
"""This decorator gets the content of the "define" array and edits "config"
according to the pairs of key/value.
"""
@wraps(func)
def wrap(*args, **kwargs):
if "define" in kwargs:
for defined_param in kwargs["define"]:
pair = def... | [
120,
134
] | false | [
"logger",
"config"
] | import configparser
import importlib
import logging
import os
from collections import UserDict
from functools import wraps
from os import getcwd
from typing import Callable, List
import tomlkit
from tomlkit.exceptions import TOMLKitError
from .errors import ImproperConfigurationError
logger = logging.getLogger(__name_... | true | 2 | |
535 | string_utils | string_utils.generation | roman_range | def roman_range(stop: int, start: int = 1, step: int = 1) -> Generator:
"""
Similarly to native Python's `range()`, returns a Generator object which generates a new roman number
on each iteration instead of an integer.
*Example:*
>>> for n in roman_range(7): print(n)
>>> # prints: I, II, III, ... | [
87,
139
] | false | [
"__all__"
] | import binascii
import os
import random
import string
from typing import Generator
from uuid import uuid4
from .manipulation import roman_encode
__all__ = [
'uuid',
'random_string',
'secure_random_hex',
'roman_range',
]
def roman_range(stop: int, start: int = 1, step: int = 1) -> Generator:
"""
... | true | 2 | |
536 | string_utils | string_utils.manipulation | reverse | def reverse(input_string: str) -> str:
"""
Returns the string with its chars reversed.
*Example:*
>>> reverse('hello') # returns 'olleh'
:param input_string: String to revert.
:type input_string: str
:return: Reversed string.
"""
if not is_string(input_string):
raise Inval... | [
281,
296
] | false | [
"__all__"
] | import base64
import random
import unicodedata
import zlib
from typing import Union
from uuid import uuid4
from ._regex import *
from .errors import InvalidInputError
from .validation import is_snake_case, is_full_string, is_camel_case, is_integer, is_string
__all__ = [
'camel_case_to_snake',
'snake_case_to_ca... | true | 2 | |
537 | string_utils | string_utils.manipulation | camel_case_to_snake | def camel_case_to_snake(input_string, separator='_'):
"""
Convert a camel case string into a snake case one.
(The original string is returned if is not a valid camel case string)
*Example:*
>>> camel_case_to_snake('ThisIsACamelStringTest') # returns 'this_is_a_camel_case_string_test'
:param i... | [
299,
320
] | false | [
"__all__"
] | import base64
import random
import unicodedata
import zlib
from typing import Union
from uuid import uuid4
from ._regex import *
from .errors import InvalidInputError
from .validation import is_snake_case, is_full_string, is_camel_case, is_integer, is_string
__all__ = [
'camel_case_to_snake',
'snake_case_to_ca... | true | 2 | |
538 | string_utils | string_utils.manipulation | snake_case_to_camel | def snake_case_to_camel(input_string: str, upper_case_first: bool = True, separator: str = '_') -> str:
"""
Convert a snake case string into a camel case one.
(The original string is returned if is not a valid snake case string)
*Example:*
>>> snake_case_to_camel('the_snake_is_green') # returns 'T... | [
323,
353
] | false | [
"__all__"
] | import base64
import random
import unicodedata
import zlib
from typing import Union
from uuid import uuid4
from ._regex import *
from .errors import InvalidInputError
from .validation import is_snake_case, is_full_string, is_camel_case, is_integer, is_string
__all__ = [
'camel_case_to_snake',
'snake_case_to_ca... | true | 2 | |
539 | string_utils | string_utils.manipulation | shuffle | def shuffle(input_string: str) -> str:
"""
Return a new string containing same chars of the given one but in a randomized order.
*Example:*
>>> shuffle('hello world') # possible output: 'l wodheorll'
:param input_string: String to shuffle
:type input_string: str
:return: Shuffled string
... | [
356,
378
] | false | [
"__all__"
] | import base64
import random
import unicodedata
import zlib
from typing import Union
from uuid import uuid4
from ._regex import *
from .errors import InvalidInputError
from .validation import is_snake_case, is_full_string, is_camel_case, is_integer, is_string
__all__ = [
'camel_case_to_snake',
'snake_case_to_ca... | true | 2 | |
540 | string_utils | string_utils.manipulation | strip_html | def strip_html(input_string: str, keep_tag_content: bool = False) -> str:
"""
Remove html code contained into the given string.
*Examples:*
>>> strip_html('test: <a href="foo/bar">click here</a>') # returns 'test: '
>>> strip_html('test: <a href="foo/bar">click here</a>', keep_tag_content=True) # ... | [
381,
401
] | false | [
"__all__"
] | import base64
import random
import unicodedata
import zlib
from typing import Union
from uuid import uuid4
from ._regex import *
from .errors import InvalidInputError
from .validation import is_snake_case, is_full_string, is_camel_case, is_integer, is_string
__all__ = [
'camel_case_to_snake',
'snake_case_to_ca... | true | 2 | |
541 | string_utils | string_utils.manipulation | prettify | def prettify(input_string: str) -> str:
"""
Reformat a string by applying the following basic grammar and formatting rules:
- String cannot start or end with spaces
- The first letter in the string and the ones after a dot, an exclamation or a question mark must be uppercase
- String cannot have mu... | [
404,
429
] | false | [
"__all__"
] | import base64
import random
import unicodedata
import zlib
from typing import Union
from uuid import uuid4
from ._regex import *
from .errors import InvalidInputError
from .validation import is_snake_case, is_full_string, is_camel_case, is_integer, is_string
__all__ = [
'camel_case_to_snake',
'snake_case_to_ca... | false | 0 | |
542 | string_utils | string_utils.manipulation | asciify | def asciify(input_string: str) -> str:
"""
Force string content to be ascii-only by translating all non-ascii chars into the closest possible representation
(eg: ó -> o, Ë -> E, ç -> c...).
**Bear in mind**: Some chars may be lost if impossible to translate.
*Example:*
>>> asciify('èéùúòóäåëý... | [
432,
458
] | false | [
"__all__"
] | import base64
import random
import unicodedata
import zlib
from typing import Union
from uuid import uuid4
from ._regex import *
from .errors import InvalidInputError
from .validation import is_snake_case, is_full_string, is_camel_case, is_integer, is_string
__all__ = [
'camel_case_to_snake',
'snake_case_to_ca... | true | 2 | |
543 | string_utils | string_utils.manipulation | slugify | def slugify(input_string: str, separator: str = '-') -> str:
"""
Converts a string into a "slug" using provided separator.
The returned string has the following properties:
- it has no spaces
- all letters are in lower case
- all punctuation signs and non alphanumeric chars are removed
- wo... | [
461,
496
] | false | [
"__all__"
] | import base64
import random
import unicodedata
import zlib
from typing import Union
from uuid import uuid4
from ._regex import *
from .errors import InvalidInputError
from .validation import is_snake_case, is_full_string, is_camel_case, is_integer, is_string
__all__ = [
'camel_case_to_snake',
'snake_case_to_ca... | true | 2 | |
544 | string_utils | string_utils.manipulation | booleanize | def booleanize(input_string: str) -> bool:
"""
Turns a string into a boolean based on its content (CASE INSENSITIVE).
A positive boolean (True) is returned if the string value is one of the following:
- "true"
- "1"
- "yes"
- "y"
Otherwise False is returned.
*Examples:*
>>> ... | [
499,
525
] | false | [
"__all__"
] | import base64
import random
import unicodedata
import zlib
from typing import Union
from uuid import uuid4
from ._regex import *
from .errors import InvalidInputError
from .validation import is_snake_case, is_full_string, is_camel_case, is_integer, is_string
__all__ = [
'camel_case_to_snake',
'snake_case_to_ca... | true | 2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.