Search is not available for this dataset
identifier
stringlengths 1
155
| parameters
stringlengths 2
6.09k
| docstring
stringlengths 11
63.4k
| docstring_summary
stringlengths 0
63.4k
| function
stringlengths 29
99.8k
| function_tokens
sequence | start_point
sequence | end_point
sequence | language
stringclasses 1
value | docstring_language
stringlengths 2
7
| docstring_language_predictions
stringlengths 18
23
| is_langid_reliable
stringclasses 2
values |
---|---|---|---|---|---|---|---|---|---|---|---|
DjangoORMStorage.__init__ | (self, model_class, key_name, key_value, property_name) | Constructor for Storage.
Args:
model: string, fully qualified name of db.Model model class.
key_name: string, key name for the entity that has the credentials
key_value: string, key value for the entity that has the
credentials.
property_name: string, name of the property that is an
CredentialsProperty.
| Constructor for Storage. | def __init__(self, model_class, key_name, key_value, property_name):
"""Constructor for Storage.
Args:
model: string, fully qualified name of db.Model model class.
key_name: string, key name for the entity that has the credentials
key_value: string, key value for the entity that has the
credentials.
property_name: string, name of the property that is an
CredentialsProperty.
"""
super(DjangoORMStorage, self).__init__()
self.model_class = model_class
self.key_name = key_name
self.key_value = key_value
self.property_name = property_name | [
"def",
"__init__",
"(",
"self",
",",
"model_class",
",",
"key_name",
",",
"key_value",
",",
"property_name",
")",
":",
"super",
"(",
"DjangoORMStorage",
",",
"self",
")",
".",
"__init__",
"(",
")",
"self",
".",
"model_class",
"=",
"model_class",
"self",
".",
"key_name",
"=",
"key_name",
"self",
".",
"key_value",
"=",
"key_value",
"self",
".",
"property_name",
"=",
"property_name"
] | [
27,
4
] | [
42,
42
] | python | en | ['da', 'en', 'en'] | True |
DjangoORMStorage.locked_get | (self) | Retrieve stored credential from the Django ORM.
Returns:
oauth2client.Credentials retrieved from the Django ORM, associated
with the ``model``, ``key_value``->``key_name`` pair used to query
for the model, and ``property_name`` identifying the
``CredentialsProperty`` field, all of which are defined in the
constructor for this Storage object.
| Retrieve stored credential from the Django ORM. | def locked_get(self):
"""Retrieve stored credential from the Django ORM.
Returns:
oauth2client.Credentials retrieved from the Django ORM, associated
with the ``model``, ``key_value``->``key_name`` pair used to query
for the model, and ``property_name`` identifying the
``CredentialsProperty`` field, all of which are defined in the
constructor for this Storage object.
"""
query = {self.key_name: self.key_value}
entities = self.model_class.objects.filter(**query)
if len(entities) > 0:
credential = getattr(entities[0], self.property_name)
if getattr(credential, 'set_store', None) is not None:
credential.set_store(self)
return credential
else:
return None | [
"def",
"locked_get",
"(",
"self",
")",
":",
"query",
"=",
"{",
"self",
".",
"key_name",
":",
"self",
".",
"key_value",
"}",
"entities",
"=",
"self",
".",
"model_class",
".",
"objects",
".",
"filter",
"(",
"*",
"*",
"query",
")",
"if",
"len",
"(",
"entities",
")",
">",
"0",
":",
"credential",
"=",
"getattr",
"(",
"entities",
"[",
"0",
"]",
",",
"self",
".",
"property_name",
")",
"if",
"getattr",
"(",
"credential",
",",
"'set_store'",
",",
"None",
")",
"is",
"not",
"None",
":",
"credential",
".",
"set_store",
"(",
"self",
")",
"return",
"credential",
"else",
":",
"return",
"None"
] | [
44,
4
] | [
63,
23
] | python | en | ['en', 'en', 'en'] | True |
DjangoORMStorage.locked_put | (self, credentials) | Write a Credentials to the Django datastore.
Args:
credentials: Credentials, the credentials to store.
| Write a Credentials to the Django datastore. | def locked_put(self, credentials):
"""Write a Credentials to the Django datastore.
Args:
credentials: Credentials, the credentials to store.
"""
entity, _ = self.model_class.objects.get_or_create(
**{self.key_name: self.key_value})
setattr(entity, self.property_name, credentials)
entity.save() | [
"def",
"locked_put",
"(",
"self",
",",
"credentials",
")",
":",
"entity",
",",
"_",
"=",
"self",
".",
"model_class",
".",
"objects",
".",
"get_or_create",
"(",
"*",
"*",
"{",
"self",
".",
"key_name",
":",
"self",
".",
"key_value",
"}",
")",
"setattr",
"(",
"entity",
",",
"self",
".",
"property_name",
",",
"credentials",
")",
"entity",
".",
"save",
"(",
")"
] | [
65,
4
] | [
75,
21
] | python | en | ['en', 'pt', 'en'] | True |
DjangoORMStorage.locked_delete | (self) | Delete Credentials from the datastore. | Delete Credentials from the datastore. | def locked_delete(self):
"""Delete Credentials from the datastore."""
query = {self.key_name: self.key_value}
self.model_class.objects.filter(**query).delete() | [
"def",
"locked_delete",
"(",
"self",
")",
":",
"query",
"=",
"{",
"self",
".",
"key_name",
":",
"self",
".",
"key_value",
"}",
"self",
".",
"model_class",
".",
"objects",
".",
"filter",
"(",
"*",
"*",
"query",
")",
".",
"delete",
"(",
")"
] | [
77,
4
] | [
80,
57
] | python | en | ['en', 'en', 'en'] | True |
project_id | () | Retreives the project id from the environment variable.
Raises:
MissingProjectIdError -- When not set.
Returns:
str -- the project name
| Retreives the project id from the environment variable. | def project_id():
"""Retreives the project id from the environment variable.
Raises:
MissingProjectIdError -- When not set.
Returns:
str -- the project name
"""
project_id = (os.environ['GOOGLE_CLOUD_PROJECT'] or
os.environ['GCLOUD_PROJECT'])
if not project_id:
raise MissingProjectIdError(
'Set the environment variable ' +
'GCLOUD_PROJECT to your Google Cloud Project Id.')
return project_id | [
"def",
"project_id",
"(",
")",
":",
"project_id",
"=",
"(",
"os",
".",
"environ",
"[",
"'GOOGLE_CLOUD_PROJECT'",
"]",
"or",
"os",
".",
"environ",
"[",
"'GCLOUD_PROJECT'",
"]",
")",
"if",
"not",
"project_id",
":",
"raise",
"MissingProjectIdError",
"(",
"'Set the environment variable '",
"+",
"'GCLOUD_PROJECT to your Google Cloud Project Id.'",
")",
"return",
"project_id"
] | [
56,
0
] | [
72,
21
] | python | en | ['en', 'en', 'en'] | True |
extract_cookies_to_jar | (jar, request, response) | Extract the cookies from the response into a CookieJar.
:param jar: cookielib.CookieJar (not necessarily a RequestsCookieJar)
:param request: our own requests.Request object
:param response: urllib3.HTTPResponse object
| Extract the cookies from the response into a CookieJar. | def extract_cookies_to_jar(jar, request, response):
"""Extract the cookies from the response into a CookieJar.
:param jar: cookielib.CookieJar (not necessarily a RequestsCookieJar)
:param request: our own requests.Request object
:param response: urllib3.HTTPResponse object
"""
if not (hasattr(response, '_original_response') and
response._original_response):
return
# the _original_response field is the wrapped httplib.HTTPResponse object,
req = MockRequest(request)
# pull out the HTTPMessage with the headers and put it in the mock:
res = MockResponse(response._original_response.msg)
jar.extract_cookies(res, req) | [
"def",
"extract_cookies_to_jar",
"(",
"jar",
",",
"request",
",",
"response",
")",
":",
"if",
"not",
"(",
"hasattr",
"(",
"response",
",",
"'_original_response'",
")",
"and",
"response",
".",
"_original_response",
")",
":",
"return",
"# the _original_response field is the wrapped httplib.HTTPResponse object,",
"req",
"=",
"MockRequest",
"(",
"request",
")",
"# pull out the HTTPMessage with the headers and put it in the mock:",
"res",
"=",
"MockResponse",
"(",
"response",
".",
"_original_response",
".",
"msg",
")",
"jar",
".",
"extract_cookies",
"(",
"res",
",",
"req",
")"
] | [
117,
0
] | [
131,
33
] | python | en | ['en', 'en', 'en'] | True |
get_cookie_header | (jar, request) |
Produce an appropriate Cookie header string to be sent with `request`, or None.
:rtype: str
|
Produce an appropriate Cookie header string to be sent with `request`, or None. | def get_cookie_header(jar, request):
"""
Produce an appropriate Cookie header string to be sent with `request`, or None.
:rtype: str
"""
r = MockRequest(request)
jar.add_cookie_header(r)
return r.get_new_headers().get('Cookie') | [
"def",
"get_cookie_header",
"(",
"jar",
",",
"request",
")",
":",
"r",
"=",
"MockRequest",
"(",
"request",
")",
"jar",
".",
"add_cookie_header",
"(",
"r",
")",
"return",
"r",
".",
"get_new_headers",
"(",
")",
".",
"get",
"(",
"'Cookie'",
")"
] | [
134,
0
] | [
142,
44
] | python | en | ['en', 'error', 'th'] | False |
remove_cookie_by_name | (cookiejar, name, domain=None, path=None) | Unsets a cookie by name, by default over all domains and paths.
Wraps CookieJar.clear(), is O(n).
| Unsets a cookie by name, by default over all domains and paths. | def remove_cookie_by_name(cookiejar, name, domain=None, path=None):
"""Unsets a cookie by name, by default over all domains and paths.
Wraps CookieJar.clear(), is O(n).
"""
clearables = []
for cookie in cookiejar:
if cookie.name != name:
continue
if domain is not None and domain != cookie.domain:
continue
if path is not None and path != cookie.path:
continue
clearables.append((cookie.domain, cookie.path, cookie.name))
for domain, path, name in clearables:
cookiejar.clear(domain, path, name) | [
"def",
"remove_cookie_by_name",
"(",
"cookiejar",
",",
"name",
",",
"domain",
"=",
"None",
",",
"path",
"=",
"None",
")",
":",
"clearables",
"=",
"[",
"]",
"for",
"cookie",
"in",
"cookiejar",
":",
"if",
"cookie",
".",
"name",
"!=",
"name",
":",
"continue",
"if",
"domain",
"is",
"not",
"None",
"and",
"domain",
"!=",
"cookie",
".",
"domain",
":",
"continue",
"if",
"path",
"is",
"not",
"None",
"and",
"path",
"!=",
"cookie",
".",
"path",
":",
"continue",
"clearables",
".",
"append",
"(",
"(",
"cookie",
".",
"domain",
",",
"cookie",
".",
"path",
",",
"cookie",
".",
"name",
")",
")",
"for",
"domain",
",",
"path",
",",
"name",
"in",
"clearables",
":",
"cookiejar",
".",
"clear",
"(",
"domain",
",",
"path",
",",
"name",
")"
] | [
145,
0
] | [
161,
43
] | python | en | ['en', 'en', 'en'] | True |
create_cookie | (name, value, **kwargs) | Make a cookie from underspecified parameters.
By default, the pair of `name` and `value` will be set for the domain ''
and sent on every request (this is sometimes called a "supercookie").
| Make a cookie from underspecified parameters. | def create_cookie(name, value, **kwargs):
"""Make a cookie from underspecified parameters.
By default, the pair of `name` and `value` will be set for the domain ''
and sent on every request (this is sometimes called a "supercookie").
"""
result = {
'version': 0,
'name': name,
'value': value,
'port': None,
'domain': '',
'path': '/',
'secure': False,
'expires': None,
'discard': True,
'comment': None,
'comment_url': None,
'rest': {'HttpOnly': None},
'rfc2109': False,
}
badargs = set(kwargs) - set(result)
if badargs:
err = 'create_cookie() got unexpected keyword arguments: %s'
raise TypeError(err % list(badargs))
result.update(kwargs)
result['port_specified'] = bool(result['port'])
result['domain_specified'] = bool(result['domain'])
result['domain_initial_dot'] = result['domain'].startswith('.')
result['path_specified'] = bool(result['path'])
return cookielib.Cookie(**result) | [
"def",
"create_cookie",
"(",
"name",
",",
"value",
",",
"*",
"*",
"kwargs",
")",
":",
"result",
"=",
"{",
"'version'",
":",
"0",
",",
"'name'",
":",
"name",
",",
"'value'",
":",
"value",
",",
"'port'",
":",
"None",
",",
"'domain'",
":",
"''",
",",
"'path'",
":",
"'/'",
",",
"'secure'",
":",
"False",
",",
"'expires'",
":",
"None",
",",
"'discard'",
":",
"True",
",",
"'comment'",
":",
"None",
",",
"'comment_url'",
":",
"None",
",",
"'rest'",
":",
"{",
"'HttpOnly'",
":",
"None",
"}",
",",
"'rfc2109'",
":",
"False",
",",
"}",
"badargs",
"=",
"set",
"(",
"kwargs",
")",
"-",
"set",
"(",
"result",
")",
"if",
"badargs",
":",
"err",
"=",
"'create_cookie() got unexpected keyword arguments: %s'",
"raise",
"TypeError",
"(",
"err",
"%",
"list",
"(",
"badargs",
")",
")",
"result",
".",
"update",
"(",
"kwargs",
")",
"result",
"[",
"'port_specified'",
"]",
"=",
"bool",
"(",
"result",
"[",
"'port'",
"]",
")",
"result",
"[",
"'domain_specified'",
"]",
"=",
"bool",
"(",
"result",
"[",
"'domain'",
"]",
")",
"result",
"[",
"'domain_initial_dot'",
"]",
"=",
"result",
"[",
"'domain'",
"]",
".",
"startswith",
"(",
"'.'",
")",
"result",
"[",
"'path_specified'",
"]",
"=",
"bool",
"(",
"result",
"[",
"'path'",
"]",
")",
"return",
"cookielib",
".",
"Cookie",
"(",
"*",
"*",
"result",
")"
] | [
440,
0
] | [
473,
37
] | python | en | ['en', 'en', 'en'] | True |
morsel_to_cookie | (morsel) | Convert a Morsel object into a Cookie containing the one k/v pair. | Convert a Morsel object into a Cookie containing the one k/v pair. | def morsel_to_cookie(morsel):
"""Convert a Morsel object into a Cookie containing the one k/v pair."""
expires = None
if morsel['max-age']:
try:
expires = int(time.time() + int(morsel['max-age']))
except ValueError:
raise TypeError('max-age: %s must be integer' % morsel['max-age'])
elif morsel['expires']:
time_template = '%a, %d-%b-%Y %H:%M:%S GMT'
expires = calendar.timegm(
time.strptime(morsel['expires'], time_template)
)
return create_cookie(
comment=morsel['comment'],
comment_url=bool(morsel['comment']),
discard=False,
domain=morsel['domain'],
expires=expires,
name=morsel.key,
path=morsel['path'],
port=None,
rest={'HttpOnly': morsel['httponly']},
rfc2109=False,
secure=bool(morsel['secure']),
value=morsel.value,
version=morsel['version'] or 0,
) | [
"def",
"morsel_to_cookie",
"(",
"morsel",
")",
":",
"expires",
"=",
"None",
"if",
"morsel",
"[",
"'max-age'",
"]",
":",
"try",
":",
"expires",
"=",
"int",
"(",
"time",
".",
"time",
"(",
")",
"+",
"int",
"(",
"morsel",
"[",
"'max-age'",
"]",
")",
")",
"except",
"ValueError",
":",
"raise",
"TypeError",
"(",
"'max-age: %s must be integer'",
"%",
"morsel",
"[",
"'max-age'",
"]",
")",
"elif",
"morsel",
"[",
"'expires'",
"]",
":",
"time_template",
"=",
"'%a, %d-%b-%Y %H:%M:%S GMT'",
"expires",
"=",
"calendar",
".",
"timegm",
"(",
"time",
".",
"strptime",
"(",
"morsel",
"[",
"'expires'",
"]",
",",
"time_template",
")",
")",
"return",
"create_cookie",
"(",
"comment",
"=",
"morsel",
"[",
"'comment'",
"]",
",",
"comment_url",
"=",
"bool",
"(",
"morsel",
"[",
"'comment'",
"]",
")",
",",
"discard",
"=",
"False",
",",
"domain",
"=",
"morsel",
"[",
"'domain'",
"]",
",",
"expires",
"=",
"expires",
",",
"name",
"=",
"morsel",
".",
"key",
",",
"path",
"=",
"morsel",
"[",
"'path'",
"]",
",",
"port",
"=",
"None",
",",
"rest",
"=",
"{",
"'HttpOnly'",
":",
"morsel",
"[",
"'httponly'",
"]",
"}",
",",
"rfc2109",
"=",
"False",
",",
"secure",
"=",
"bool",
"(",
"morsel",
"[",
"'secure'",
"]",
")",
",",
"value",
"=",
"morsel",
".",
"value",
",",
"version",
"=",
"morsel",
"[",
"'version'",
"]",
"or",
"0",
",",
")"
] | [
476,
0
] | [
504,
5
] | python | en | ['en', 'en', 'en'] | True |
cookiejar_from_dict | (cookie_dict, cookiejar=None, overwrite=True) | Returns a CookieJar from a key/value dictionary.
:param cookie_dict: Dict of key/values to insert into CookieJar.
:param cookiejar: (optional) A cookiejar to add the cookies to.
:param overwrite: (optional) If False, will not replace cookies
already in the jar with new ones.
:rtype: CookieJar
| Returns a CookieJar from a key/value dictionary. | def cookiejar_from_dict(cookie_dict, cookiejar=None, overwrite=True):
"""Returns a CookieJar from a key/value dictionary.
:param cookie_dict: Dict of key/values to insert into CookieJar.
:param cookiejar: (optional) A cookiejar to add the cookies to.
:param overwrite: (optional) If False, will not replace cookies
already in the jar with new ones.
:rtype: CookieJar
"""
if cookiejar is None:
cookiejar = RequestsCookieJar()
if cookie_dict is not None:
names_from_jar = [cookie.name for cookie in cookiejar]
for name in cookie_dict:
if overwrite or (name not in names_from_jar):
cookiejar.set_cookie(create_cookie(name, cookie_dict[name]))
return cookiejar | [
"def",
"cookiejar_from_dict",
"(",
"cookie_dict",
",",
"cookiejar",
"=",
"None",
",",
"overwrite",
"=",
"True",
")",
":",
"if",
"cookiejar",
"is",
"None",
":",
"cookiejar",
"=",
"RequestsCookieJar",
"(",
")",
"if",
"cookie_dict",
"is",
"not",
"None",
":",
"names_from_jar",
"=",
"[",
"cookie",
".",
"name",
"for",
"cookie",
"in",
"cookiejar",
"]",
"for",
"name",
"in",
"cookie_dict",
":",
"if",
"overwrite",
"or",
"(",
"name",
"not",
"in",
"names_from_jar",
")",
":",
"cookiejar",
".",
"set_cookie",
"(",
"create_cookie",
"(",
"name",
",",
"cookie_dict",
"[",
"name",
"]",
")",
")",
"return",
"cookiejar"
] | [
507,
0
] | [
525,
20
] | python | en | ['en', 'en', 'en'] | True |
merge_cookies | (cookiejar, cookies) | Add cookies to cookiejar and returns a merged CookieJar.
:param cookiejar: CookieJar object to add the cookies to.
:param cookies: Dictionary or CookieJar object to be added.
:rtype: CookieJar
| Add cookies to cookiejar and returns a merged CookieJar. | def merge_cookies(cookiejar, cookies):
"""Add cookies to cookiejar and returns a merged CookieJar.
:param cookiejar: CookieJar object to add the cookies to.
:param cookies: Dictionary or CookieJar object to be added.
:rtype: CookieJar
"""
if not isinstance(cookiejar, cookielib.CookieJar):
raise ValueError('You can only merge into CookieJar')
if isinstance(cookies, dict):
cookiejar = cookiejar_from_dict(
cookies, cookiejar=cookiejar, overwrite=False)
elif isinstance(cookies, cookielib.CookieJar):
try:
cookiejar.update(cookies)
except AttributeError:
for cookie_in_jar in cookies:
cookiejar.set_cookie(cookie_in_jar)
return cookiejar | [
"def",
"merge_cookies",
"(",
"cookiejar",
",",
"cookies",
")",
":",
"if",
"not",
"isinstance",
"(",
"cookiejar",
",",
"cookielib",
".",
"CookieJar",
")",
":",
"raise",
"ValueError",
"(",
"'You can only merge into CookieJar'",
")",
"if",
"isinstance",
"(",
"cookies",
",",
"dict",
")",
":",
"cookiejar",
"=",
"cookiejar_from_dict",
"(",
"cookies",
",",
"cookiejar",
"=",
"cookiejar",
",",
"overwrite",
"=",
"False",
")",
"elif",
"isinstance",
"(",
"cookies",
",",
"cookielib",
".",
"CookieJar",
")",
":",
"try",
":",
"cookiejar",
".",
"update",
"(",
"cookies",
")",
"except",
"AttributeError",
":",
"for",
"cookie_in_jar",
"in",
"cookies",
":",
"cookiejar",
".",
"set_cookie",
"(",
"cookie_in_jar",
")",
"return",
"cookiejar"
] | [
528,
0
] | [
548,
20
] | python | en | ['en', 'af', 'en'] | True |
MockRequest.add_header | (self, key, val) | cookielib has no legitimate use for this method; add it back if you find one. | cookielib has no legitimate use for this method; add it back if you find one. | def add_header(self, key, val):
"""cookielib has no legitimate use for this method; add it back if you find one."""
raise NotImplementedError("Cookie headers should be added with add_unredirected_header()") | [
"def",
"add_header",
"(",
"self",
",",
"key",
",",
"val",
")",
":",
"raise",
"NotImplementedError",
"(",
"\"Cookie headers should be added with add_unredirected_header()\"",
")"
] | [
73,
4
] | [
75,
98
] | python | en | ['en', 'en', 'en'] | True |
MockResponse.__init__ | (self, headers) | Make a MockResponse for `cookielib` to read.
:param headers: a httplib.HTTPMessage or analogous carrying the headers
| Make a MockResponse for `cookielib` to read. | def __init__(self, headers):
"""Make a MockResponse for `cookielib` to read.
:param headers: a httplib.HTTPMessage or analogous carrying the headers
"""
self._headers = headers | [
"def",
"__init__",
"(",
"self",
",",
"headers",
")",
":",
"self",
".",
"_headers",
"=",
"headers"
] | [
103,
4
] | [
108,
31
] | python | en | ['en', 'en', 'en'] | True |
RequestsCookieJar.get | (self, name, default=None, domain=None, path=None) | Dict-like get() that also supports optional domain and path args in
order to resolve naming collisions from using one cookie jar over
multiple domains.
.. warning:: operation is O(n), not O(1).
| Dict-like get() that also supports optional domain and path args in
order to resolve naming collisions from using one cookie jar over
multiple domains. | def get(self, name, default=None, domain=None, path=None):
"""Dict-like get() that also supports optional domain and path args in
order to resolve naming collisions from using one cookie jar over
multiple domains.
.. warning:: operation is O(n), not O(1).
"""
try:
return self._find_no_duplicates(name, domain, path)
except KeyError:
return default | [
"def",
"get",
"(",
"self",
",",
"name",
",",
"default",
"=",
"None",
",",
"domain",
"=",
"None",
",",
"path",
"=",
"None",
")",
":",
"try",
":",
"return",
"self",
".",
"_find_no_duplicates",
"(",
"name",
",",
"domain",
",",
"path",
")",
"except",
"KeyError",
":",
"return",
"default"
] | [
188,
4
] | [
198,
26
] | python | en | ['en', 'en', 'en'] | True |
RequestsCookieJar.set | (self, name, value, **kwargs) | Dict-like set() that also supports optional domain and path args in
order to resolve naming collisions from using one cookie jar over
multiple domains.
| Dict-like set() that also supports optional domain and path args in
order to resolve naming collisions from using one cookie jar over
multiple domains.
| def set(self, name, value, **kwargs):
"""Dict-like set() that also supports optional domain and path args in
order to resolve naming collisions from using one cookie jar over
multiple domains.
"""
# support client code that unsets cookies by assignment of a None value:
if value is None:
remove_cookie_by_name(self, name, domain=kwargs.get('domain'), path=kwargs.get('path'))
return
if isinstance(value, Morsel):
c = morsel_to_cookie(value)
else:
c = create_cookie(name, value, **kwargs)
self.set_cookie(c)
return c | [
"def",
"set",
"(",
"self",
",",
"name",
",",
"value",
",",
"*",
"*",
"kwargs",
")",
":",
"# support client code that unsets cookies by assignment of a None value:",
"if",
"value",
"is",
"None",
":",
"remove_cookie_by_name",
"(",
"self",
",",
"name",
",",
"domain",
"=",
"kwargs",
".",
"get",
"(",
"'domain'",
")",
",",
"path",
"=",
"kwargs",
".",
"get",
"(",
"'path'",
")",
")",
"return",
"if",
"isinstance",
"(",
"value",
",",
"Morsel",
")",
":",
"c",
"=",
"morsel_to_cookie",
"(",
"value",
")",
"else",
":",
"c",
"=",
"create_cookie",
"(",
"name",
",",
"value",
",",
"*",
"*",
"kwargs",
")",
"self",
".",
"set_cookie",
"(",
"c",
")",
"return",
"c"
] | [
200,
4
] | [
215,
16
] | python | en | ['en', 'en', 'en'] | True |
RequestsCookieJar.iterkeys | (self) | Dict-like iterkeys() that returns an iterator of names of cookies
from the jar.
.. seealso:: itervalues() and iteritems().
| Dict-like iterkeys() that returns an iterator of names of cookies
from the jar. | def iterkeys(self):
"""Dict-like iterkeys() that returns an iterator of names of cookies
from the jar.
.. seealso:: itervalues() and iteritems().
"""
for cookie in iter(self):
yield cookie.name | [
"def",
"iterkeys",
"(",
"self",
")",
":",
"for",
"cookie",
"in",
"iter",
"(",
"self",
")",
":",
"yield",
"cookie",
".",
"name"
] | [
217,
4
] | [
224,
29
] | python | en | ['en', 'en', 'en'] | True |
RequestsCookieJar.keys | (self) | Dict-like keys() that returns a list of names of cookies from the
jar.
.. seealso:: values() and items().
| Dict-like keys() that returns a list of names of cookies from the
jar. | def keys(self):
"""Dict-like keys() that returns a list of names of cookies from the
jar.
.. seealso:: values() and items().
"""
return list(self.iterkeys()) | [
"def",
"keys",
"(",
"self",
")",
":",
"return",
"list",
"(",
"self",
".",
"iterkeys",
"(",
")",
")"
] | [
226,
4
] | [
232,
36
] | python | en | ['en', 'en', 'en'] | True |
RequestsCookieJar.itervalues | (self) | Dict-like itervalues() that returns an iterator of values of cookies
from the jar.
.. seealso:: iterkeys() and iteritems().
| Dict-like itervalues() that returns an iterator of values of cookies
from the jar. | def itervalues(self):
"""Dict-like itervalues() that returns an iterator of values of cookies
from the jar.
.. seealso:: iterkeys() and iteritems().
"""
for cookie in iter(self):
yield cookie.value | [
"def",
"itervalues",
"(",
"self",
")",
":",
"for",
"cookie",
"in",
"iter",
"(",
"self",
")",
":",
"yield",
"cookie",
".",
"value"
] | [
234,
4
] | [
241,
30
] | python | en | ['en', 'en', 'en'] | True |
RequestsCookieJar.values | (self) | Dict-like values() that returns a list of values of cookies from the
jar.
.. seealso:: keys() and items().
| Dict-like values() that returns a list of values of cookies from the
jar. | def values(self):
"""Dict-like values() that returns a list of values of cookies from the
jar.
.. seealso:: keys() and items().
"""
return list(self.itervalues()) | [
"def",
"values",
"(",
"self",
")",
":",
"return",
"list",
"(",
"self",
".",
"itervalues",
"(",
")",
")"
] | [
243,
4
] | [
249,
38
] | python | en | ['en', 'en', 'en'] | True |
RequestsCookieJar.iteritems | (self) | Dict-like iteritems() that returns an iterator of name-value tuples
from the jar.
.. seealso:: iterkeys() and itervalues().
| Dict-like iteritems() that returns an iterator of name-value tuples
from the jar. | def iteritems(self):
"""Dict-like iteritems() that returns an iterator of name-value tuples
from the jar.
.. seealso:: iterkeys() and itervalues().
"""
for cookie in iter(self):
yield cookie.name, cookie.value | [
"def",
"iteritems",
"(",
"self",
")",
":",
"for",
"cookie",
"in",
"iter",
"(",
"self",
")",
":",
"yield",
"cookie",
".",
"name",
",",
"cookie",
".",
"value"
] | [
251,
4
] | [
258,
43
] | python | en | ['en', 'en', 'en'] | True |
RequestsCookieJar.items | (self) | Dict-like items() that returns a list of name-value tuples from the
jar. Allows client-code to call ``dict(RequestsCookieJar)`` and get a
vanilla python dict of key value pairs.
.. seealso:: keys() and values().
| Dict-like items() that returns a list of name-value tuples from the
jar. Allows client-code to call ``dict(RequestsCookieJar)`` and get a
vanilla python dict of key value pairs. | def items(self):
"""Dict-like items() that returns a list of name-value tuples from the
jar. Allows client-code to call ``dict(RequestsCookieJar)`` and get a
vanilla python dict of key value pairs.
.. seealso:: keys() and values().
"""
return list(self.iteritems()) | [
"def",
"items",
"(",
"self",
")",
":",
"return",
"list",
"(",
"self",
".",
"iteritems",
"(",
")",
")"
] | [
260,
4
] | [
267,
37
] | python | en | ['en', 'en', 'en'] | True |
RequestsCookieJar.list_domains | (self) | Utility method to list all the domains in the jar. | Utility method to list all the domains in the jar. | def list_domains(self):
"""Utility method to list all the domains in the jar."""
domains = []
for cookie in iter(self):
if cookie.domain not in domains:
domains.append(cookie.domain)
return domains | [
"def",
"list_domains",
"(",
"self",
")",
":",
"domains",
"=",
"[",
"]",
"for",
"cookie",
"in",
"iter",
"(",
"self",
")",
":",
"if",
"cookie",
".",
"domain",
"not",
"in",
"domains",
":",
"domains",
".",
"append",
"(",
"cookie",
".",
"domain",
")",
"return",
"domains"
] | [
269,
4
] | [
275,
22
] | python | en | ['en', 'en', 'en'] | True |
RequestsCookieJar.list_paths | (self) | Utility method to list all the paths in the jar. | Utility method to list all the paths in the jar. | def list_paths(self):
"""Utility method to list all the paths in the jar."""
paths = []
for cookie in iter(self):
if cookie.path not in paths:
paths.append(cookie.path)
return paths | [
"def",
"list_paths",
"(",
"self",
")",
":",
"paths",
"=",
"[",
"]",
"for",
"cookie",
"in",
"iter",
"(",
"self",
")",
":",
"if",
"cookie",
".",
"path",
"not",
"in",
"paths",
":",
"paths",
".",
"append",
"(",
"cookie",
".",
"path",
")",
"return",
"paths"
] | [
277,
4
] | [
283,
20
] | python | en | ['en', 'en', 'en'] | True |
RequestsCookieJar.multiple_domains | (self) | Returns True if there are multiple domains in the jar.
Returns False otherwise.
:rtype: bool
| Returns True if there are multiple domains in the jar.
Returns False otherwise. | def multiple_domains(self):
"""Returns True if there are multiple domains in the jar.
Returns False otherwise.
:rtype: bool
"""
domains = []
for cookie in iter(self):
if cookie.domain is not None and cookie.domain in domains:
return True
domains.append(cookie.domain)
return False | [
"def",
"multiple_domains",
"(",
"self",
")",
":",
"domains",
"=",
"[",
"]",
"for",
"cookie",
"in",
"iter",
"(",
"self",
")",
":",
"if",
"cookie",
".",
"domain",
"is",
"not",
"None",
"and",
"cookie",
".",
"domain",
"in",
"domains",
":",
"return",
"True",
"domains",
".",
"append",
"(",
"cookie",
".",
"domain",
")",
"return",
"False"
] | [
285,
4
] | [
296,
20
] | python | en | ['en', 'en', 'en'] | True |
RequestsCookieJar.get_dict | (self, domain=None, path=None) | Takes as an argument an optional domain and path and returns a plain
old Python dict of name-value pairs of cookies that meet the
requirements.
:rtype: dict
| Takes as an argument an optional domain and path and returns a plain
old Python dict of name-value pairs of cookies that meet the
requirements. | def get_dict(self, domain=None, path=None):
"""Takes as an argument an optional domain and path and returns a plain
old Python dict of name-value pairs of cookies that meet the
requirements.
:rtype: dict
"""
dictionary = {}
for cookie in iter(self):
if (
(domain is None or cookie.domain == domain) and
(path is None or cookie.path == path)
):
dictionary[cookie.name] = cookie.value
return dictionary | [
"def",
"get_dict",
"(",
"self",
",",
"domain",
"=",
"None",
",",
"path",
"=",
"None",
")",
":",
"dictionary",
"=",
"{",
"}",
"for",
"cookie",
"in",
"iter",
"(",
"self",
")",
":",
"if",
"(",
"(",
"domain",
"is",
"None",
"or",
"cookie",
".",
"domain",
"==",
"domain",
")",
"and",
"(",
"path",
"is",
"None",
"or",
"cookie",
".",
"path",
"==",
"path",
")",
")",
":",
"dictionary",
"[",
"cookie",
".",
"name",
"]",
"=",
"cookie",
".",
"value",
"return",
"dictionary"
] | [
298,
4
] | [
312,
25
] | python | en | ['en', 'en', 'en'] | True |
RequestsCookieJar.__getitem__ | (self, name) | Dict-like __getitem__() for compatibility with client code. Throws
exception if there are more than one cookie with name. In that case,
use the more explicit get() method instead.
.. warning:: operation is O(n), not O(1).
| Dict-like __getitem__() for compatibility with client code. Throws
exception if there are more than one cookie with name. In that case,
use the more explicit get() method instead. | def __getitem__(self, name):
"""Dict-like __getitem__() for compatibility with client code. Throws
exception if there are more than one cookie with name. In that case,
use the more explicit get() method instead.
.. warning:: operation is O(n), not O(1).
"""
return self._find_no_duplicates(name) | [
"def",
"__getitem__",
"(",
"self",
",",
"name",
")",
":",
"return",
"self",
".",
"_find_no_duplicates",
"(",
"name",
")"
] | [
320,
4
] | [
327,
45
] | python | en | ['en', 'en', 'en'] | True |
RequestsCookieJar.__setitem__ | (self, name, value) | Dict-like __setitem__ for compatibility with client code. Throws
exception if there is already a cookie of that name in the jar. In that
case, use the more explicit set() method instead.
| Dict-like __setitem__ for compatibility with client code. Throws
exception if there is already a cookie of that name in the jar. In that
case, use the more explicit set() method instead.
| def __setitem__(self, name, value):
"""Dict-like __setitem__ for compatibility with client code. Throws
exception if there is already a cookie of that name in the jar. In that
case, use the more explicit set() method instead.
"""
self.set(name, value) | [
"def",
"__setitem__",
"(",
"self",
",",
"name",
",",
"value",
")",
":",
"self",
".",
"set",
"(",
"name",
",",
"value",
")"
] | [
329,
4
] | [
334,
29
] | python | en | ['en', 'en', 'en'] | True |
RequestsCookieJar.__delitem__ | (self, name) | Deletes a cookie given a name. Wraps ``cookielib.CookieJar``'s
``remove_cookie_by_name()``.
| Deletes a cookie given a name. Wraps ``cookielib.CookieJar``'s
``remove_cookie_by_name()``.
| def __delitem__(self, name):
"""Deletes a cookie given a name. Wraps ``cookielib.CookieJar``'s
``remove_cookie_by_name()``.
"""
remove_cookie_by_name(self, name) | [
"def",
"__delitem__",
"(",
"self",
",",
"name",
")",
":",
"remove_cookie_by_name",
"(",
"self",
",",
"name",
")"
] | [
336,
4
] | [
340,
41
] | python | en | ['en', 'en', 'en'] | True |
RequestsCookieJar.update | (self, other) | Updates this jar with cookies from another CookieJar or dict-like | Updates this jar with cookies from another CookieJar or dict-like | def update(self, other):
"""Updates this jar with cookies from another CookieJar or dict-like"""
if isinstance(other, cookielib.CookieJar):
for cookie in other:
self.set_cookie(copy.copy(cookie))
else:
super(RequestsCookieJar, self).update(other) | [
"def",
"update",
"(",
"self",
",",
"other",
")",
":",
"if",
"isinstance",
"(",
"other",
",",
"cookielib",
".",
"CookieJar",
")",
":",
"for",
"cookie",
"in",
"other",
":",
"self",
".",
"set_cookie",
"(",
"copy",
".",
"copy",
"(",
"cookie",
")",
")",
"else",
":",
"super",
"(",
"RequestsCookieJar",
",",
"self",
")",
".",
"update",
"(",
"other",
")"
] | [
347,
4
] | [
353,
56
] | python | en | ['en', 'en', 'en'] | True |
RequestsCookieJar._find | (self, name, domain=None, path=None) | Requests uses this method internally to get cookie values.
If there are conflicting cookies, _find arbitrarily chooses one.
See _find_no_duplicates if you want an exception thrown if there are
conflicting cookies.
:param name: a string containing name of cookie
:param domain: (optional) string containing domain of cookie
:param path: (optional) string containing path of cookie
:return: cookie.value
| Requests uses this method internally to get cookie values. | def _find(self, name, domain=None, path=None):
"""Requests uses this method internally to get cookie values.
If there are conflicting cookies, _find arbitrarily chooses one.
See _find_no_duplicates if you want an exception thrown if there are
conflicting cookies.
:param name: a string containing name of cookie
:param domain: (optional) string containing domain of cookie
:param path: (optional) string containing path of cookie
:return: cookie.value
"""
for cookie in iter(self):
if cookie.name == name:
if domain is None or cookie.domain == domain:
if path is None or cookie.path == path:
return cookie.value
raise KeyError('name=%r, domain=%r, path=%r' % (name, domain, path)) | [
"def",
"_find",
"(",
"self",
",",
"name",
",",
"domain",
"=",
"None",
",",
"path",
"=",
"None",
")",
":",
"for",
"cookie",
"in",
"iter",
"(",
"self",
")",
":",
"if",
"cookie",
".",
"name",
"==",
"name",
":",
"if",
"domain",
"is",
"None",
"or",
"cookie",
".",
"domain",
"==",
"domain",
":",
"if",
"path",
"is",
"None",
"or",
"cookie",
".",
"path",
"==",
"path",
":",
"return",
"cookie",
".",
"value",
"raise",
"KeyError",
"(",
"'name=%r, domain=%r, path=%r'",
"%",
"(",
"name",
",",
"domain",
",",
"path",
")",
")"
] | [
355,
4
] | [
373,
76
] | python | en | ['en', 'en', 'en'] | True |
RequestsCookieJar._find_no_duplicates | (self, name, domain=None, path=None) | Both ``__get_item__`` and ``get`` call this function: it's never
used elsewhere in Requests.
:param name: a string containing name of cookie
:param domain: (optional) string containing domain of cookie
:param path: (optional) string containing path of cookie
:raises KeyError: if cookie is not found
:raises CookieConflictError: if there are multiple cookies
that match name and optionally domain and path
:return: cookie.value
| Both ``__get_item__`` and ``get`` call this function: it's never
used elsewhere in Requests. | def _find_no_duplicates(self, name, domain=None, path=None):
"""Both ``__get_item__`` and ``get`` call this function: it's never
used elsewhere in Requests.
:param name: a string containing name of cookie
:param domain: (optional) string containing domain of cookie
:param path: (optional) string containing path of cookie
:raises KeyError: if cookie is not found
:raises CookieConflictError: if there are multiple cookies
that match name and optionally domain and path
:return: cookie.value
"""
toReturn = None
for cookie in iter(self):
if cookie.name == name:
if domain is None or cookie.domain == domain:
if path is None or cookie.path == path:
if toReturn is not None: # if there are multiple cookies that meet passed in criteria
raise CookieConflictError('There are multiple cookies with name, %r' % (name))
toReturn = cookie.value # we will eventually return this as long as no cookie conflict
if toReturn:
return toReturn
raise KeyError('name=%r, domain=%r, path=%r' % (name, domain, path)) | [
"def",
"_find_no_duplicates",
"(",
"self",
",",
"name",
",",
"domain",
"=",
"None",
",",
"path",
"=",
"None",
")",
":",
"toReturn",
"=",
"None",
"for",
"cookie",
"in",
"iter",
"(",
"self",
")",
":",
"if",
"cookie",
".",
"name",
"==",
"name",
":",
"if",
"domain",
"is",
"None",
"or",
"cookie",
".",
"domain",
"==",
"domain",
":",
"if",
"path",
"is",
"None",
"or",
"cookie",
".",
"path",
"==",
"path",
":",
"if",
"toReturn",
"is",
"not",
"None",
":",
"# if there are multiple cookies that meet passed in criteria",
"raise",
"CookieConflictError",
"(",
"'There are multiple cookies with name, %r'",
"%",
"(",
"name",
")",
")",
"toReturn",
"=",
"cookie",
".",
"value",
"# we will eventually return this as long as no cookie conflict",
"if",
"toReturn",
":",
"return",
"toReturn",
"raise",
"KeyError",
"(",
"'name=%r, domain=%r, path=%r'",
"%",
"(",
"name",
",",
"domain",
",",
"path",
")",
")"
] | [
375,
4
] | [
398,
76
] | python | en | ['en', 'en', 'en'] | True |
RequestsCookieJar.__getstate__ | (self) | Unlike a normal CookieJar, this class is pickleable. | Unlike a normal CookieJar, this class is pickleable. | def __getstate__(self):
"""Unlike a normal CookieJar, this class is pickleable."""
state = self.__dict__.copy()
# remove the unpickleable RLock object
state.pop('_cookies_lock')
return state | [
"def",
"__getstate__",
"(",
"self",
")",
":",
"state",
"=",
"self",
".",
"__dict__",
".",
"copy",
"(",
")",
"# remove the unpickleable RLock object",
"state",
".",
"pop",
"(",
"'_cookies_lock'",
")",
"return",
"state"
] | [
400,
4
] | [
405,
20
] | python | en | ['en', 'en', 'en'] | True |
RequestsCookieJar.__setstate__ | (self, state) | Unlike a normal CookieJar, this class is pickleable. | Unlike a normal CookieJar, this class is pickleable. | def __setstate__(self, state):
"""Unlike a normal CookieJar, this class is pickleable."""
self.__dict__.update(state)
if '_cookies_lock' not in self.__dict__:
self._cookies_lock = threading.RLock() | [
"def",
"__setstate__",
"(",
"self",
",",
"state",
")",
":",
"self",
".",
"__dict__",
".",
"update",
"(",
"state",
")",
"if",
"'_cookies_lock'",
"not",
"in",
"self",
".",
"__dict__",
":",
"self",
".",
"_cookies_lock",
"=",
"threading",
".",
"RLock",
"(",
")"
] | [
407,
4
] | [
411,
50
] | python | en | ['en', 'en', 'en'] | True |
RequestsCookieJar.copy | (self) | Return a copy of this RequestsCookieJar. | Return a copy of this RequestsCookieJar. | def copy(self):
"""Return a copy of this RequestsCookieJar."""
new_cj = RequestsCookieJar()
new_cj.set_policy(self.get_policy())
new_cj.update(self)
return new_cj | [
"def",
"copy",
"(",
"self",
")",
":",
"new_cj",
"=",
"RequestsCookieJar",
"(",
")",
"new_cj",
".",
"set_policy",
"(",
"self",
".",
"get_policy",
"(",
")",
")",
"new_cj",
".",
"update",
"(",
"self",
")",
"return",
"new_cj"
] | [
413,
4
] | [
418,
21
] | python | en | ['en', 'en', 'en'] | True |
RequestsCookieJar.get_policy | (self) | Return the CookiePolicy instance used. | Return the CookiePolicy instance used. | def get_policy(self):
"""Return the CookiePolicy instance used."""
return self._policy | [
"def",
"get_policy",
"(",
"self",
")",
":",
"return",
"self",
".",
"_policy"
] | [
420,
4
] | [
422,
27
] | python | en | ['en', 'en', 'en'] | True |
MigrationExecutor.migration_plan | (self, targets, clean_start=False) |
Given a set of targets, return a list of (Migration instance, backwards?).
|
Given a set of targets, return a list of (Migration instance, backwards?).
| def migration_plan(self, targets, clean_start=False):
"""
Given a set of targets, return a list of (Migration instance, backwards?).
"""
plan = []
if clean_start:
applied = {}
else:
applied = dict(self.loader.applied_migrations)
for target in targets:
# If the target is (app_label, None), that means unmigrate everything
if target[1] is None:
for root in self.loader.graph.root_nodes():
if root[0] == target[0]:
for migration in self.loader.graph.backwards_plan(root):
if migration in applied:
plan.append((self.loader.graph.nodes[migration], True))
applied.pop(migration)
# If the migration is already applied, do backwards mode,
# otherwise do forwards mode.
elif target in applied:
# Don't migrate backwards all the way to the target node (that
# may roll back dependencies in other apps that don't need to
# be rolled back); instead roll back through target's immediate
# child(ren) in the same app, and no further.
next_in_app = sorted(
n for n in
self.loader.graph.node_map[target].children
if n[0] == target[0]
)
for node in next_in_app:
for migration in self.loader.graph.backwards_plan(node):
if migration in applied:
plan.append((self.loader.graph.nodes[migration], True))
applied.pop(migration)
else:
for migration in self.loader.graph.forwards_plan(target):
if migration not in applied:
plan.append((self.loader.graph.nodes[migration], False))
applied[migration] = self.loader.graph.nodes[migration]
return plan | [
"def",
"migration_plan",
"(",
"self",
",",
"targets",
",",
"clean_start",
"=",
"False",
")",
":",
"plan",
"=",
"[",
"]",
"if",
"clean_start",
":",
"applied",
"=",
"{",
"}",
"else",
":",
"applied",
"=",
"dict",
"(",
"self",
".",
"loader",
".",
"applied_migrations",
")",
"for",
"target",
"in",
"targets",
":",
"# If the target is (app_label, None), that means unmigrate everything",
"if",
"target",
"[",
"1",
"]",
"is",
"None",
":",
"for",
"root",
"in",
"self",
".",
"loader",
".",
"graph",
".",
"root_nodes",
"(",
")",
":",
"if",
"root",
"[",
"0",
"]",
"==",
"target",
"[",
"0",
"]",
":",
"for",
"migration",
"in",
"self",
".",
"loader",
".",
"graph",
".",
"backwards_plan",
"(",
"root",
")",
":",
"if",
"migration",
"in",
"applied",
":",
"plan",
".",
"append",
"(",
"(",
"self",
".",
"loader",
".",
"graph",
".",
"nodes",
"[",
"migration",
"]",
",",
"True",
")",
")",
"applied",
".",
"pop",
"(",
"migration",
")",
"# If the migration is already applied, do backwards mode,",
"# otherwise do forwards mode.",
"elif",
"target",
"in",
"applied",
":",
"# Don't migrate backwards all the way to the target node (that",
"# may roll back dependencies in other apps that don't need to",
"# be rolled back); instead roll back through target's immediate",
"# child(ren) in the same app, and no further.",
"next_in_app",
"=",
"sorted",
"(",
"n",
"for",
"n",
"in",
"self",
".",
"loader",
".",
"graph",
".",
"node_map",
"[",
"target",
"]",
".",
"children",
"if",
"n",
"[",
"0",
"]",
"==",
"target",
"[",
"0",
"]",
")",
"for",
"node",
"in",
"next_in_app",
":",
"for",
"migration",
"in",
"self",
".",
"loader",
".",
"graph",
".",
"backwards_plan",
"(",
"node",
")",
":",
"if",
"migration",
"in",
"applied",
":",
"plan",
".",
"append",
"(",
"(",
"self",
".",
"loader",
".",
"graph",
".",
"nodes",
"[",
"migration",
"]",
",",
"True",
")",
")",
"applied",
".",
"pop",
"(",
"migration",
")",
"else",
":",
"for",
"migration",
"in",
"self",
".",
"loader",
".",
"graph",
".",
"forwards_plan",
"(",
"target",
")",
":",
"if",
"migration",
"not",
"in",
"applied",
":",
"plan",
".",
"append",
"(",
"(",
"self",
".",
"loader",
".",
"graph",
".",
"nodes",
"[",
"migration",
"]",
",",
"False",
")",
")",
"applied",
"[",
"migration",
"]",
"=",
"self",
".",
"loader",
".",
"graph",
".",
"nodes",
"[",
"migration",
"]",
"return",
"plan"
] | [
21,
4
] | [
61,
19
] | python | en | ['en', 'error', 'th'] | False |
MigrationExecutor._create_project_state | (self, with_applied_migrations=False) |
Create a project state including all the applications without
migrations and applied migrations if with_applied_migrations=True.
|
Create a project state including all the applications without
migrations and applied migrations if with_applied_migrations=True.
| def _create_project_state(self, with_applied_migrations=False):
"""
Create a project state including all the applications without
migrations and applied migrations if with_applied_migrations=True.
"""
state = ProjectState(real_apps=list(self.loader.unmigrated_apps))
if with_applied_migrations:
# Create the forwards plan Django would follow on an empty database
full_plan = self.migration_plan(self.loader.graph.leaf_nodes(), clean_start=True)
applied_migrations = {
self.loader.graph.nodes[key] for key in self.loader.applied_migrations
if key in self.loader.graph.nodes
}
for migration, _ in full_plan:
if migration in applied_migrations:
migration.mutate_state(state, preserve=False)
return state | [
"def",
"_create_project_state",
"(",
"self",
",",
"with_applied_migrations",
"=",
"False",
")",
":",
"state",
"=",
"ProjectState",
"(",
"real_apps",
"=",
"list",
"(",
"self",
".",
"loader",
".",
"unmigrated_apps",
")",
")",
"if",
"with_applied_migrations",
":",
"# Create the forwards plan Django would follow on an empty database",
"full_plan",
"=",
"self",
".",
"migration_plan",
"(",
"self",
".",
"loader",
".",
"graph",
".",
"leaf_nodes",
"(",
")",
",",
"clean_start",
"=",
"True",
")",
"applied_migrations",
"=",
"{",
"self",
".",
"loader",
".",
"graph",
".",
"nodes",
"[",
"key",
"]",
"for",
"key",
"in",
"self",
".",
"loader",
".",
"applied_migrations",
"if",
"key",
"in",
"self",
".",
"loader",
".",
"graph",
".",
"nodes",
"}",
"for",
"migration",
",",
"_",
"in",
"full_plan",
":",
"if",
"migration",
"in",
"applied_migrations",
":",
"migration",
".",
"mutate_state",
"(",
"state",
",",
"preserve",
"=",
"False",
")",
"return",
"state"
] | [
63,
4
] | [
79,
20
] | python | en | ['en', 'error', 'th'] | False |
MigrationExecutor.migrate | (self, targets, plan=None, state=None, fake=False, fake_initial=False) |
Migrate the database up to the given targets.
Django first needs to create all project states before a migration is
(un)applied and in a second step run all the database operations.
|
Migrate the database up to the given targets. | def migrate(self, targets, plan=None, state=None, fake=False, fake_initial=False):
"""
Migrate the database up to the given targets.
Django first needs to create all project states before a migration is
(un)applied and in a second step run all the database operations.
"""
# The django_migrations table must be present to record applied
# migrations.
self.recorder.ensure_schema()
if plan is None:
plan = self.migration_plan(targets)
# Create the forwards plan Django would follow on an empty database
full_plan = self.migration_plan(self.loader.graph.leaf_nodes(), clean_start=True)
all_forwards = all(not backwards for mig, backwards in plan)
all_backwards = all(backwards for mig, backwards in plan)
if not plan:
if state is None:
# The resulting state should include applied migrations.
state = self._create_project_state(with_applied_migrations=True)
elif all_forwards == all_backwards:
# This should only happen if there's a mixed plan
raise InvalidMigrationPlan(
"Migration plans with both forwards and backwards migrations "
"are not supported. Please split your migration process into "
"separate plans of only forwards OR backwards migrations.",
plan
)
elif all_forwards:
if state is None:
# The resulting state should still include applied migrations.
state = self._create_project_state(with_applied_migrations=True)
state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial)
else:
# No need to check for `elif all_backwards` here, as that condition
# would always evaluate to true.
state = self._migrate_all_backwards(plan, full_plan, fake=fake)
self.check_replacements()
return state | [
"def",
"migrate",
"(",
"self",
",",
"targets",
",",
"plan",
"=",
"None",
",",
"state",
"=",
"None",
",",
"fake",
"=",
"False",
",",
"fake_initial",
"=",
"False",
")",
":",
"# The django_migrations table must be present to record applied",
"# migrations.",
"self",
".",
"recorder",
".",
"ensure_schema",
"(",
")",
"if",
"plan",
"is",
"None",
":",
"plan",
"=",
"self",
".",
"migration_plan",
"(",
"targets",
")",
"# Create the forwards plan Django would follow on an empty database",
"full_plan",
"=",
"self",
".",
"migration_plan",
"(",
"self",
".",
"loader",
".",
"graph",
".",
"leaf_nodes",
"(",
")",
",",
"clean_start",
"=",
"True",
")",
"all_forwards",
"=",
"all",
"(",
"not",
"backwards",
"for",
"mig",
",",
"backwards",
"in",
"plan",
")",
"all_backwards",
"=",
"all",
"(",
"backwards",
"for",
"mig",
",",
"backwards",
"in",
"plan",
")",
"if",
"not",
"plan",
":",
"if",
"state",
"is",
"None",
":",
"# The resulting state should include applied migrations.",
"state",
"=",
"self",
".",
"_create_project_state",
"(",
"with_applied_migrations",
"=",
"True",
")",
"elif",
"all_forwards",
"==",
"all_backwards",
":",
"# This should only happen if there's a mixed plan",
"raise",
"InvalidMigrationPlan",
"(",
"\"Migration plans with both forwards and backwards migrations \"",
"\"are not supported. Please split your migration process into \"",
"\"separate plans of only forwards OR backwards migrations.\"",
",",
"plan",
")",
"elif",
"all_forwards",
":",
"if",
"state",
"is",
"None",
":",
"# The resulting state should still include applied migrations.",
"state",
"=",
"self",
".",
"_create_project_state",
"(",
"with_applied_migrations",
"=",
"True",
")",
"state",
"=",
"self",
".",
"_migrate_all_forwards",
"(",
"state",
",",
"plan",
",",
"full_plan",
",",
"fake",
"=",
"fake",
",",
"fake_initial",
"=",
"fake_initial",
")",
"else",
":",
"# No need to check for `elif all_backwards` here, as that condition",
"# would always evaluate to true.",
"state",
"=",
"self",
".",
"_migrate_all_backwards",
"(",
"plan",
",",
"full_plan",
",",
"fake",
"=",
"fake",
")",
"self",
".",
"check_replacements",
"(",
")",
"return",
"state"
] | [
81,
4
] | [
124,
20
] | python | en | ['en', 'error', 'th'] | False |
MigrationExecutor._migrate_all_forwards | (self, state, plan, full_plan, fake, fake_initial) |
Take a list of 2-tuples of the form (migration instance, False) and
apply them in the order they occur in the full_plan.
|
Take a list of 2-tuples of the form (migration instance, False) and
apply them in the order they occur in the full_plan.
| def _migrate_all_forwards(self, state, plan, full_plan, fake, fake_initial):
"""
Take a list of 2-tuples of the form (migration instance, False) and
apply them in the order they occur in the full_plan.
"""
migrations_to_run = {m[0] for m in plan}
for migration, _ in full_plan:
if not migrations_to_run:
# We remove every migration that we applied from these sets so
# that we can bail out once the last migration has been applied
# and don't always run until the very end of the migration
# process.
break
if migration in migrations_to_run:
if 'apps' not in state.__dict__:
if self.progress_callback:
self.progress_callback("render_start")
state.apps # Render all -- performance critical
if self.progress_callback:
self.progress_callback("render_success")
state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial)
migrations_to_run.remove(migration)
return state | [
"def",
"_migrate_all_forwards",
"(",
"self",
",",
"state",
",",
"plan",
",",
"full_plan",
",",
"fake",
",",
"fake_initial",
")",
":",
"migrations_to_run",
"=",
"{",
"m",
"[",
"0",
"]",
"for",
"m",
"in",
"plan",
"}",
"for",
"migration",
",",
"_",
"in",
"full_plan",
":",
"if",
"not",
"migrations_to_run",
":",
"# We remove every migration that we applied from these sets so",
"# that we can bail out once the last migration has been applied",
"# and don't always run until the very end of the migration",
"# process.",
"break",
"if",
"migration",
"in",
"migrations_to_run",
":",
"if",
"'apps'",
"not",
"in",
"state",
".",
"__dict__",
":",
"if",
"self",
".",
"progress_callback",
":",
"self",
".",
"progress_callback",
"(",
"\"render_start\"",
")",
"state",
".",
"apps",
"# Render all -- performance critical",
"if",
"self",
".",
"progress_callback",
":",
"self",
".",
"progress_callback",
"(",
"\"render_success\"",
")",
"state",
"=",
"self",
".",
"apply_migration",
"(",
"state",
",",
"migration",
",",
"fake",
"=",
"fake",
",",
"fake_initial",
"=",
"fake_initial",
")",
"migrations_to_run",
".",
"remove",
"(",
"migration",
")",
"return",
"state"
] | [
126,
4
] | [
149,
20
] | python | en | ['en', 'error', 'th'] | False |
MigrationExecutor._migrate_all_backwards | (self, plan, full_plan, fake) |
Take a list of 2-tuples of the form (migration instance, True) and
unapply them in reverse order they occur in the full_plan.
Since unapplying a migration requires the project state prior to that
migration, Django will compute the migration states before each of them
in a first run over the plan and then unapply them in a second run over
the plan.
|
Take a list of 2-tuples of the form (migration instance, True) and
unapply them in reverse order they occur in the full_plan. | def _migrate_all_backwards(self, plan, full_plan, fake):
"""
Take a list of 2-tuples of the form (migration instance, True) and
unapply them in reverse order they occur in the full_plan.
Since unapplying a migration requires the project state prior to that
migration, Django will compute the migration states before each of them
in a first run over the plan and then unapply them in a second run over
the plan.
"""
migrations_to_run = {m[0] for m in plan}
# Holds all migration states prior to the migrations being unapplied
states = {}
state = self._create_project_state()
applied_migrations = {
self.loader.graph.nodes[key] for key in self.loader.applied_migrations
if key in self.loader.graph.nodes
}
if self.progress_callback:
self.progress_callback("render_start")
for migration, _ in full_plan:
if not migrations_to_run:
# We remove every migration that we applied from this set so
# that we can bail out once the last migration has been applied
# and don't always run until the very end of the migration
# process.
break
if migration in migrations_to_run:
if 'apps' not in state.__dict__:
state.apps # Render all -- performance critical
# The state before this migration
states[migration] = state
# The old state keeps as-is, we continue with the new state
state = migration.mutate_state(state, preserve=True)
migrations_to_run.remove(migration)
elif migration in applied_migrations:
# Only mutate the state if the migration is actually applied
# to make sure the resulting state doesn't include changes
# from unrelated migrations.
migration.mutate_state(state, preserve=False)
if self.progress_callback:
self.progress_callback("render_success")
for migration, _ in plan:
self.unapply_migration(states[migration], migration, fake=fake)
applied_migrations.remove(migration)
# Generate the post migration state by starting from the state before
# the last migration is unapplied and mutating it to include all the
# remaining applied migrations.
last_unapplied_migration = plan[-1][0]
state = states[last_unapplied_migration]
for index, (migration, _) in enumerate(full_plan):
if migration == last_unapplied_migration:
for migration, _ in full_plan[index:]:
if migration in applied_migrations:
migration.mutate_state(state, preserve=False)
break
return state | [
"def",
"_migrate_all_backwards",
"(",
"self",
",",
"plan",
",",
"full_plan",
",",
"fake",
")",
":",
"migrations_to_run",
"=",
"{",
"m",
"[",
"0",
"]",
"for",
"m",
"in",
"plan",
"}",
"# Holds all migration states prior to the migrations being unapplied",
"states",
"=",
"{",
"}",
"state",
"=",
"self",
".",
"_create_project_state",
"(",
")",
"applied_migrations",
"=",
"{",
"self",
".",
"loader",
".",
"graph",
".",
"nodes",
"[",
"key",
"]",
"for",
"key",
"in",
"self",
".",
"loader",
".",
"applied_migrations",
"if",
"key",
"in",
"self",
".",
"loader",
".",
"graph",
".",
"nodes",
"}",
"if",
"self",
".",
"progress_callback",
":",
"self",
".",
"progress_callback",
"(",
"\"render_start\"",
")",
"for",
"migration",
",",
"_",
"in",
"full_plan",
":",
"if",
"not",
"migrations_to_run",
":",
"# We remove every migration that we applied from this set so",
"# that we can bail out once the last migration has been applied",
"# and don't always run until the very end of the migration",
"# process.",
"break",
"if",
"migration",
"in",
"migrations_to_run",
":",
"if",
"'apps'",
"not",
"in",
"state",
".",
"__dict__",
":",
"state",
".",
"apps",
"# Render all -- performance critical",
"# The state before this migration",
"states",
"[",
"migration",
"]",
"=",
"state",
"# The old state keeps as-is, we continue with the new state",
"state",
"=",
"migration",
".",
"mutate_state",
"(",
"state",
",",
"preserve",
"=",
"True",
")",
"migrations_to_run",
".",
"remove",
"(",
"migration",
")",
"elif",
"migration",
"in",
"applied_migrations",
":",
"# Only mutate the state if the migration is actually applied",
"# to make sure the resulting state doesn't include changes",
"# from unrelated migrations.",
"migration",
".",
"mutate_state",
"(",
"state",
",",
"preserve",
"=",
"False",
")",
"if",
"self",
".",
"progress_callback",
":",
"self",
".",
"progress_callback",
"(",
"\"render_success\"",
")",
"for",
"migration",
",",
"_",
"in",
"plan",
":",
"self",
".",
"unapply_migration",
"(",
"states",
"[",
"migration",
"]",
",",
"migration",
",",
"fake",
"=",
"fake",
")",
"applied_migrations",
".",
"remove",
"(",
"migration",
")",
"# Generate the post migration state by starting from the state before",
"# the last migration is unapplied and mutating it to include all the",
"# remaining applied migrations.",
"last_unapplied_migration",
"=",
"plan",
"[",
"-",
"1",
"]",
"[",
"0",
"]",
"state",
"=",
"states",
"[",
"last_unapplied_migration",
"]",
"for",
"index",
",",
"(",
"migration",
",",
"_",
")",
"in",
"enumerate",
"(",
"full_plan",
")",
":",
"if",
"migration",
"==",
"last_unapplied_migration",
":",
"for",
"migration",
",",
"_",
"in",
"full_plan",
"[",
"index",
":",
"]",
":",
"if",
"migration",
"in",
"applied_migrations",
":",
"migration",
".",
"mutate_state",
"(",
"state",
",",
"preserve",
"=",
"False",
")",
"break",
"return",
"state"
] | [
151,
4
] | [
210,
20
] | python | en | ['en', 'error', 'th'] | False |
MigrationExecutor.apply_migration | (self, state, migration, fake=False, fake_initial=False) | Run a migration forwards. | Run a migration forwards. | def apply_migration(self, state, migration, fake=False, fake_initial=False):
"""Run a migration forwards."""
migration_recorded = False
if self.progress_callback:
self.progress_callback("apply_start", migration, fake)
if not fake:
if fake_initial:
# Test to see if this is an already-applied initial migration
applied, state = self.detect_soft_applied(state, migration)
if applied:
fake = True
if not fake:
# Alright, do it normally
with self.connection.schema_editor(atomic=migration.atomic) as schema_editor:
state = migration.apply(state, schema_editor)
if not schema_editor.deferred_sql:
self.record_migration(migration)
migration_recorded = True
if not migration_recorded:
self.record_migration(migration)
# Report progress
if self.progress_callback:
self.progress_callback("apply_success", migration, fake)
return state | [
"def",
"apply_migration",
"(",
"self",
",",
"state",
",",
"migration",
",",
"fake",
"=",
"False",
",",
"fake_initial",
"=",
"False",
")",
":",
"migration_recorded",
"=",
"False",
"if",
"self",
".",
"progress_callback",
":",
"self",
".",
"progress_callback",
"(",
"\"apply_start\"",
",",
"migration",
",",
"fake",
")",
"if",
"not",
"fake",
":",
"if",
"fake_initial",
":",
"# Test to see if this is an already-applied initial migration",
"applied",
",",
"state",
"=",
"self",
".",
"detect_soft_applied",
"(",
"state",
",",
"migration",
")",
"if",
"applied",
":",
"fake",
"=",
"True",
"if",
"not",
"fake",
":",
"# Alright, do it normally",
"with",
"self",
".",
"connection",
".",
"schema_editor",
"(",
"atomic",
"=",
"migration",
".",
"atomic",
")",
"as",
"schema_editor",
":",
"state",
"=",
"migration",
".",
"apply",
"(",
"state",
",",
"schema_editor",
")",
"if",
"not",
"schema_editor",
".",
"deferred_sql",
":",
"self",
".",
"record_migration",
"(",
"migration",
")",
"migration_recorded",
"=",
"True",
"if",
"not",
"migration_recorded",
":",
"self",
".",
"record_migration",
"(",
"migration",
")",
"# Report progress",
"if",
"self",
".",
"progress_callback",
":",
"self",
".",
"progress_callback",
"(",
"\"apply_success\"",
",",
"migration",
",",
"fake",
")",
"return",
"state"
] | [
212,
4
] | [
235,
20
] | python | en | ['es', 'en', 'en'] | True |
MigrationExecutor.unapply_migration | (self, state, migration, fake=False) | Run a migration backwards. | Run a migration backwards. | def unapply_migration(self, state, migration, fake=False):
"""Run a migration backwards."""
if self.progress_callback:
self.progress_callback("unapply_start", migration, fake)
if not fake:
with self.connection.schema_editor(atomic=migration.atomic) as schema_editor:
state = migration.unapply(state, schema_editor)
# For replacement migrations, record individual statuses
if migration.replaces:
for app_label, name in migration.replaces:
self.recorder.record_unapplied(app_label, name)
else:
self.recorder.record_unapplied(migration.app_label, migration.name)
# Report progress
if self.progress_callback:
self.progress_callback("unapply_success", migration, fake)
return state | [
"def",
"unapply_migration",
"(",
"self",
",",
"state",
",",
"migration",
",",
"fake",
"=",
"False",
")",
":",
"if",
"self",
".",
"progress_callback",
":",
"self",
".",
"progress_callback",
"(",
"\"unapply_start\"",
",",
"migration",
",",
"fake",
")",
"if",
"not",
"fake",
":",
"with",
"self",
".",
"connection",
".",
"schema_editor",
"(",
"atomic",
"=",
"migration",
".",
"atomic",
")",
"as",
"schema_editor",
":",
"state",
"=",
"migration",
".",
"unapply",
"(",
"state",
",",
"schema_editor",
")",
"# For replacement migrations, record individual statuses",
"if",
"migration",
".",
"replaces",
":",
"for",
"app_label",
",",
"name",
"in",
"migration",
".",
"replaces",
":",
"self",
".",
"recorder",
".",
"record_unapplied",
"(",
"app_label",
",",
"name",
")",
"else",
":",
"self",
".",
"recorder",
".",
"record_unapplied",
"(",
"migration",
".",
"app_label",
",",
"migration",
".",
"name",
")",
"# Report progress",
"if",
"self",
".",
"progress_callback",
":",
"self",
".",
"progress_callback",
"(",
"\"unapply_success\"",
",",
"migration",
",",
"fake",
")",
"return",
"state"
] | [
245,
4
] | [
261,
20
] | python | en | ['it', 'fil', 'en'] | False |
MigrationExecutor.check_replacements | (self) |
Mark replacement migrations applied if their replaced set all are.
Do this unconditionally on every migrate, rather than just when
migrations are applied or unapplied, to correctly handle the case
when a new squash migration is pushed to a deployment that already had
all its replaced migrations applied. In this case no new migration will
be applied, but the applied state of the squashed migration must be
maintained.
|
Mark replacement migrations applied if their replaced set all are. | def check_replacements(self):
"""
Mark replacement migrations applied if their replaced set all are.
Do this unconditionally on every migrate, rather than just when
migrations are applied or unapplied, to correctly handle the case
when a new squash migration is pushed to a deployment that already had
all its replaced migrations applied. In this case no new migration will
be applied, but the applied state of the squashed migration must be
maintained.
"""
applied = self.recorder.applied_migrations()
for key, migration in self.loader.replacements.items():
all_applied = all(m in applied for m in migration.replaces)
if all_applied and key not in applied:
self.recorder.record_applied(*key) | [
"def",
"check_replacements",
"(",
"self",
")",
":",
"applied",
"=",
"self",
".",
"recorder",
".",
"applied_migrations",
"(",
")",
"for",
"key",
",",
"migration",
"in",
"self",
".",
"loader",
".",
"replacements",
".",
"items",
"(",
")",
":",
"all_applied",
"=",
"all",
"(",
"m",
"in",
"applied",
"for",
"m",
"in",
"migration",
".",
"replaces",
")",
"if",
"all_applied",
"and",
"key",
"not",
"in",
"applied",
":",
"self",
".",
"recorder",
".",
"record_applied",
"(",
"*",
"key",
")"
] | [
263,
4
] | [
278,
50
] | python | en | ['en', 'error', 'th'] | False |
MigrationExecutor.detect_soft_applied | (self, project_state, migration) |
Test whether a migration has been implicitly applied - that the
tables or columns it would create exist. This is intended only for use
on initial migrations (as it only looks for CreateModel and AddField).
|
Test whether a migration has been implicitly applied - that the
tables or columns it would create exist. This is intended only for use
on initial migrations (as it only looks for CreateModel and AddField).
| def detect_soft_applied(self, project_state, migration):
"""
Test whether a migration has been implicitly applied - that the
tables or columns it would create exist. This is intended only for use
on initial migrations (as it only looks for CreateModel and AddField).
"""
def should_skip_detecting_model(migration, model):
"""
No need to detect tables for proxy models, unmanaged models, or
models that can't be migrated on the current database.
"""
return (
model._meta.proxy or not model._meta.managed or not
router.allow_migrate(
self.connection.alias, migration.app_label,
model_name=model._meta.model_name,
)
)
if migration.initial is None:
# Bail if the migration isn't the first one in its app
if any(app == migration.app_label for app, name in migration.dependencies):
return False, project_state
elif migration.initial is False:
# Bail if it's NOT an initial migration
return False, project_state
if project_state is None:
after_state = self.loader.project_state((migration.app_label, migration.name), at_end=True)
else:
after_state = migration.mutate_state(project_state)
apps = after_state.apps
found_create_model_migration = False
found_add_field_migration = False
fold_identifier_case = self.connection.features.ignores_table_name_case
with self.connection.cursor() as cursor:
existing_table_names = set(self.connection.introspection.table_names(cursor))
if fold_identifier_case:
existing_table_names = {name.casefold() for name in existing_table_names}
# Make sure all create model and add field operations are done
for operation in migration.operations:
if isinstance(operation, migrations.CreateModel):
model = apps.get_model(migration.app_label, operation.name)
if model._meta.swapped:
# We have to fetch the model to test with from the
# main app cache, as it's not a direct dependency.
model = global_apps.get_model(model._meta.swapped)
if should_skip_detecting_model(migration, model):
continue
db_table = model._meta.db_table
if fold_identifier_case:
db_table = db_table.casefold()
if db_table not in existing_table_names:
return False, project_state
found_create_model_migration = True
elif isinstance(operation, migrations.AddField):
model = apps.get_model(migration.app_label, operation.model_name)
if model._meta.swapped:
# We have to fetch the model to test with from the
# main app cache, as it's not a direct dependency.
model = global_apps.get_model(model._meta.swapped)
if should_skip_detecting_model(migration, model):
continue
table = model._meta.db_table
field = model._meta.get_field(operation.name)
# Handle implicit many-to-many tables created by AddField.
if field.many_to_many:
through_db_table = field.remote_field.through._meta.db_table
if fold_identifier_case:
through_db_table = through_db_table.casefold()
if through_db_table not in existing_table_names:
return False, project_state
else:
found_add_field_migration = True
continue
with self.connection.cursor() as cursor:
columns = self.connection.introspection.get_table_description(cursor, table)
for column in columns:
field_column = field.column
column_name = column.name
if fold_identifier_case:
column_name = column_name.casefold()
field_column = field_column.casefold()
if column_name == field_column:
found_add_field_migration = True
break
else:
return False, project_state
# If we get this far and we found at least one CreateModel or AddField migration,
# the migration is considered implicitly applied.
return (found_create_model_migration or found_add_field_migration), after_state | [
"def",
"detect_soft_applied",
"(",
"self",
",",
"project_state",
",",
"migration",
")",
":",
"def",
"should_skip_detecting_model",
"(",
"migration",
",",
"model",
")",
":",
"\"\"\"\n No need to detect tables for proxy models, unmanaged models, or\n models that can't be migrated on the current database.\n \"\"\"",
"return",
"(",
"model",
".",
"_meta",
".",
"proxy",
"or",
"not",
"model",
".",
"_meta",
".",
"managed",
"or",
"not",
"router",
".",
"allow_migrate",
"(",
"self",
".",
"connection",
".",
"alias",
",",
"migration",
".",
"app_label",
",",
"model_name",
"=",
"model",
".",
"_meta",
".",
"model_name",
",",
")",
")",
"if",
"migration",
".",
"initial",
"is",
"None",
":",
"# Bail if the migration isn't the first one in its app",
"if",
"any",
"(",
"app",
"==",
"migration",
".",
"app_label",
"for",
"app",
",",
"name",
"in",
"migration",
".",
"dependencies",
")",
":",
"return",
"False",
",",
"project_state",
"elif",
"migration",
".",
"initial",
"is",
"False",
":",
"# Bail if it's NOT an initial migration",
"return",
"False",
",",
"project_state",
"if",
"project_state",
"is",
"None",
":",
"after_state",
"=",
"self",
".",
"loader",
".",
"project_state",
"(",
"(",
"migration",
".",
"app_label",
",",
"migration",
".",
"name",
")",
",",
"at_end",
"=",
"True",
")",
"else",
":",
"after_state",
"=",
"migration",
".",
"mutate_state",
"(",
"project_state",
")",
"apps",
"=",
"after_state",
".",
"apps",
"found_create_model_migration",
"=",
"False",
"found_add_field_migration",
"=",
"False",
"fold_identifier_case",
"=",
"self",
".",
"connection",
".",
"features",
".",
"ignores_table_name_case",
"with",
"self",
".",
"connection",
".",
"cursor",
"(",
")",
"as",
"cursor",
":",
"existing_table_names",
"=",
"set",
"(",
"self",
".",
"connection",
".",
"introspection",
".",
"table_names",
"(",
"cursor",
")",
")",
"if",
"fold_identifier_case",
":",
"existing_table_names",
"=",
"{",
"name",
".",
"casefold",
"(",
")",
"for",
"name",
"in",
"existing_table_names",
"}",
"# Make sure all create model and add field operations are done",
"for",
"operation",
"in",
"migration",
".",
"operations",
":",
"if",
"isinstance",
"(",
"operation",
",",
"migrations",
".",
"CreateModel",
")",
":",
"model",
"=",
"apps",
".",
"get_model",
"(",
"migration",
".",
"app_label",
",",
"operation",
".",
"name",
")",
"if",
"model",
".",
"_meta",
".",
"swapped",
":",
"# We have to fetch the model to test with from the",
"# main app cache, as it's not a direct dependency.",
"model",
"=",
"global_apps",
".",
"get_model",
"(",
"model",
".",
"_meta",
".",
"swapped",
")",
"if",
"should_skip_detecting_model",
"(",
"migration",
",",
"model",
")",
":",
"continue",
"db_table",
"=",
"model",
".",
"_meta",
".",
"db_table",
"if",
"fold_identifier_case",
":",
"db_table",
"=",
"db_table",
".",
"casefold",
"(",
")",
"if",
"db_table",
"not",
"in",
"existing_table_names",
":",
"return",
"False",
",",
"project_state",
"found_create_model_migration",
"=",
"True",
"elif",
"isinstance",
"(",
"operation",
",",
"migrations",
".",
"AddField",
")",
":",
"model",
"=",
"apps",
".",
"get_model",
"(",
"migration",
".",
"app_label",
",",
"operation",
".",
"model_name",
")",
"if",
"model",
".",
"_meta",
".",
"swapped",
":",
"# We have to fetch the model to test with from the",
"# main app cache, as it's not a direct dependency.",
"model",
"=",
"global_apps",
".",
"get_model",
"(",
"model",
".",
"_meta",
".",
"swapped",
")",
"if",
"should_skip_detecting_model",
"(",
"migration",
",",
"model",
")",
":",
"continue",
"table",
"=",
"model",
".",
"_meta",
".",
"db_table",
"field",
"=",
"model",
".",
"_meta",
".",
"get_field",
"(",
"operation",
".",
"name",
")",
"# Handle implicit many-to-many tables created by AddField.",
"if",
"field",
".",
"many_to_many",
":",
"through_db_table",
"=",
"field",
".",
"remote_field",
".",
"through",
".",
"_meta",
".",
"db_table",
"if",
"fold_identifier_case",
":",
"through_db_table",
"=",
"through_db_table",
".",
"casefold",
"(",
")",
"if",
"through_db_table",
"not",
"in",
"existing_table_names",
":",
"return",
"False",
",",
"project_state",
"else",
":",
"found_add_field_migration",
"=",
"True",
"continue",
"with",
"self",
".",
"connection",
".",
"cursor",
"(",
")",
"as",
"cursor",
":",
"columns",
"=",
"self",
".",
"connection",
".",
"introspection",
".",
"get_table_description",
"(",
"cursor",
",",
"table",
")",
"for",
"column",
"in",
"columns",
":",
"field_column",
"=",
"field",
".",
"column",
"column_name",
"=",
"column",
".",
"name",
"if",
"fold_identifier_case",
":",
"column_name",
"=",
"column_name",
".",
"casefold",
"(",
")",
"field_column",
"=",
"field_column",
".",
"casefold",
"(",
")",
"if",
"column_name",
"==",
"field_column",
":",
"found_add_field_migration",
"=",
"True",
"break",
"else",
":",
"return",
"False",
",",
"project_state",
"# If we get this far and we found at least one CreateModel or AddField migration,",
"# the migration is considered implicitly applied.",
"return",
"(",
"found_create_model_migration",
"or",
"found_add_field_migration",
")",
",",
"after_state"
] | [
280,
4
] | [
372,
87
] | python | en | ['en', 'error', 'th'] | False |
SpatialiteGeometryColumns.table_name_col | (cls) |
Return the name of the metadata column used to store the feature table
name.
|
Return the name of the metadata column used to store the feature table
name.
| def table_name_col(cls):
"""
Return the name of the metadata column used to store the feature table
name.
"""
return 'f_table_name' | [
"def",
"table_name_col",
"(",
"cls",
")",
":",
"return",
"'f_table_name'"
] | [
33,
4
] | [
38,
29
] | python | en | ['en', 'error', 'th'] | False |
SpatialiteGeometryColumns.geom_col_name | (cls) |
Return the name of the metadata column used to store the feature
geometry column.
|
Return the name of the metadata column used to store the feature
geometry column.
| def geom_col_name(cls):
"""
Return the name of the metadata column used to store the feature
geometry column.
"""
return 'f_geometry_column' | [
"def",
"geom_col_name",
"(",
"cls",
")",
":",
"return",
"'f_geometry_column'"
] | [
41,
4
] | [
46,
34
] | python | en | ['en', 'error', 'th'] | False |
install_lib.get_exclusions | (self) |
Return a collections.Sized collections.Container of paths to be
excluded for single_version_externally_managed installations.
|
Return a collections.Sized collections.Container of paths to be
excluded for single_version_externally_managed installations.
| def get_exclusions(self):
"""
Return a collections.Sized collections.Container of paths to be
excluded for single_version_externally_managed installations.
"""
all_packages = (
pkg
for ns_pkg in self._get_SVEM_NSPs()
for pkg in self._all_packages(ns_pkg)
)
excl_specs = product(all_packages, self._gen_exclusion_paths())
return set(starmap(self._exclude_pkg_path, excl_specs)) | [
"def",
"get_exclusions",
"(",
"self",
")",
":",
"all_packages",
"=",
"(",
"pkg",
"for",
"ns_pkg",
"in",
"self",
".",
"_get_SVEM_NSPs",
"(",
")",
"for",
"pkg",
"in",
"self",
".",
"_all_packages",
"(",
"ns_pkg",
")",
")",
"excl_specs",
"=",
"product",
"(",
"all_packages",
",",
"self",
".",
"_gen_exclusion_paths",
"(",
")",
")",
"return",
"set",
"(",
"starmap",
"(",
"self",
".",
"_exclude_pkg_path",
",",
"excl_specs",
")",
")"
] | [
29,
4
] | [
41,
63
] | python | en | ['en', 'error', 'th'] | False |
install_lib._exclude_pkg_path | (self, pkg, exclusion_path) |
Given a package name and exclusion path within that package,
compute the full exclusion path.
|
Given a package name and exclusion path within that package,
compute the full exclusion path.
| def _exclude_pkg_path(self, pkg, exclusion_path):
"""
Given a package name and exclusion path within that package,
compute the full exclusion path.
"""
parts = pkg.split('.') + [exclusion_path]
return os.path.join(self.install_dir, *parts) | [
"def",
"_exclude_pkg_path",
"(",
"self",
",",
"pkg",
",",
"exclusion_path",
")",
":",
"parts",
"=",
"pkg",
".",
"split",
"(",
"'.'",
")",
"+",
"[",
"exclusion_path",
"]",
"return",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"install_dir",
",",
"*",
"parts",
")"
] | [
43,
4
] | [
49,
53
] | python | en | ['en', 'error', 'th'] | False |
install_lib._all_packages | (pkg_name) |
>>> list(install_lib._all_packages('foo.bar.baz'))
['foo.bar.baz', 'foo.bar', 'foo']
|
>>> list(install_lib._all_packages('foo.bar.baz'))
['foo.bar.baz', 'foo.bar', 'foo']
| def _all_packages(pkg_name):
"""
>>> list(install_lib._all_packages('foo.bar.baz'))
['foo.bar.baz', 'foo.bar', 'foo']
"""
while pkg_name:
yield pkg_name
pkg_name, sep, child = pkg_name.rpartition('.') | [
"def",
"_all_packages",
"(",
"pkg_name",
")",
":",
"while",
"pkg_name",
":",
"yield",
"pkg_name",
"pkg_name",
",",
"sep",
",",
"child",
"=",
"pkg_name",
".",
"rpartition",
"(",
"'.'",
")"
] | [
52,
4
] | [
59,
59
] | python | en | ['en', 'error', 'th'] | False |
install_lib._get_SVEM_NSPs | (self) |
Get namespace packages (list) but only for
single_version_externally_managed installations and empty otherwise.
|
Get namespace packages (list) but only for
single_version_externally_managed installations and empty otherwise.
| def _get_SVEM_NSPs(self):
"""
Get namespace packages (list) but only for
single_version_externally_managed installations and empty otherwise.
"""
# TODO: is it necessary to short-circuit here? i.e. what's the cost
# if get_finalized_command is called even when namespace_packages is
# False?
if not self.distribution.namespace_packages:
return []
install_cmd = self.get_finalized_command('install')
svem = install_cmd.single_version_externally_managed
return self.distribution.namespace_packages if svem else [] | [
"def",
"_get_SVEM_NSPs",
"(",
"self",
")",
":",
"# TODO: is it necessary to short-circuit here? i.e. what's the cost",
"# if get_finalized_command is called even when namespace_packages is",
"# False?",
"if",
"not",
"self",
".",
"distribution",
".",
"namespace_packages",
":",
"return",
"[",
"]",
"install_cmd",
"=",
"self",
".",
"get_finalized_command",
"(",
"'install'",
")",
"svem",
"=",
"install_cmd",
".",
"single_version_externally_managed",
"return",
"self",
".",
"distribution",
".",
"namespace_packages",
"if",
"svem",
"else",
"[",
"]"
] | [
61,
4
] | [
75,
67
] | python | en | ['en', 'error', 'th'] | False |
install_lib._gen_exclusion_paths | () |
Generate file paths to be excluded for namespace packages (bytecode
cache files).
|
Generate file paths to be excluded for namespace packages (bytecode
cache files).
| def _gen_exclusion_paths():
"""
Generate file paths to be excluded for namespace packages (bytecode
cache files).
"""
# always exclude the package module itself
yield '__init__.py'
yield '__init__.pyc'
yield '__init__.pyo'
if not hasattr(imp, 'get_tag'):
return
base = os.path.join('__pycache__', '__init__.' + imp.get_tag())
yield base + '.pyc'
yield base + '.pyo'
yield base + '.opt-1.pyc'
yield base + '.opt-2.pyc' | [
"def",
"_gen_exclusion_paths",
"(",
")",
":",
"# always exclude the package module itself",
"yield",
"'__init__.py'",
"yield",
"'__init__.pyc'",
"yield",
"'__init__.pyo'",
"if",
"not",
"hasattr",
"(",
"imp",
",",
"'get_tag'",
")",
":",
"return",
"base",
"=",
"os",
".",
"path",
".",
"join",
"(",
"'__pycache__'",
",",
"'__init__.'",
"+",
"imp",
".",
"get_tag",
"(",
")",
")",
"yield",
"base",
"+",
"'.pyc'",
"yield",
"base",
"+",
"'.pyo'",
"yield",
"base",
"+",
"'.opt-1.pyc'",
"yield",
"base",
"+",
"'.opt-2.pyc'"
] | [
78,
4
] | [
96,
33
] | python | en | ['en', 'error', 'th'] | False |
get_image_dimensions | (file_or_path, close=False) |
Return the (width, height) of an image, given an open file or a path. Set
'close' to True to close the file at the end if it is initially in an open
state.
|
Return the (width, height) of an image, given an open file or a path. Set
'close' to True to close the file at the end if it is initially in an open
state.
| def get_image_dimensions(file_or_path, close=False):
"""
Return the (width, height) of an image, given an open file or a path. Set
'close' to True to close the file at the end if it is initially in an open
state.
"""
from PIL import ImageFile as PillowImageFile
p = PillowImageFile.Parser()
if hasattr(file_or_path, 'read'):
file = file_or_path
file_pos = file.tell()
file.seek(0)
else:
file = open(file_or_path, 'rb')
close = True
try:
# Most of the time Pillow only needs a small chunk to parse the image
# and get the dimensions, but with some TIFF files Pillow needs to
# parse the whole file.
chunk_size = 1024
while 1:
data = file.read(chunk_size)
if not data:
break
try:
p.feed(data)
except zlib.error as e:
# ignore zlib complaining on truncated stream, just feed more
# data to parser (ticket #19457).
if e.args[0].startswith("Error -5"):
pass
else:
raise
except struct.error:
# Ignore PIL failing on a too short buffer when reads return
# less bytes than expected. Skip and feed more data to the
# parser (ticket #24544).
pass
except RuntimeError:
# e.g. "RuntimeError: could not create decoder object" for
# WebP files. A different chunk_size may work.
pass
if p.image:
return p.image.size
chunk_size *= 2
return (None, None)
finally:
if close:
file.close()
else:
file.seek(file_pos) | [
"def",
"get_image_dimensions",
"(",
"file_or_path",
",",
"close",
"=",
"False",
")",
":",
"from",
"PIL",
"import",
"ImageFile",
"as",
"PillowImageFile",
"p",
"=",
"PillowImageFile",
".",
"Parser",
"(",
")",
"if",
"hasattr",
"(",
"file_or_path",
",",
"'read'",
")",
":",
"file",
"=",
"file_or_path",
"file_pos",
"=",
"file",
".",
"tell",
"(",
")",
"file",
".",
"seek",
"(",
"0",
")",
"else",
":",
"file",
"=",
"open",
"(",
"file_or_path",
",",
"'rb'",
")",
"close",
"=",
"True",
"try",
":",
"# Most of the time Pillow only needs a small chunk to parse the image",
"# and get the dimensions, but with some TIFF files Pillow needs to",
"# parse the whole file.",
"chunk_size",
"=",
"1024",
"while",
"1",
":",
"data",
"=",
"file",
".",
"read",
"(",
"chunk_size",
")",
"if",
"not",
"data",
":",
"break",
"try",
":",
"p",
".",
"feed",
"(",
"data",
")",
"except",
"zlib",
".",
"error",
"as",
"e",
":",
"# ignore zlib complaining on truncated stream, just feed more",
"# data to parser (ticket #19457).",
"if",
"e",
".",
"args",
"[",
"0",
"]",
".",
"startswith",
"(",
"\"Error -5\"",
")",
":",
"pass",
"else",
":",
"raise",
"except",
"struct",
".",
"error",
":",
"# Ignore PIL failing on a too short buffer when reads return",
"# less bytes than expected. Skip and feed more data to the",
"# parser (ticket #24544).",
"pass",
"except",
"RuntimeError",
":",
"# e.g. \"RuntimeError: could not create decoder object\" for",
"# WebP files. A different chunk_size may work.",
"pass",
"if",
"p",
".",
"image",
":",
"return",
"p",
".",
"image",
".",
"size",
"chunk_size",
"*=",
"2",
"return",
"(",
"None",
",",
"None",
")",
"finally",
":",
"if",
"close",
":",
"file",
".",
"close",
"(",
")",
"else",
":",
"file",
".",
"seek",
"(",
"file_pos",
")"
] | [
32,
0
] | [
83,
31
] | python | en | ['en', 'error', 'th'] | False |
log_likelihood | (cl_obs, cosmo, wigner_mat, cov_mat, n_cov, n_of_zs, l_max=1000, bin_size=20) |
Calculates the (unnormalized) log-likelihood given a set observation as described in the paper.
|
Calculates the (unnormalized) log-likelihood given a set observation as described in the paper.
| def log_likelihood(cl_obs, cosmo, wigner_mat, cov_mat, n_cov, n_of_zs, l_max=1000, bin_size=20):
"""
Calculates the (unnormalized) log-likelihood given a set observation as described in the paper.
"""
# check if l_max and bin_size are consistent
if l_max%bin_size != 0:
raise ValueError(f"Incompatible choice of l_max {l_max} and bin_size {bin_size}! The bin_size "
f"has to divide the l_max without remainder.")
# We start by getting the spectra
specs = data.gen_ccl_spectra(cosmo, n_of_zs, l_max=l_max+1)
# we apply the wigner matrix and bin, note that l=0 is always ignored
specs = [np.mean((wigner_mat.dot(cl[:l_max+1]))[1:].reshape((20, -1)), axis=1) for cl in specs]
# difference to obs
diff = np.concatenate(specs) - cl_obs
# Get xS^-1x
q = diff.dot(np.linalg.inv(cov_mat).dot(diff))
# log prob
loglikelihood = -0.5*n_cov*np.log(1.0 + q/(n_cov - 1))
return loglikelihood | [
"def",
"log_likelihood",
"(",
"cl_obs",
",",
"cosmo",
",",
"wigner_mat",
",",
"cov_mat",
",",
"n_cov",
",",
"n_of_zs",
",",
"l_max",
"=",
"1000",
",",
"bin_size",
"=",
"20",
")",
":",
"# check if l_max and bin_size are consistent",
"if",
"l_max",
"%",
"bin_size",
"!=",
"0",
":",
"raise",
"ValueError",
"(",
"f\"Incompatible choice of l_max {l_max} and bin_size {bin_size}! The bin_size \"",
"f\"has to divide the l_max without remainder.\"",
")",
"# We start by getting the spectra",
"specs",
"=",
"data",
".",
"gen_ccl_spectra",
"(",
"cosmo",
",",
"n_of_zs",
",",
"l_max",
"=",
"l_max",
"+",
"1",
")",
"# we apply the wigner matrix and bin, note that l=0 is always ignored",
"specs",
"=",
"[",
"np",
".",
"mean",
"(",
"(",
"wigner_mat",
".",
"dot",
"(",
"cl",
"[",
":",
"l_max",
"+",
"1",
"]",
")",
")",
"[",
"1",
":",
"]",
".",
"reshape",
"(",
"(",
"20",
",",
"-",
"1",
")",
")",
",",
"axis",
"=",
"1",
")",
"for",
"cl",
"in",
"specs",
"]",
"# difference to obs",
"diff",
"=",
"np",
".",
"concatenate",
"(",
"specs",
")",
"-",
"cl_obs",
"# Get xS^-1x",
"q",
"=",
"diff",
".",
"dot",
"(",
"np",
".",
"linalg",
".",
"inv",
"(",
"cov_mat",
")",
".",
"dot",
"(",
"diff",
")",
")",
"# log prob",
"loglikelihood",
"=",
"-",
"0.5",
"*",
"n_cov",
"*",
"np",
".",
"log",
"(",
"1.0",
"+",
"q",
"/",
"(",
"n_cov",
"-",
"1",
")",
")",
"return",
"loglikelihood"
] | [
3,
0
] | [
27,
24
] | python | en | ['en', 'error', 'th'] | False |
deprecated | (
reason: str,
replacement: Optional[str],
gone_in: Optional[str],
issue: Optional[int] = None,
) | Helper to deprecate existing functionality.
reason:
Textual reason shown to the user about why this functionality has
been deprecated.
replacement:
Textual suggestion shown to the user about what alternative
functionality they can use.
gone_in:
The version of pip does this functionality should get removed in.
Raises errors if pip's current version is greater than or equal to
this.
issue:
Issue number on the tracker that would serve as a useful place for
users to find related discussion and provide feedback.
Always pass replacement, gone_in and issue as keyword arguments for clarity
at the call site.
| Helper to deprecate existing functionality. | def deprecated(
reason: str,
replacement: Optional[str],
gone_in: Optional[str],
issue: Optional[int] = None,
) -> None:
"""Helper to deprecate existing functionality.
reason:
Textual reason shown to the user about why this functionality has
been deprecated.
replacement:
Textual suggestion shown to the user about what alternative
functionality they can use.
gone_in:
The version of pip does this functionality should get removed in.
Raises errors if pip's current version is greater than or equal to
this.
issue:
Issue number on the tracker that would serve as a useful place for
users to find related discussion and provide feedback.
Always pass replacement, gone_in and issue as keyword arguments for clarity
at the call site.
"""
# Construct a nice message.
# This is eagerly formatted as we want it to get logged as if someone
# typed this entire message out.
sentences = [
(reason, DEPRECATION_MSG_PREFIX + "{}"),
(gone_in, "pip {} will remove support for this functionality."),
(replacement, "A possible replacement is {}."),
(
issue,
(
"You can find discussion regarding this at "
"https://github.com/pypa/pip/issues/{}."
),
),
]
message = " ".join(
template.format(val) for val, template in sentences if val is not None
)
# Raise as an error if it has to be removed.
if gone_in is not None and parse(current_version) >= parse(gone_in):
raise PipDeprecationWarning(message)
warnings.warn(message, category=PipDeprecationWarning, stacklevel=2) | [
"def",
"deprecated",
"(",
"reason",
":",
"str",
",",
"replacement",
":",
"Optional",
"[",
"str",
"]",
",",
"gone_in",
":",
"Optional",
"[",
"str",
"]",
",",
"issue",
":",
"Optional",
"[",
"int",
"]",
"=",
"None",
",",
")",
"->",
"None",
":",
"# Construct a nice message.",
"# This is eagerly formatted as we want it to get logged as if someone",
"# typed this entire message out.",
"sentences",
"=",
"[",
"(",
"reason",
",",
"DEPRECATION_MSG_PREFIX",
"+",
"\"{}\"",
")",
",",
"(",
"gone_in",
",",
"\"pip {} will remove support for this functionality.\"",
")",
",",
"(",
"replacement",
",",
"\"A possible replacement is {}.\"",
")",
",",
"(",
"issue",
",",
"(",
"\"You can find discussion regarding this at \"",
"\"https://github.com/pypa/pip/issues/{}.\"",
")",
",",
")",
",",
"]",
"message",
"=",
"\" \"",
".",
"join",
"(",
"template",
".",
"format",
"(",
"val",
")",
"for",
"val",
",",
"template",
"in",
"sentences",
"if",
"val",
"is",
"not",
"None",
")",
"# Raise as an error if it has to be removed.",
"if",
"gone_in",
"is",
"not",
"None",
"and",
"parse",
"(",
"current_version",
")",
">=",
"parse",
"(",
"gone_in",
")",
":",
"raise",
"PipDeprecationWarning",
"(",
"message",
")",
"warnings",
".",
"warn",
"(",
"message",
",",
"category",
"=",
"PipDeprecationWarning",
",",
"stacklevel",
"=",
"2",
")"
] | [
54,
0
] | [
103,
72
] | python | en | ['it', 'en', 'en'] | True |
BlueprintSetupState.add_url_rule | (self, rule, endpoint=None, view_func=None, **options) | A helper method to register a rule (and optionally a view function)
to the application. The endpoint is automatically prefixed with the
blueprint's name.
| A helper method to register a rule (and optionally a view function)
to the application. The endpoint is automatically prefixed with the
blueprint's name.
| def add_url_rule(self, rule, endpoint=None, view_func=None, **options):
"""A helper method to register a rule (and optionally a view function)
to the application. The endpoint is automatically prefixed with the
blueprint's name.
"""
if self.url_prefix:
rule = self.url_prefix + rule
options.setdefault('subdomain', self.subdomain)
if endpoint is None:
endpoint = _endpoint_from_view_func(view_func)
defaults = self.url_defaults
if 'defaults' in options:
defaults = dict(defaults, **options.pop('defaults'))
self.app.add_url_rule(rule, '%s.%s' % (self.blueprint.name, endpoint),
view_func, defaults=defaults, **options) | [
"def",
"add_url_rule",
"(",
"self",
",",
"rule",
",",
"endpoint",
"=",
"None",
",",
"view_func",
"=",
"None",
",",
"*",
"*",
"options",
")",
":",
"if",
"self",
".",
"url_prefix",
":",
"rule",
"=",
"self",
".",
"url_prefix",
"+",
"rule",
"options",
".",
"setdefault",
"(",
"'subdomain'",
",",
"self",
".",
"subdomain",
")",
"if",
"endpoint",
"is",
"None",
":",
"endpoint",
"=",
"_endpoint_from_view_func",
"(",
"view_func",
")",
"defaults",
"=",
"self",
".",
"url_defaults",
"if",
"'defaults'",
"in",
"options",
":",
"defaults",
"=",
"dict",
"(",
"defaults",
",",
"*",
"*",
"options",
".",
"pop",
"(",
"'defaults'",
")",
")",
"self",
".",
"app",
".",
"add_url_rule",
"(",
"rule",
",",
"'%s.%s'",
"%",
"(",
"self",
".",
"blueprint",
".",
"name",
",",
"endpoint",
")",
",",
"view_func",
",",
"defaults",
"=",
"defaults",
",",
"*",
"*",
"options",
")"
] | [
61,
4
] | [
75,
70
] | python | en | ['en', 'en', 'en'] | True |
Blueprint.record | (self, func) | Registers a function that is called when the blueprint is
registered on the application. This function is called with the
state as argument as returned by the :meth:`make_setup_state`
method.
| Registers a function that is called when the blueprint is
registered on the application. This function is called with the
state as argument as returned by the :meth:`make_setup_state`
method.
| def record(self, func):
"""Registers a function that is called when the blueprint is
registered on the application. This function is called with the
state as argument as returned by the :meth:`make_setup_state`
method.
"""
if self._got_registered_once and self.warn_on_modifications:
from warnings import warn
warn(Warning('The blueprint was already registered once '
'but is getting modified now. These changes '
'will not show up.'))
self.deferred_functions.append(func) | [
"def",
"record",
"(",
"self",
",",
"func",
")",
":",
"if",
"self",
".",
"_got_registered_once",
"and",
"self",
".",
"warn_on_modifications",
":",
"from",
"warnings",
"import",
"warn",
"warn",
"(",
"Warning",
"(",
"'The blueprint was already registered once '",
"'but is getting modified now. These changes '",
"'will not show up.'",
")",
")",
"self",
".",
"deferred_functions",
".",
"append",
"(",
"func",
")"
] | [
107,
4
] | [
118,
44
] | python | en | ['en', 'en', 'en'] | True |
Blueprint.record_once | (self, func) | Works like :meth:`record` but wraps the function in another
function that will ensure the function is only called once. If the
blueprint is registered a second time on the application, the
function passed is not called.
| Works like :meth:`record` but wraps the function in another
function that will ensure the function is only called once. If the
blueprint is registered a second time on the application, the
function passed is not called.
| def record_once(self, func):
"""Works like :meth:`record` but wraps the function in another
function that will ensure the function is only called once. If the
blueprint is registered a second time on the application, the
function passed is not called.
"""
def wrapper(state):
if state.first_registration:
func(state)
return self.record(update_wrapper(wrapper, func)) | [
"def",
"record_once",
"(",
"self",
",",
"func",
")",
":",
"def",
"wrapper",
"(",
"state",
")",
":",
"if",
"state",
".",
"first_registration",
":",
"func",
"(",
"state",
")",
"return",
"self",
".",
"record",
"(",
"update_wrapper",
"(",
"wrapper",
",",
"func",
")",
")"
] | [
120,
4
] | [
129,
57
] | python | en | ['en', 'en', 'en'] | True |
Blueprint.make_setup_state | (self, app, options, first_registration=False) | Creates an instance of :meth:`~flask.blueprints.BlueprintSetupState`
object that is later passed to the register callback functions.
Subclasses can override this to return a subclass of the setup state.
| Creates an instance of :meth:`~flask.blueprints.BlueprintSetupState`
object that is later passed to the register callback functions.
Subclasses can override this to return a subclass of the setup state.
| def make_setup_state(self, app, options, first_registration=False):
"""Creates an instance of :meth:`~flask.blueprints.BlueprintSetupState`
object that is later passed to the register callback functions.
Subclasses can override this to return a subclass of the setup state.
"""
return BlueprintSetupState(self, app, options, first_registration) | [
"def",
"make_setup_state",
"(",
"self",
",",
"app",
",",
"options",
",",
"first_registration",
"=",
"False",
")",
":",
"return",
"BlueprintSetupState",
"(",
"self",
",",
"app",
",",
"options",
",",
"first_registration",
")"
] | [
131,
4
] | [
136,
74
] | python | en | ['en', 'lb', 'en'] | True |
Blueprint.register | (self, app, options, first_registration=False) | Called by :meth:`Flask.register_blueprint` to register a blueprint
on the application. This can be overridden to customize the register
behavior. Keyword arguments from
:func:`~flask.Flask.register_blueprint` are directly forwarded to this
method in the `options` dictionary.
| Called by :meth:`Flask.register_blueprint` to register a blueprint
on the application. This can be overridden to customize the register
behavior. Keyword arguments from
:func:`~flask.Flask.register_blueprint` are directly forwarded to this
method in the `options` dictionary.
| def register(self, app, options, first_registration=False):
"""Called by :meth:`Flask.register_blueprint` to register a blueprint
on the application. This can be overridden to customize the register
behavior. Keyword arguments from
:func:`~flask.Flask.register_blueprint` are directly forwarded to this
method in the `options` dictionary.
"""
self._got_registered_once = True
state = self.make_setup_state(app, options, first_registration)
if self.has_static_folder:
state.add_url_rule(self.static_url_path + '/<path:filename>',
view_func=self.send_static_file,
endpoint='static')
for deferred in self.deferred_functions:
deferred(state) | [
"def",
"register",
"(",
"self",
",",
"app",
",",
"options",
",",
"first_registration",
"=",
"False",
")",
":",
"self",
".",
"_got_registered_once",
"=",
"True",
"state",
"=",
"self",
".",
"make_setup_state",
"(",
"app",
",",
"options",
",",
"first_registration",
")",
"if",
"self",
".",
"has_static_folder",
":",
"state",
".",
"add_url_rule",
"(",
"self",
".",
"static_url_path",
"+",
"'/<path:filename>'",
",",
"view_func",
"=",
"self",
".",
"send_static_file",
",",
"endpoint",
"=",
"'static'",
")",
"for",
"deferred",
"in",
"self",
".",
"deferred_functions",
":",
"deferred",
"(",
"state",
")"
] | [
138,
4
] | [
153,
27
] | python | en | ['en', 'en', 'en'] | True |
Blueprint.route | (self, rule, **options) | Like :meth:`Flask.route` but for a blueprint. The endpoint for the
:func:`url_for` function is prefixed with the name of the blueprint.
| Like :meth:`Flask.route` but for a blueprint. The endpoint for the
:func:`url_for` function is prefixed with the name of the blueprint.
| def route(self, rule, **options):
"""Like :meth:`Flask.route` but for a blueprint. The endpoint for the
:func:`url_for` function is prefixed with the name of the blueprint.
"""
def decorator(f):
endpoint = options.pop("endpoint", f.__name__)
self.add_url_rule(rule, endpoint, f, **options)
return f
return decorator | [
"def",
"route",
"(",
"self",
",",
"rule",
",",
"*",
"*",
"options",
")",
":",
"def",
"decorator",
"(",
"f",
")",
":",
"endpoint",
"=",
"options",
".",
"pop",
"(",
"\"endpoint\"",
",",
"f",
".",
"__name__",
")",
"self",
".",
"add_url_rule",
"(",
"rule",
",",
"endpoint",
",",
"f",
",",
"*",
"*",
"options",
")",
"return",
"f",
"return",
"decorator"
] | [
155,
4
] | [
163,
24
] | python | en | ['en', 'en', 'en'] | True |
Blueprint.add_url_rule | (self, rule, endpoint=None, view_func=None, **options) | Like :meth:`Flask.add_url_rule` but for a blueprint. The endpoint for
the :func:`url_for` function is prefixed with the name of the blueprint.
| Like :meth:`Flask.add_url_rule` but for a blueprint. The endpoint for
the :func:`url_for` function is prefixed with the name of the blueprint.
| def add_url_rule(self, rule, endpoint=None, view_func=None, **options):
"""Like :meth:`Flask.add_url_rule` but for a blueprint. The endpoint for
the :func:`url_for` function is prefixed with the name of the blueprint.
"""
if endpoint:
assert '.' not in endpoint, "Blueprint endpoints should not contain dots"
self.record(lambda s:
s.add_url_rule(rule, endpoint, view_func, **options)) | [
"def",
"add_url_rule",
"(",
"self",
",",
"rule",
",",
"endpoint",
"=",
"None",
",",
"view_func",
"=",
"None",
",",
"*",
"*",
"options",
")",
":",
"if",
"endpoint",
":",
"assert",
"'.'",
"not",
"in",
"endpoint",
",",
"\"Blueprint endpoints should not contain dots\"",
"self",
".",
"record",
"(",
"lambda",
"s",
":",
"s",
".",
"add_url_rule",
"(",
"rule",
",",
"endpoint",
",",
"view_func",
",",
"*",
"*",
"options",
")",
")"
] | [
165,
4
] | [
172,
65
] | python | en | ['en', 'en', 'en'] | True |
Blueprint.endpoint | (self, endpoint) | Like :meth:`Flask.endpoint` but for a blueprint. This does not
prefix the endpoint with the blueprint name, this has to be done
explicitly by the user of this method. If the endpoint is prefixed
with a `.` it will be registered to the current blueprint, otherwise
it's an application independent endpoint.
| Like :meth:`Flask.endpoint` but for a blueprint. This does not
prefix the endpoint with the blueprint name, this has to be done
explicitly by the user of this method. If the endpoint is prefixed
with a `.` it will be registered to the current blueprint, otherwise
it's an application independent endpoint.
| def endpoint(self, endpoint):
"""Like :meth:`Flask.endpoint` but for a blueprint. This does not
prefix the endpoint with the blueprint name, this has to be done
explicitly by the user of this method. If the endpoint is prefixed
with a `.` it will be registered to the current blueprint, otherwise
it's an application independent endpoint.
"""
def decorator(f):
def register_endpoint(state):
state.app.view_functions[endpoint] = f
self.record_once(register_endpoint)
return f
return decorator | [
"def",
"endpoint",
"(",
"self",
",",
"endpoint",
")",
":",
"def",
"decorator",
"(",
"f",
")",
":",
"def",
"register_endpoint",
"(",
"state",
")",
":",
"state",
".",
"app",
".",
"view_functions",
"[",
"endpoint",
"]",
"=",
"f",
"self",
".",
"record_once",
"(",
"register_endpoint",
")",
"return",
"f",
"return",
"decorator"
] | [
174,
4
] | [
186,
24
] | python | en | ['en', 'en', 'en'] | True |
Blueprint.app_template_filter | (self, name=None) | Register a custom template filter, available application wide. Like
:meth:`Flask.template_filter` but for a blueprint.
:param name: the optional name of the filter, otherwise the
function name will be used.
| Register a custom template filter, available application wide. Like
:meth:`Flask.template_filter` but for a blueprint. | def app_template_filter(self, name=None):
"""Register a custom template filter, available application wide. Like
:meth:`Flask.template_filter` but for a blueprint.
:param name: the optional name of the filter, otherwise the
function name will be used.
"""
def decorator(f):
self.add_app_template_filter(f, name=name)
return f
return decorator | [
"def",
"app_template_filter",
"(",
"self",
",",
"name",
"=",
"None",
")",
":",
"def",
"decorator",
"(",
"f",
")",
":",
"self",
".",
"add_app_template_filter",
"(",
"f",
",",
"name",
"=",
"name",
")",
"return",
"f",
"return",
"decorator"
] | [
188,
4
] | [
198,
24
] | python | en | ['en', 'en', 'en'] | True |
Blueprint.add_app_template_filter | (self, f, name=None) | Register a custom template filter, available application wide. Like
:meth:`Flask.add_template_filter` but for a blueprint. Works exactly
like the :meth:`app_template_filter` decorator.
:param name: the optional name of the filter, otherwise the
function name will be used.
| Register a custom template filter, available application wide. Like
:meth:`Flask.add_template_filter` but for a blueprint. Works exactly
like the :meth:`app_template_filter` decorator. | def add_app_template_filter(self, f, name=None):
"""Register a custom template filter, available application wide. Like
:meth:`Flask.add_template_filter` but for a blueprint. Works exactly
like the :meth:`app_template_filter` decorator.
:param name: the optional name of the filter, otherwise the
function name will be used.
"""
def register_template(state):
state.app.jinja_env.filters[name or f.__name__] = f
self.record_once(register_template) | [
"def",
"add_app_template_filter",
"(",
"self",
",",
"f",
",",
"name",
"=",
"None",
")",
":",
"def",
"register_template",
"(",
"state",
")",
":",
"state",
".",
"app",
".",
"jinja_env",
".",
"filters",
"[",
"name",
"or",
"f",
".",
"__name__",
"]",
"=",
"f",
"self",
".",
"record_once",
"(",
"register_template",
")"
] | [
200,
4
] | [
210,
43
] | python | en | ['en', 'en', 'en'] | True |
Blueprint.app_template_test | (self, name=None) | Register a custom template test, available application wide. Like
:meth:`Flask.template_test` but for a blueprint.
.. versionadded:: 0.10
:param name: the optional name of the test, otherwise the
function name will be used.
| Register a custom template test, available application wide. Like
:meth:`Flask.template_test` but for a blueprint. | def app_template_test(self, name=None):
"""Register a custom template test, available application wide. Like
:meth:`Flask.template_test` but for a blueprint.
.. versionadded:: 0.10
:param name: the optional name of the test, otherwise the
function name will be used.
"""
def decorator(f):
self.add_app_template_test(f, name=name)
return f
return decorator | [
"def",
"app_template_test",
"(",
"self",
",",
"name",
"=",
"None",
")",
":",
"def",
"decorator",
"(",
"f",
")",
":",
"self",
".",
"add_app_template_test",
"(",
"f",
",",
"name",
"=",
"name",
")",
"return",
"f",
"return",
"decorator"
] | [
212,
4
] | [
224,
24
] | python | en | ['en', 'en', 'en'] | True |
Blueprint.add_app_template_test | (self, f, name=None) | Register a custom template test, available application wide. Like
:meth:`Flask.add_template_test` but for a blueprint. Works exactly
like the :meth:`app_template_test` decorator.
.. versionadded:: 0.10
:param name: the optional name of the test, otherwise the
function name will be used.
| Register a custom template test, available application wide. Like
:meth:`Flask.add_template_test` but for a blueprint. Works exactly
like the :meth:`app_template_test` decorator. | def add_app_template_test(self, f, name=None):
"""Register a custom template test, available application wide. Like
:meth:`Flask.add_template_test` but for a blueprint. Works exactly
like the :meth:`app_template_test` decorator.
.. versionadded:: 0.10
:param name: the optional name of the test, otherwise the
function name will be used.
"""
def register_template(state):
state.app.jinja_env.tests[name or f.__name__] = f
self.record_once(register_template) | [
"def",
"add_app_template_test",
"(",
"self",
",",
"f",
",",
"name",
"=",
"None",
")",
":",
"def",
"register_template",
"(",
"state",
")",
":",
"state",
".",
"app",
".",
"jinja_env",
".",
"tests",
"[",
"name",
"or",
"f",
".",
"__name__",
"]",
"=",
"f",
"self",
".",
"record_once",
"(",
"register_template",
")"
] | [
226,
4
] | [
238,
43
] | python | en | ['en', 'en', 'en'] | True |
Blueprint.app_template_global | (self, name=None) | Register a custom template global, available application wide. Like
:meth:`Flask.template_global` but for a blueprint.
.. versionadded:: 0.10
:param name: the optional name of the global, otherwise the
function name will be used.
| Register a custom template global, available application wide. Like
:meth:`Flask.template_global` but for a blueprint. | def app_template_global(self, name=None):
"""Register a custom template global, available application wide. Like
:meth:`Flask.template_global` but for a blueprint.
.. versionadded:: 0.10
:param name: the optional name of the global, otherwise the
function name will be used.
"""
def decorator(f):
self.add_app_template_global(f, name=name)
return f
return decorator | [
"def",
"app_template_global",
"(",
"self",
",",
"name",
"=",
"None",
")",
":",
"def",
"decorator",
"(",
"f",
")",
":",
"self",
".",
"add_app_template_global",
"(",
"f",
",",
"name",
"=",
"name",
")",
"return",
"f",
"return",
"decorator"
] | [
240,
4
] | [
252,
24
] | python | en | ['en', 'en', 'en'] | True |
Blueprint.add_app_template_global | (self, f, name=None) | Register a custom template global, available application wide. Like
:meth:`Flask.add_template_global` but for a blueprint. Works exactly
like the :meth:`app_template_global` decorator.
.. versionadded:: 0.10
:param name: the optional name of the global, otherwise the
function name will be used.
| Register a custom template global, available application wide. Like
:meth:`Flask.add_template_global` but for a blueprint. Works exactly
like the :meth:`app_template_global` decorator. | def add_app_template_global(self, f, name=None):
"""Register a custom template global, available application wide. Like
:meth:`Flask.add_template_global` but for a blueprint. Works exactly
like the :meth:`app_template_global` decorator.
.. versionadded:: 0.10
:param name: the optional name of the global, otherwise the
function name will be used.
"""
def register_template(state):
state.app.jinja_env.globals[name or f.__name__] = f
self.record_once(register_template) | [
"def",
"add_app_template_global",
"(",
"self",
",",
"f",
",",
"name",
"=",
"None",
")",
":",
"def",
"register_template",
"(",
"state",
")",
":",
"state",
".",
"app",
".",
"jinja_env",
".",
"globals",
"[",
"name",
"or",
"f",
".",
"__name__",
"]",
"=",
"f",
"self",
".",
"record_once",
"(",
"register_template",
")"
] | [
254,
4
] | [
266,
43
] | python | en | ['en', 'en', 'en'] | True |
Blueprint.before_request | (self, f) | Like :meth:`Flask.before_request` but for a blueprint. This function
is only executed before each request that is handled by a function of
that blueprint.
| Like :meth:`Flask.before_request` but for a blueprint. This function
is only executed before each request that is handled by a function of
that blueprint.
| def before_request(self, f):
"""Like :meth:`Flask.before_request` but for a blueprint. This function
is only executed before each request that is handled by a function of
that blueprint.
"""
self.record_once(lambda s: s.app.before_request_funcs
.setdefault(self.name, []).append(f))
return f | [
"def",
"before_request",
"(",
"self",
",",
"f",
")",
":",
"self",
".",
"record_once",
"(",
"lambda",
"s",
":",
"s",
".",
"app",
".",
"before_request_funcs",
".",
"setdefault",
"(",
"self",
".",
"name",
",",
"[",
"]",
")",
".",
"append",
"(",
"f",
")",
")",
"return",
"f"
] | [
268,
4
] | [
275,
16
] | python | en | ['en', 'en', 'en'] | True |
Blueprint.before_app_request | (self, f) | Like :meth:`Flask.before_request`. Such a function is executed
before each request, even if outside of a blueprint.
| Like :meth:`Flask.before_request`. Such a function is executed
before each request, even if outside of a blueprint.
| def before_app_request(self, f):
"""Like :meth:`Flask.before_request`. Such a function is executed
before each request, even if outside of a blueprint.
"""
self.record_once(lambda s: s.app.before_request_funcs
.setdefault(None, []).append(f))
return f | [
"def",
"before_app_request",
"(",
"self",
",",
"f",
")",
":",
"self",
".",
"record_once",
"(",
"lambda",
"s",
":",
"s",
".",
"app",
".",
"before_request_funcs",
".",
"setdefault",
"(",
"None",
",",
"[",
"]",
")",
".",
"append",
"(",
"f",
")",
")",
"return",
"f"
] | [
277,
4
] | [
283,
16
] | python | en | ['en', 'en', 'en'] | True |
Blueprint.before_app_first_request | (self, f) | Like :meth:`Flask.before_first_request`. Such a function is
executed before the first request to the application.
| Like :meth:`Flask.before_first_request`. Such a function is
executed before the first request to the application.
| def before_app_first_request(self, f):
"""Like :meth:`Flask.before_first_request`. Such a function is
executed before the first request to the application.
"""
self.record_once(lambda s: s.app.before_first_request_funcs.append(f))
return f | [
"def",
"before_app_first_request",
"(",
"self",
",",
"f",
")",
":",
"self",
".",
"record_once",
"(",
"lambda",
"s",
":",
"s",
".",
"app",
".",
"before_first_request_funcs",
".",
"append",
"(",
"f",
")",
")",
"return",
"f"
] | [
285,
4
] | [
290,
16
] | python | en | ['en', 'en', 'en'] | True |
Blueprint.after_request | (self, f) | Like :meth:`Flask.after_request` but for a blueprint. This function
is only executed after each request that is handled by a function of
that blueprint.
| Like :meth:`Flask.after_request` but for a blueprint. This function
is only executed after each request that is handled by a function of
that blueprint.
| def after_request(self, f):
"""Like :meth:`Flask.after_request` but for a blueprint. This function
is only executed after each request that is handled by a function of
that blueprint.
"""
self.record_once(lambda s: s.app.after_request_funcs
.setdefault(self.name, []).append(f))
return f | [
"def",
"after_request",
"(",
"self",
",",
"f",
")",
":",
"self",
".",
"record_once",
"(",
"lambda",
"s",
":",
"s",
".",
"app",
".",
"after_request_funcs",
".",
"setdefault",
"(",
"self",
".",
"name",
",",
"[",
"]",
")",
".",
"append",
"(",
"f",
")",
")",
"return",
"f"
] | [
292,
4
] | [
299,
16
] | python | en | ['en', 'en', 'en'] | True |
Blueprint.after_app_request | (self, f) | Like :meth:`Flask.after_request` but for a blueprint. Such a function
is executed after each request, even if outside of the blueprint.
| Like :meth:`Flask.after_request` but for a blueprint. Such a function
is executed after each request, even if outside of the blueprint.
| def after_app_request(self, f):
"""Like :meth:`Flask.after_request` but for a blueprint. Such a function
is executed after each request, even if outside of the blueprint.
"""
self.record_once(lambda s: s.app.after_request_funcs
.setdefault(None, []).append(f))
return f | [
"def",
"after_app_request",
"(",
"self",
",",
"f",
")",
":",
"self",
".",
"record_once",
"(",
"lambda",
"s",
":",
"s",
".",
"app",
".",
"after_request_funcs",
".",
"setdefault",
"(",
"None",
",",
"[",
"]",
")",
".",
"append",
"(",
"f",
")",
")",
"return",
"f"
] | [
301,
4
] | [
307,
16
] | python | en | ['en', 'en', 'en'] | True |
Blueprint.teardown_request | (self, f) | Like :meth:`Flask.teardown_request` but for a blueprint. This
function is only executed when tearing down requests handled by a
function of that blueprint. Teardown request functions are executed
when the request context is popped, even when no actual request was
performed.
| Like :meth:`Flask.teardown_request` but for a blueprint. This
function is only executed when tearing down requests handled by a
function of that blueprint. Teardown request functions are executed
when the request context is popped, even when no actual request was
performed.
| def teardown_request(self, f):
"""Like :meth:`Flask.teardown_request` but for a blueprint. This
function is only executed when tearing down requests handled by a
function of that blueprint. Teardown request functions are executed
when the request context is popped, even when no actual request was
performed.
"""
self.record_once(lambda s: s.app.teardown_request_funcs
.setdefault(self.name, []).append(f))
return f | [
"def",
"teardown_request",
"(",
"self",
",",
"f",
")",
":",
"self",
".",
"record_once",
"(",
"lambda",
"s",
":",
"s",
".",
"app",
".",
"teardown_request_funcs",
".",
"setdefault",
"(",
"self",
".",
"name",
",",
"[",
"]",
")",
".",
"append",
"(",
"f",
")",
")",
"return",
"f"
] | [
309,
4
] | [
318,
16
] | python | en | ['en', 'en', 'en'] | True |
Blueprint.teardown_app_request | (self, f) | Like :meth:`Flask.teardown_request` but for a blueprint. Such a
function is executed when tearing down each request, even if outside of
the blueprint.
| Like :meth:`Flask.teardown_request` but for a blueprint. Such a
function is executed when tearing down each request, even if outside of
the blueprint.
| def teardown_app_request(self, f):
"""Like :meth:`Flask.teardown_request` but for a blueprint. Such a
function is executed when tearing down each request, even if outside of
the blueprint.
"""
self.record_once(lambda s: s.app.teardown_request_funcs
.setdefault(None, []).append(f))
return f | [
"def",
"teardown_app_request",
"(",
"self",
",",
"f",
")",
":",
"self",
".",
"record_once",
"(",
"lambda",
"s",
":",
"s",
".",
"app",
".",
"teardown_request_funcs",
".",
"setdefault",
"(",
"None",
",",
"[",
"]",
")",
".",
"append",
"(",
"f",
")",
")",
"return",
"f"
] | [
320,
4
] | [
327,
16
] | python | en | ['en', 'en', 'en'] | True |
Blueprint.context_processor | (self, f) | Like :meth:`Flask.context_processor` but for a blueprint. This
function is only executed for requests handled by a blueprint.
| Like :meth:`Flask.context_processor` but for a blueprint. This
function is only executed for requests handled by a blueprint.
| def context_processor(self, f):
"""Like :meth:`Flask.context_processor` but for a blueprint. This
function is only executed for requests handled by a blueprint.
"""
self.record_once(lambda s: s.app.template_context_processors
.setdefault(self.name, []).append(f))
return f | [
"def",
"context_processor",
"(",
"self",
",",
"f",
")",
":",
"self",
".",
"record_once",
"(",
"lambda",
"s",
":",
"s",
".",
"app",
".",
"template_context_processors",
".",
"setdefault",
"(",
"self",
".",
"name",
",",
"[",
"]",
")",
".",
"append",
"(",
"f",
")",
")",
"return",
"f"
] | [
329,
4
] | [
335,
16
] | python | en | ['en', 'en', 'en'] | True |
Blueprint.app_context_processor | (self, f) | Like :meth:`Flask.context_processor` but for a blueprint. Such a
function is executed each request, even if outside of the blueprint.
| Like :meth:`Flask.context_processor` but for a blueprint. Such a
function is executed each request, even if outside of the blueprint.
| def app_context_processor(self, f):
"""Like :meth:`Flask.context_processor` but for a blueprint. Such a
function is executed each request, even if outside of the blueprint.
"""
self.record_once(lambda s: s.app.template_context_processors
.setdefault(None, []).append(f))
return f | [
"def",
"app_context_processor",
"(",
"self",
",",
"f",
")",
":",
"self",
".",
"record_once",
"(",
"lambda",
"s",
":",
"s",
".",
"app",
".",
"template_context_processors",
".",
"setdefault",
"(",
"None",
",",
"[",
"]",
")",
".",
"append",
"(",
"f",
")",
")",
"return",
"f"
] | [
337,
4
] | [
343,
16
] | python | en | ['en', 'en', 'en'] | True |
Blueprint.app_errorhandler | (self, code) | Like :meth:`Flask.errorhandler` but for a blueprint. This
handler is used for all requests, even if outside of the blueprint.
| Like :meth:`Flask.errorhandler` but for a blueprint. This
handler is used for all requests, even if outside of the blueprint.
| def app_errorhandler(self, code):
"""Like :meth:`Flask.errorhandler` but for a blueprint. This
handler is used for all requests, even if outside of the blueprint.
"""
def decorator(f):
self.record_once(lambda s: s.app.errorhandler(code)(f))
return f
return decorator | [
"def",
"app_errorhandler",
"(",
"self",
",",
"code",
")",
":",
"def",
"decorator",
"(",
"f",
")",
":",
"self",
".",
"record_once",
"(",
"lambda",
"s",
":",
"s",
".",
"app",
".",
"errorhandler",
"(",
"code",
")",
"(",
"f",
")",
")",
"return",
"f",
"return",
"decorator"
] | [
345,
4
] | [
352,
24
] | python | en | ['en', 'en', 'en'] | True |
Blueprint.url_value_preprocessor | (self, f) | Registers a function as URL value preprocessor for this
blueprint. It's called before the view functions are called and
can modify the url values provided.
| Registers a function as URL value preprocessor for this
blueprint. It's called before the view functions are called and
can modify the url values provided.
| def url_value_preprocessor(self, f):
"""Registers a function as URL value preprocessor for this
blueprint. It's called before the view functions are called and
can modify the url values provided.
"""
self.record_once(lambda s: s.app.url_value_preprocessors
.setdefault(self.name, []).append(f))
return f | [
"def",
"url_value_preprocessor",
"(",
"self",
",",
"f",
")",
":",
"self",
".",
"record_once",
"(",
"lambda",
"s",
":",
"s",
".",
"app",
".",
"url_value_preprocessors",
".",
"setdefault",
"(",
"self",
".",
"name",
",",
"[",
"]",
")",
".",
"append",
"(",
"f",
")",
")",
"return",
"f"
] | [
354,
4
] | [
361,
16
] | python | en | ['en', 'en', 'en'] | True |
Blueprint.url_defaults | (self, f) | Callback function for URL defaults for this blueprint. It's called
with the endpoint and values and should update the values passed
in place.
| Callback function for URL defaults for this blueprint. It's called
with the endpoint and values and should update the values passed
in place.
| def url_defaults(self, f):
"""Callback function for URL defaults for this blueprint. It's called
with the endpoint and values and should update the values passed
in place.
"""
self.record_once(lambda s: s.app.url_default_functions
.setdefault(self.name, []).append(f))
return f | [
"def",
"url_defaults",
"(",
"self",
",",
"f",
")",
":",
"self",
".",
"record_once",
"(",
"lambda",
"s",
":",
"s",
".",
"app",
".",
"url_default_functions",
".",
"setdefault",
"(",
"self",
".",
"name",
",",
"[",
"]",
")",
".",
"append",
"(",
"f",
")",
")",
"return",
"f"
] | [
363,
4
] | [
370,
16
] | python | en | ['en', 'en', 'en'] | True |
Blueprint.app_url_value_preprocessor | (self, f) | Same as :meth:`url_value_preprocessor` but application wide.
| Same as :meth:`url_value_preprocessor` but application wide.
| def app_url_value_preprocessor(self, f):
"""Same as :meth:`url_value_preprocessor` but application wide.
"""
self.record_once(lambda s: s.app.url_value_preprocessors
.setdefault(None, []).append(f))
return f | [
"def",
"app_url_value_preprocessor",
"(",
"self",
",",
"f",
")",
":",
"self",
".",
"record_once",
"(",
"lambda",
"s",
":",
"s",
".",
"app",
".",
"url_value_preprocessors",
".",
"setdefault",
"(",
"None",
",",
"[",
"]",
")",
".",
"append",
"(",
"f",
")",
")",
"return",
"f"
] | [
372,
4
] | [
377,
16
] | python | en | ['en', 'en', 'en'] | True |
Blueprint.app_url_defaults | (self, f) | Same as :meth:`url_defaults` but application wide.
| Same as :meth:`url_defaults` but application wide.
| def app_url_defaults(self, f):
"""Same as :meth:`url_defaults` but application wide.
"""
self.record_once(lambda s: s.app.url_default_functions
.setdefault(None, []).append(f))
return f | [
"def",
"app_url_defaults",
"(",
"self",
",",
"f",
")",
":",
"self",
".",
"record_once",
"(",
"lambda",
"s",
":",
"s",
".",
"app",
".",
"url_default_functions",
".",
"setdefault",
"(",
"None",
",",
"[",
"]",
")",
".",
"append",
"(",
"f",
")",
")",
"return",
"f"
] | [
379,
4
] | [
384,
16
] | python | en | ['en', 'en', 'en'] | True |
Blueprint.errorhandler | (self, code_or_exception) | Registers an error handler that becomes active for this blueprint
only. Please be aware that routing does not happen local to a
blueprint so an error handler for 404 usually is not handled by
a blueprint unless it is caused inside a view function. Another
special case is the 500 internal server error which is always looked
up from the application.
Otherwise works as the :meth:`~flask.Flask.errorhandler` decorator
of the :class:`~flask.Flask` object.
| Registers an error handler that becomes active for this blueprint
only. Please be aware that routing does not happen local to a
blueprint so an error handler for 404 usually is not handled by
a blueprint unless it is caused inside a view function. Another
special case is the 500 internal server error which is always looked
up from the application. | def errorhandler(self, code_or_exception):
"""Registers an error handler that becomes active for this blueprint
only. Please be aware that routing does not happen local to a
blueprint so an error handler for 404 usually is not handled by
a blueprint unless it is caused inside a view function. Another
special case is the 500 internal server error which is always looked
up from the application.
Otherwise works as the :meth:`~flask.Flask.errorhandler` decorator
of the :class:`~flask.Flask` object.
"""
def decorator(f):
self.record_once(lambda s: s.app._register_error_handler(
self.name, code_or_exception, f))
return f
return decorator | [
"def",
"errorhandler",
"(",
"self",
",",
"code_or_exception",
")",
":",
"def",
"decorator",
"(",
"f",
")",
":",
"self",
".",
"record_once",
"(",
"lambda",
"s",
":",
"s",
".",
"app",
".",
"_register_error_handler",
"(",
"self",
".",
"name",
",",
"code_or_exception",
",",
"f",
")",
")",
"return",
"f",
"return",
"decorator"
] | [
386,
4
] | [
401,
24
] | python | en | ['en', 'en', 'en'] | True |
Blueprint.register_error_handler | (self, code_or_exception, f) | Non-decorator version of the :meth:`errorhandler` error attach
function, akin to the :meth:`~flask.Flask.register_error_handler`
application-wide function of the :class:`~flask.Flask` object but
for error handlers limited to this blueprint.
.. versionadded:: 0.11
| Non-decorator version of the :meth:`errorhandler` error attach
function, akin to the :meth:`~flask.Flask.register_error_handler`
application-wide function of the :class:`~flask.Flask` object but
for error handlers limited to this blueprint. | def register_error_handler(self, code_or_exception, f):
"""Non-decorator version of the :meth:`errorhandler` error attach
function, akin to the :meth:`~flask.Flask.register_error_handler`
application-wide function of the :class:`~flask.Flask` object but
for error handlers limited to this blueprint.
.. versionadded:: 0.11
"""
self.record_once(lambda s: s.app._register_error_handler(
self.name, code_or_exception, f)) | [
"def",
"register_error_handler",
"(",
"self",
",",
"code_or_exception",
",",
"f",
")",
":",
"self",
".",
"record_once",
"(",
"lambda",
"s",
":",
"s",
".",
"app",
".",
"_register_error_handler",
"(",
"self",
".",
"name",
",",
"code_or_exception",
",",
"f",
")",
")"
] | [
403,
4
] | [
412,
45
] | python | en | ['en', 'de', 'en'] | True |
_import_table_from_path | (filename: Path, sheet_name: Optional[str] = None, index: Optional[str] = None) | Imports a file as a pandas.DataFrame. Infers filetype from the filename extension/suffix.
| Imports a file as a pandas.DataFrame. Infers filetype from the filename extension/suffix.
| def _import_table_from_path(filename: Path, sheet_name: Optional[str] = None, index: Optional[str] = None) -> pandas.DataFrame:
""" Imports a file as a pandas.DataFrame. Infers filetype from the filename extension/suffix.
"""
if filename.suffix in {'.xls', '.xlsx'}:
data: pandas.DataFrame = pandas.read_excel(str(filename), sheet_name = sheet_name)
else:
sep = '\t' if filename.suffix in {'.tsv', '.tab'} else ','
data: pandas.DataFrame = pandas.read_table(str(filename), sep = sep)
if index and index in data.columns:
data = data.set_index(index)
return data | [
"def",
"_import_table_from_path",
"(",
"filename",
":",
"Path",
",",
"sheet_name",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
",",
"index",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
")",
"->",
"pandas",
".",
"DataFrame",
":",
"if",
"filename",
".",
"suffix",
"in",
"{",
"'.xls'",
",",
"'.xlsx'",
"}",
":",
"data",
":",
"pandas",
".",
"DataFrame",
"=",
"pandas",
".",
"read_excel",
"(",
"str",
"(",
"filename",
")",
",",
"sheet_name",
"=",
"sheet_name",
")",
"else",
":",
"sep",
"=",
"'\\t'",
"if",
"filename",
".",
"suffix",
"in",
"{",
"'.tsv'",
",",
"'.tab'",
"}",
"else",
"','",
"data",
":",
"pandas",
".",
"DataFrame",
"=",
"pandas",
".",
"read_table",
"(",
"str",
"(",
"filename",
")",
",",
"sep",
"=",
"sep",
")",
"if",
"index",
"and",
"index",
"in",
"data",
".",
"columns",
":",
"data",
"=",
"data",
".",
"set_index",
"(",
"index",
")",
"return",
"data"
] | [
6,
0
] | [
18,
12
] | python | en | ['en', 'en', 'en'] | True |
_import_table_from_string | (string: str, delimiter: Optional[str] = None, index: Optional[str] = None) | Imports a table represented as a basic string object. | Imports a table represented as a basic string object. | def _import_table_from_string(string: str, delimiter: Optional[str] = None, index: Optional[str] = None) -> pandas.DataFrame:
""" Imports a table represented as a basic string object."""
# Remove unwanted whitespace.
string = '\n'.join(i.strip() for i in string.split('\n') if i)
if not delimiter:
delimiter = '\t' if '\t' in string else ','
result = pandas.read_table(io.StringIO(string), sep = delimiter, index_col = False)
if index:
# Using `index_col` in `read_table()` doesn't work for some reason.
#result[index] = result[index].astype(str)
result.set_index(index, inplace = True)
return result | [
"def",
"_import_table_from_string",
"(",
"string",
":",
"str",
",",
"delimiter",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
",",
"index",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
")",
"->",
"pandas",
".",
"DataFrame",
":",
"# Remove unwanted whitespace.",
"string",
"=",
"'\\n'",
".",
"join",
"(",
"i",
".",
"strip",
"(",
")",
"for",
"i",
"in",
"string",
".",
"split",
"(",
"'\\n'",
")",
"if",
"i",
")",
"if",
"not",
"delimiter",
":",
"delimiter",
"=",
"'\\t'",
"if",
"'\\t'",
"in",
"string",
"else",
"','",
"result",
"=",
"pandas",
".",
"read_table",
"(",
"io",
".",
"StringIO",
"(",
"string",
")",
",",
"sep",
"=",
"delimiter",
",",
"index_col",
"=",
"False",
")",
"if",
"index",
":",
"# Using `index_col` in `read_table()` doesn't work for some reason.",
"#result[index] = result[index].astype(str)",
"result",
".",
"set_index",
"(",
"index",
",",
"inplace",
"=",
"True",
")",
"return",
"result"
] | [
21,
0
] | [
32,
14
] | python | en | ['en', 'en', 'en'] | True |
tempdir | () | Create a temporary directory in a context manager. | Create a temporary directory in a context manager. | def tempdir():
"""Create a temporary directory in a context manager."""
td = tempfile.mkdtemp()
try:
yield td
finally:
shutil.rmtree(td) | [
"def",
"tempdir",
"(",
")",
":",
"td",
"=",
"tempfile",
".",
"mkdtemp",
"(",
")",
"try",
":",
"yield",
"td",
"finally",
":",
"shutil",
".",
"rmtree",
"(",
"td",
")"
] | [
10,
0
] | [
16,
25
] | python | en | ['en', 'en', 'en'] | True |
mkdir_p | (*args, **kwargs) | Like `mkdir`, but does not raise an exception if the
directory already exists.
| Like `mkdir`, but does not raise an exception if the
directory already exists.
| def mkdir_p(*args, **kwargs):
"""Like `mkdir`, but does not raise an exception if the
directory already exists.
"""
try:
return os.mkdir(*args, **kwargs)
except OSError as exc:
if exc.errno != errno.EEXIST:
raise | [
"def",
"mkdir_p",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"return",
"os",
".",
"mkdir",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"except",
"OSError",
"as",
"exc",
":",
"if",
"exc",
".",
"errno",
"!=",
"errno",
".",
"EEXIST",
":",
"raise"
] | [
19,
0
] | [
27,
17
] | python | en | ['en', 'en', 'en'] | True |
dir_to_zipfile | (root) | Construct an in-memory zip file for a directory. | Construct an in-memory zip file for a directory. | def dir_to_zipfile(root):
"""Construct an in-memory zip file for a directory."""
buffer = io.BytesIO()
zip_file = zipfile.ZipFile(buffer, 'w')
for root, dirs, files in os.walk(root):
for path in dirs:
fs_path = os.path.join(root, path)
rel_path = os.path.relpath(fs_path, root)
zip_file.writestr(rel_path + '/', '')
for path in files:
fs_path = os.path.join(root, path)
rel_path = os.path.relpath(fs_path, root)
zip_file.write(fs_path, rel_path)
return zip_file | [
"def",
"dir_to_zipfile",
"(",
"root",
")",
":",
"buffer",
"=",
"io",
".",
"BytesIO",
"(",
")",
"zip_file",
"=",
"zipfile",
".",
"ZipFile",
"(",
"buffer",
",",
"'w'",
")",
"for",
"root",
",",
"dirs",
",",
"files",
"in",
"os",
".",
"walk",
"(",
"root",
")",
":",
"for",
"path",
"in",
"dirs",
":",
"fs_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"root",
",",
"path",
")",
"rel_path",
"=",
"os",
".",
"path",
".",
"relpath",
"(",
"fs_path",
",",
"root",
")",
"zip_file",
".",
"writestr",
"(",
"rel_path",
"+",
"'/'",
",",
"''",
")",
"for",
"path",
"in",
"files",
":",
"fs_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"root",
",",
"path",
")",
"rel_path",
"=",
"os",
".",
"path",
".",
"relpath",
"(",
"fs_path",
",",
"root",
")",
"zip_file",
".",
"write",
"(",
"fs_path",
",",
"rel_path",
")",
"return",
"zip_file"
] | [
30,
0
] | [
43,
19
] | python | en | ['br', 'en', 'en'] | True |
OGRGeomType.__init__ | (self, type_input) | Figure out the correct OGR Type based upon the input. | Figure out the correct OGR Type based upon the input. | def __init__(self, type_input):
"Figure out the correct OGR Type based upon the input."
if isinstance(type_input, OGRGeomType):
num = type_input.num
elif isinstance(type_input, str):
type_input = type_input.lower()
if type_input == 'geometry':
type_input = 'unknown'
num = self._str_types.get(type_input)
if num is None:
raise GDALException('Invalid OGR String Type "%s"' % type_input)
elif isinstance(type_input, int):
if type_input not in self._types:
raise GDALException('Invalid OGR Integer Type: %d' % type_input)
num = type_input
else:
raise TypeError('Invalid OGR input type given.')
# Setting the OGR geometry type number.
self.num = num | [
"def",
"__init__",
"(",
"self",
",",
"type_input",
")",
":",
"if",
"isinstance",
"(",
"type_input",
",",
"OGRGeomType",
")",
":",
"num",
"=",
"type_input",
".",
"num",
"elif",
"isinstance",
"(",
"type_input",
",",
"str",
")",
":",
"type_input",
"=",
"type_input",
".",
"lower",
"(",
")",
"if",
"type_input",
"==",
"'geometry'",
":",
"type_input",
"=",
"'unknown'",
"num",
"=",
"self",
".",
"_str_types",
".",
"get",
"(",
"type_input",
")",
"if",
"num",
"is",
"None",
":",
"raise",
"GDALException",
"(",
"'Invalid OGR String Type \"%s\"'",
"%",
"type_input",
")",
"elif",
"isinstance",
"(",
"type_input",
",",
"int",
")",
":",
"if",
"type_input",
"not",
"in",
"self",
".",
"_types",
":",
"raise",
"GDALException",
"(",
"'Invalid OGR Integer Type: %d'",
"%",
"type_input",
")",
"num",
"=",
"type_input",
"else",
":",
"raise",
"TypeError",
"(",
"'Invalid OGR input type given.'",
")",
"# Setting the OGR geometry type number.",
"self",
".",
"num",
"=",
"num"
] | [
32,
4
] | [
51,
22
] | python | en | ['en', 'en', 'en'] | True |
OGRGeomType.__str__ | (self) | Return the value of the name property. | Return the value of the name property. | def __str__(self):
"Return the value of the name property."
return self.name | [
"def",
"__str__",
"(",
"self",
")",
":",
"return",
"self",
".",
"name"
] | [
53,
4
] | [
55,
24
] | python | en | ['en', 'en', 'en'] | True |
OGRGeomType.__eq__ | (self, other) |
Do an equivalence test on the OGR type with the given
other OGRGeomType, the short-hand string, or the integer.
|
Do an equivalence test on the OGR type with the given
other OGRGeomType, the short-hand string, or the integer.
| def __eq__(self, other):
"""
Do an equivalence test on the OGR type with the given
other OGRGeomType, the short-hand string, or the integer.
"""
if isinstance(other, OGRGeomType):
return self.num == other.num
elif isinstance(other, str):
return self.name.lower() == other.lower()
elif isinstance(other, int):
return self.num == other
else:
return False | [
"def",
"__eq__",
"(",
"self",
",",
"other",
")",
":",
"if",
"isinstance",
"(",
"other",
",",
"OGRGeomType",
")",
":",
"return",
"self",
".",
"num",
"==",
"other",
".",
"num",
"elif",
"isinstance",
"(",
"other",
",",
"str",
")",
":",
"return",
"self",
".",
"name",
".",
"lower",
"(",
")",
"==",
"other",
".",
"lower",
"(",
")",
"elif",
"isinstance",
"(",
"other",
",",
"int",
")",
":",
"return",
"self",
".",
"num",
"==",
"other",
"else",
":",
"return",
"False"
] | [
57,
4
] | [
69,
24
] | python | en | ['en', 'error', 'th'] | False |
OGRGeomType.name | (self) | Return a short-hand string form of the OGR Geometry type. | Return a short-hand string form of the OGR Geometry type. | def name(self):
"Return a short-hand string form of the OGR Geometry type."
return self._types[self.num] | [
"def",
"name",
"(",
"self",
")",
":",
"return",
"self",
".",
"_types",
"[",
"self",
".",
"num",
"]"
] | [
72,
4
] | [
74,
36
] | python | en | ['en', 'en', 'en'] | True |
OGRGeomType.django | (self) | Return the Django GeometryField for this OGR Type. | Return the Django GeometryField for this OGR Type. | def django(self):
"Return the Django GeometryField for this OGR Type."
s = self.name.replace('25D', '')
if s in ('LinearRing', 'None'):
return None
elif s == 'Unknown':
s = 'Geometry'
elif s == 'PointZ':
s = 'Point'
return s + 'Field' | [
"def",
"django",
"(",
"self",
")",
":",
"s",
"=",
"self",
".",
"name",
".",
"replace",
"(",
"'25D'",
",",
"''",
")",
"if",
"s",
"in",
"(",
"'LinearRing'",
",",
"'None'",
")",
":",
"return",
"None",
"elif",
"s",
"==",
"'Unknown'",
":",
"s",
"=",
"'Geometry'",
"elif",
"s",
"==",
"'PointZ'",
":",
"s",
"=",
"'Point'",
"return",
"s",
"+",
"'Field'"
] | [
77,
4
] | [
86,
26
] | python | en | ['en', 'af', 'en'] | True |
OGRGeomType.to_multi | (self) |
Transform Point, LineString, Polygon, and their 25D equivalents
to their Multi... counterpart.
|
Transform Point, LineString, Polygon, and their 25D equivalents
to their Multi... counterpart.
| def to_multi(self):
"""
Transform Point, LineString, Polygon, and their 25D equivalents
to their Multi... counterpart.
"""
if self.name.startswith(('Point', 'LineString', 'Polygon')):
self.num += 3 | [
"def",
"to_multi",
"(",
"self",
")",
":",
"if",
"self",
".",
"name",
".",
"startswith",
"(",
"(",
"'Point'",
",",
"'LineString'",
",",
"'Polygon'",
")",
")",
":",
"self",
".",
"num",
"+=",
"3"
] | [
88,
4
] | [
94,
25
] | python | en | ['en', 'error', 'th'] | False |
check_password | (environ, username, password) |
Authenticate against Django's auth database.
mod_wsgi docs specify None, True, False as return value depending
on whether the user exists and authenticates.
|
Authenticate against Django's auth database. | def check_password(environ, username, password):
"""
Authenticate against Django's auth database.
mod_wsgi docs specify None, True, False as return value depending
on whether the user exists and authenticates.
"""
# db connection state is managed similarly to the wsgi handler
# as mod_wsgi may call these functions outside of a request/response cycle
db.reset_queries()
try:
try:
user = UserModel._default_manager.get_by_natural_key(username)
except UserModel.DoesNotExist:
return None
if not user.is_active:
return None
return user.check_password(password)
finally:
db.close_old_connections() | [
"def",
"check_password",
"(",
"environ",
",",
"username",
",",
"password",
")",
":",
"# db connection state is managed similarly to the wsgi handler",
"# as mod_wsgi may call these functions outside of a request/response cycle",
"db",
".",
"reset_queries",
"(",
")",
"try",
":",
"try",
":",
"user",
"=",
"UserModel",
".",
"_default_manager",
".",
"get_by_natural_key",
"(",
"username",
")",
"except",
"UserModel",
".",
"DoesNotExist",
":",
"return",
"None",
"if",
"not",
"user",
".",
"is_active",
":",
"return",
"None",
"return",
"user",
".",
"check_password",
"(",
"password",
")",
"finally",
":",
"db",
".",
"close_old_connections",
"(",
")"
] | [
6,
0
] | [
25,
34
] | python | en | ['en', 'error', 'th'] | False |
groups_for_user | (environ, username) |
Authorize a user based on groups
|
Authorize a user based on groups
| def groups_for_user(environ, username):
"""
Authorize a user based on groups
"""
db.reset_queries()
try:
try:
user = UserModel._default_manager.get_by_natural_key(username)
except UserModel.DoesNotExist:
return []
if not user.is_active:
return []
return [group.name.encode() for group in user.groups.all()]
finally:
db.close_old_connections() | [
"def",
"groups_for_user",
"(",
"environ",
",",
"username",
")",
":",
"db",
".",
"reset_queries",
"(",
")",
"try",
":",
"try",
":",
"user",
"=",
"UserModel",
".",
"_default_manager",
".",
"get_by_natural_key",
"(",
"username",
")",
"except",
"UserModel",
".",
"DoesNotExist",
":",
"return",
"[",
"]",
"if",
"not",
"user",
".",
"is_active",
":",
"return",
"[",
"]",
"return",
"[",
"group",
".",
"name",
".",
"encode",
"(",
")",
"for",
"group",
"in",
"user",
".",
"groups",
".",
"all",
"(",
")",
"]",
"finally",
":",
"db",
".",
"close_old_connections",
"(",
")"
] | [
28,
0
] | [
42,
34
] | python | en | ['en', 'error', 'th'] | False |
main | () | Run administrative tasks. | Run administrative tasks. | def main():
"""Run administrative tasks."""
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'gallery.settings')
try:
from django.core.management import execute_from_command_line
except ImportError as exc:
raise ImportError(
"Couldn't import Django. Are you sure it's installed and "
"available on your PYTHONPATH environment variable? Did you "
"forget to activate a virtual environment?"
) from exc
execute_from_command_line(sys.argv) | [
"def",
"main",
"(",
")",
":",
"os",
".",
"environ",
".",
"setdefault",
"(",
"'DJANGO_SETTINGS_MODULE'",
",",
"'gallery.settings'",
")",
"try",
":",
"from",
"django",
".",
"core",
".",
"management",
"import",
"execute_from_command_line",
"except",
"ImportError",
"as",
"exc",
":",
"raise",
"ImportError",
"(",
"\"Couldn't import Django. Are you sure it's installed and \"",
"\"available on your PYTHONPATH environment variable? Did you \"",
"\"forget to activate a virtual environment?\"",
")",
"from",
"exc",
"execute_from_command_line",
"(",
"sys",
".",
"argv",
")"
] | [
6,
0
] | [
17,
39
] | python | en | ['lv', 'gd', 'en'] | False |
Environment._search_distribution | (self, name: str) | Find a distribution matching the ``name`` in the environment.
This searches from *all* distributions available in the environment, to
match the behavior of ``pkg_resources.get_distribution()``.
| Find a distribution matching the ``name`` in the environment. | def _search_distribution(self, name: str) -> Optional[BaseDistribution]:
"""Find a distribution matching the ``name`` in the environment.
This searches from *all* distributions available in the environment, to
match the behavior of ``pkg_resources.get_distribution()``.
"""
canonical_name = canonicalize_name(name)
for dist in self.iter_distributions():
if dist.canonical_name == canonical_name:
return dist
return None | [
"def",
"_search_distribution",
"(",
"self",
",",
"name",
":",
"str",
")",
"->",
"Optional",
"[",
"BaseDistribution",
"]",
":",
"canonical_name",
"=",
"canonicalize_name",
"(",
"name",
")",
"for",
"dist",
"in",
"self",
".",
"iter_distributions",
"(",
")",
":",
"if",
"dist",
".",
"canonical_name",
"==",
"canonical_name",
":",
"return",
"dist",
"return",
"None"
] | [
115,
4
] | [
125,
19
] | python | en | ['en', 'en', 'en'] | True |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.