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 |
---|---|---|---|---|---|---|---|---|---|---|---|
gdal_full_version | () | Return the full GDAL version information. | Return the full GDAL version information. | def gdal_full_version():
"Return the full GDAL version information."
return _version_info(b'') | [
"def",
"gdal_full_version",
"(",
")",
":",
"return",
"_version_info",
"(",
"b''",
")"
] | [
87,
0
] | [
89,
29
] | python | en | ['en', 'no', 'en'] | True |
csrf | (request) |
Context processor that provides a CSRF token, or the string 'NOTPROVIDED' if
it has not been provided by either a view decorator or the middleware
|
Context processor that provides a CSRF token, or the string 'NOTPROVIDED' if
it has not been provided by either a view decorator or the middleware
| def csrf(request):
"""
Context processor that provides a CSRF token, or the string 'NOTPROVIDED' if
it has not been provided by either a view decorator or the middleware
"""
def _get_val():
token = get_token(request)
if token is None:
# In order to be able to provide debugging info in the
# case of misconfiguration, we use a sentinel value
# instead of returning an empty dict.
return 'NOTPROVIDED'
else:
return token
return {'csrf_token': SimpleLazyObject(_get_val)} | [
"def",
"csrf",
"(",
"request",
")",
":",
"def",
"_get_val",
"(",
")",
":",
"token",
"=",
"get_token",
"(",
"request",
")",
"if",
"token",
"is",
"None",
":",
"# In order to be able to provide debugging info in the",
"# case of misconfiguration, we use a sentinel value",
"# instead of returning an empty dict.",
"return",
"'NOTPROVIDED'",
"else",
":",
"return",
"token",
"return",
"{",
"'csrf_token'",
":",
"SimpleLazyObject",
"(",
"_get_val",
")",
"}"
] | [
16,
0
] | [
31,
53
] | python | en | ['en', 'error', 'th'] | False |
debug | (request) |
Return context variables helpful for debugging.
|
Return context variables helpful for debugging.
| def debug(request):
"""
Return context variables helpful for debugging.
"""
context_extras = {}
if settings.DEBUG and request.META.get('REMOTE_ADDR') in settings.INTERNAL_IPS:
context_extras['debug'] = True
from django.db import connections
# Return a lazy reference that computes connection.queries on access,
# to ensure it contains queries triggered after this function runs.
context_extras['sql_queries'] = lazy(
lambda: list(itertools.chain.from_iterable(connections[x].queries for x in connections)),
list
)
return context_extras | [
"def",
"debug",
"(",
"request",
")",
":",
"context_extras",
"=",
"{",
"}",
"if",
"settings",
".",
"DEBUG",
"and",
"request",
".",
"META",
".",
"get",
"(",
"'REMOTE_ADDR'",
")",
"in",
"settings",
".",
"INTERNAL_IPS",
":",
"context_extras",
"[",
"'debug'",
"]",
"=",
"True",
"from",
"django",
".",
"db",
"import",
"connections",
"# Return a lazy reference that computes connection.queries on access,",
"# to ensure it contains queries triggered after this function runs.",
"context_extras",
"[",
"'sql_queries'",
"]",
"=",
"lazy",
"(",
"lambda",
":",
"list",
"(",
"itertools",
".",
"chain",
".",
"from_iterable",
"(",
"connections",
"[",
"x",
"]",
".",
"queries",
"for",
"x",
"in",
"connections",
")",
")",
",",
"list",
")",
"return",
"context_extras"
] | [
34,
0
] | [
49,
25
] | python | en | ['en', 'error', 'th'] | False |
static | (request) |
Add static-related context variables to the context.
|
Add static-related context variables to the context.
| def static(request):
"""
Add static-related context variables to the context.
"""
return {'STATIC_URL': settings.STATIC_URL} | [
"def",
"static",
"(",
"request",
")",
":",
"return",
"{",
"'STATIC_URL'",
":",
"settings",
".",
"STATIC_URL",
"}"
] | [
66,
0
] | [
70,
46
] | python | en | ['en', 'error', 'th'] | False |
media | (request) |
Add media-related context variables to the context.
|
Add media-related context variables to the context.
| def media(request):
"""
Add media-related context variables to the context.
"""
return {'MEDIA_URL': settings.MEDIA_URL} | [
"def",
"media",
"(",
"request",
")",
":",
"return",
"{",
"'MEDIA_URL'",
":",
"settings",
".",
"MEDIA_URL",
"}"
] | [
73,
0
] | [
77,
44
] | python | en | ['en', 'error', 'th'] | False |
getrgb | (color) |
Convert a color string to an RGB or RGBA tuple. If the string cannot be
parsed, this function raises a :py:exc:`ValueError` exception.
.. versionadded:: 1.1.4
:param color: A color string
:return: ``(red, green, blue[, alpha])``
|
Convert a color string to an RGB or RGBA tuple. If the string cannot be
parsed, this function raises a :py:exc:`ValueError` exception. | def getrgb(color):
"""
Convert a color string to an RGB or RGBA tuple. If the string cannot be
parsed, this function raises a :py:exc:`ValueError` exception.
.. versionadded:: 1.1.4
:param color: A color string
:return: ``(red, green, blue[, alpha])``
"""
if len(color) > 100:
raise ValueError("color specifier is too long")
color = color.lower()
rgb = colormap.get(color, None)
if rgb:
if isinstance(rgb, tuple):
return rgb
colormap[color] = rgb = getrgb(rgb)
return rgb
# check for known string formats
if re.match("#[a-f0-9]{3}$", color):
return (int(color[1] * 2, 16), int(color[2] * 2, 16), int(color[3] * 2, 16))
if re.match("#[a-f0-9]{4}$", color):
return (
int(color[1] * 2, 16),
int(color[2] * 2, 16),
int(color[3] * 2, 16),
int(color[4] * 2, 16),
)
if re.match("#[a-f0-9]{6}$", color):
return (int(color[1:3], 16), int(color[3:5], 16), int(color[5:7], 16))
if re.match("#[a-f0-9]{8}$", color):
return (
int(color[1:3], 16),
int(color[3:5], 16),
int(color[5:7], 16),
int(color[7:9], 16),
)
m = re.match(r"rgb\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)$", color)
if m:
return (int(m.group(1)), int(m.group(2)), int(m.group(3)))
m = re.match(r"rgb\(\s*(\d+)%\s*,\s*(\d+)%\s*,\s*(\d+)%\s*\)$", color)
if m:
return (
int((int(m.group(1)) * 255) / 100.0 + 0.5),
int((int(m.group(2)) * 255) / 100.0 + 0.5),
int((int(m.group(3)) * 255) / 100.0 + 0.5),
)
m = re.match(
r"hsl\(\s*(\d+\.?\d*)\s*,\s*(\d+\.?\d*)%\s*,\s*(\d+\.?\d*)%\s*\)$", color
)
if m:
from colorsys import hls_to_rgb
rgb = hls_to_rgb(
float(m.group(1)) / 360.0,
float(m.group(3)) / 100.0,
float(m.group(2)) / 100.0,
)
return (
int(rgb[0] * 255 + 0.5),
int(rgb[1] * 255 + 0.5),
int(rgb[2] * 255 + 0.5),
)
m = re.match(
r"hs[bv]\(\s*(\d+\.?\d*)\s*,\s*(\d+\.?\d*)%\s*,\s*(\d+\.?\d*)%\s*\)$", color
)
if m:
from colorsys import hsv_to_rgb
rgb = hsv_to_rgb(
float(m.group(1)) / 360.0,
float(m.group(2)) / 100.0,
float(m.group(3)) / 100.0,
)
return (
int(rgb[0] * 255 + 0.5),
int(rgb[1] * 255 + 0.5),
int(rgb[2] * 255 + 0.5),
)
m = re.match(r"rgba\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)$", color)
if m:
return (int(m.group(1)), int(m.group(2)), int(m.group(3)), int(m.group(4)))
raise ValueError(f"unknown color specifier: {repr(color)}") | [
"def",
"getrgb",
"(",
"color",
")",
":",
"if",
"len",
"(",
"color",
")",
">",
"100",
":",
"raise",
"ValueError",
"(",
"\"color specifier is too long\"",
")",
"color",
"=",
"color",
".",
"lower",
"(",
")",
"rgb",
"=",
"colormap",
".",
"get",
"(",
"color",
",",
"None",
")",
"if",
"rgb",
":",
"if",
"isinstance",
"(",
"rgb",
",",
"tuple",
")",
":",
"return",
"rgb",
"colormap",
"[",
"color",
"]",
"=",
"rgb",
"=",
"getrgb",
"(",
"rgb",
")",
"return",
"rgb",
"# check for known string formats",
"if",
"re",
".",
"match",
"(",
"\"#[a-f0-9]{3}$\"",
",",
"color",
")",
":",
"return",
"(",
"int",
"(",
"color",
"[",
"1",
"]",
"*",
"2",
",",
"16",
")",
",",
"int",
"(",
"color",
"[",
"2",
"]",
"*",
"2",
",",
"16",
")",
",",
"int",
"(",
"color",
"[",
"3",
"]",
"*",
"2",
",",
"16",
")",
")",
"if",
"re",
".",
"match",
"(",
"\"#[a-f0-9]{4}$\"",
",",
"color",
")",
":",
"return",
"(",
"int",
"(",
"color",
"[",
"1",
"]",
"*",
"2",
",",
"16",
")",
",",
"int",
"(",
"color",
"[",
"2",
"]",
"*",
"2",
",",
"16",
")",
",",
"int",
"(",
"color",
"[",
"3",
"]",
"*",
"2",
",",
"16",
")",
",",
"int",
"(",
"color",
"[",
"4",
"]",
"*",
"2",
",",
"16",
")",
",",
")",
"if",
"re",
".",
"match",
"(",
"\"#[a-f0-9]{6}$\"",
",",
"color",
")",
":",
"return",
"(",
"int",
"(",
"color",
"[",
"1",
":",
"3",
"]",
",",
"16",
")",
",",
"int",
"(",
"color",
"[",
"3",
":",
"5",
"]",
",",
"16",
")",
",",
"int",
"(",
"color",
"[",
"5",
":",
"7",
"]",
",",
"16",
")",
")",
"if",
"re",
".",
"match",
"(",
"\"#[a-f0-9]{8}$\"",
",",
"color",
")",
":",
"return",
"(",
"int",
"(",
"color",
"[",
"1",
":",
"3",
"]",
",",
"16",
")",
",",
"int",
"(",
"color",
"[",
"3",
":",
"5",
"]",
",",
"16",
")",
",",
"int",
"(",
"color",
"[",
"5",
":",
"7",
"]",
",",
"16",
")",
",",
"int",
"(",
"color",
"[",
"7",
":",
"9",
"]",
",",
"16",
")",
",",
")",
"m",
"=",
"re",
".",
"match",
"(",
"r\"rgb\\(\\s*(\\d+)\\s*,\\s*(\\d+)\\s*,\\s*(\\d+)\\s*\\)$\"",
",",
"color",
")",
"if",
"m",
":",
"return",
"(",
"int",
"(",
"m",
".",
"group",
"(",
"1",
")",
")",
",",
"int",
"(",
"m",
".",
"group",
"(",
"2",
")",
")",
",",
"int",
"(",
"m",
".",
"group",
"(",
"3",
")",
")",
")",
"m",
"=",
"re",
".",
"match",
"(",
"r\"rgb\\(\\s*(\\d+)%\\s*,\\s*(\\d+)%\\s*,\\s*(\\d+)%\\s*\\)$\"",
",",
"color",
")",
"if",
"m",
":",
"return",
"(",
"int",
"(",
"(",
"int",
"(",
"m",
".",
"group",
"(",
"1",
")",
")",
"*",
"255",
")",
"/",
"100.0",
"+",
"0.5",
")",
",",
"int",
"(",
"(",
"int",
"(",
"m",
".",
"group",
"(",
"2",
")",
")",
"*",
"255",
")",
"/",
"100.0",
"+",
"0.5",
")",
",",
"int",
"(",
"(",
"int",
"(",
"m",
".",
"group",
"(",
"3",
")",
")",
"*",
"255",
")",
"/",
"100.0",
"+",
"0.5",
")",
",",
")",
"m",
"=",
"re",
".",
"match",
"(",
"r\"hsl\\(\\s*(\\d+\\.?\\d*)\\s*,\\s*(\\d+\\.?\\d*)%\\s*,\\s*(\\d+\\.?\\d*)%\\s*\\)$\"",
",",
"color",
")",
"if",
"m",
":",
"from",
"colorsys",
"import",
"hls_to_rgb",
"rgb",
"=",
"hls_to_rgb",
"(",
"float",
"(",
"m",
".",
"group",
"(",
"1",
")",
")",
"/",
"360.0",
",",
"float",
"(",
"m",
".",
"group",
"(",
"3",
")",
")",
"/",
"100.0",
",",
"float",
"(",
"m",
".",
"group",
"(",
"2",
")",
")",
"/",
"100.0",
",",
")",
"return",
"(",
"int",
"(",
"rgb",
"[",
"0",
"]",
"*",
"255",
"+",
"0.5",
")",
",",
"int",
"(",
"rgb",
"[",
"1",
"]",
"*",
"255",
"+",
"0.5",
")",
",",
"int",
"(",
"rgb",
"[",
"2",
"]",
"*",
"255",
"+",
"0.5",
")",
",",
")",
"m",
"=",
"re",
".",
"match",
"(",
"r\"hs[bv]\\(\\s*(\\d+\\.?\\d*)\\s*,\\s*(\\d+\\.?\\d*)%\\s*,\\s*(\\d+\\.?\\d*)%\\s*\\)$\"",
",",
"color",
")",
"if",
"m",
":",
"from",
"colorsys",
"import",
"hsv_to_rgb",
"rgb",
"=",
"hsv_to_rgb",
"(",
"float",
"(",
"m",
".",
"group",
"(",
"1",
")",
")",
"/",
"360.0",
",",
"float",
"(",
"m",
".",
"group",
"(",
"2",
")",
")",
"/",
"100.0",
",",
"float",
"(",
"m",
".",
"group",
"(",
"3",
")",
")",
"/",
"100.0",
",",
")",
"return",
"(",
"int",
"(",
"rgb",
"[",
"0",
"]",
"*",
"255",
"+",
"0.5",
")",
",",
"int",
"(",
"rgb",
"[",
"1",
"]",
"*",
"255",
"+",
"0.5",
")",
",",
"int",
"(",
"rgb",
"[",
"2",
"]",
"*",
"255",
"+",
"0.5",
")",
",",
")",
"m",
"=",
"re",
".",
"match",
"(",
"r\"rgba\\(\\s*(\\d+)\\s*,\\s*(\\d+)\\s*,\\s*(\\d+)\\s*,\\s*(\\d+)\\s*\\)$\"",
",",
"color",
")",
"if",
"m",
":",
"return",
"(",
"int",
"(",
"m",
".",
"group",
"(",
"1",
")",
")",
",",
"int",
"(",
"m",
".",
"group",
"(",
"2",
")",
")",
",",
"int",
"(",
"m",
".",
"group",
"(",
"3",
")",
")",
",",
"int",
"(",
"m",
".",
"group",
"(",
"4",
")",
")",
")",
"raise",
"ValueError",
"(",
"f\"unknown color specifier: {repr(color)}\"",
")"
] | [
24,
0
] | [
117,
63
] | python | en | ['en', 'error', 'th'] | False |
getcolor | (color, mode) |
Same as :py:func:`~PIL.ImageColor.getrgb`, but converts the RGB value to a
greyscale value if the mode is not color or a palette image. If the string
cannot be parsed, this function raises a :py:exc:`ValueError` exception.
.. versionadded:: 1.1.4
:param color: A color string
:return: ``(graylevel [, alpha]) or (red, green, blue[, alpha])``
|
Same as :py:func:`~PIL.ImageColor.getrgb`, but converts the RGB value to a
greyscale value if the mode is not color or a palette image. If the string
cannot be parsed, this function raises a :py:exc:`ValueError` exception. | def getcolor(color, mode):
"""
Same as :py:func:`~PIL.ImageColor.getrgb`, but converts the RGB value to a
greyscale value if the mode is not color or a palette image. If the string
cannot be parsed, this function raises a :py:exc:`ValueError` exception.
.. versionadded:: 1.1.4
:param color: A color string
:return: ``(graylevel [, alpha]) or (red, green, blue[, alpha])``
"""
# same as getrgb, but converts the result to the given mode
color, alpha = getrgb(color), 255
if len(color) == 4:
color, alpha = color[0:3], color[3]
if Image.getmodebase(mode) == "L":
r, g, b = color
# ITU-R Recommendation 601-2 for nonlinear RGB
# scaled to 24 bits to match the convert's implementation.
color = (r * 19595 + g * 38470 + b * 7471 + 0x8000) >> 16
if mode[-1] == "A":
return (color, alpha)
else:
if mode[-1] == "A":
return color + (alpha,)
return color | [
"def",
"getcolor",
"(",
"color",
",",
"mode",
")",
":",
"# same as getrgb, but converts the result to the given mode",
"color",
",",
"alpha",
"=",
"getrgb",
"(",
"color",
")",
",",
"255",
"if",
"len",
"(",
"color",
")",
"==",
"4",
":",
"color",
",",
"alpha",
"=",
"color",
"[",
"0",
":",
"3",
"]",
",",
"color",
"[",
"3",
"]",
"if",
"Image",
".",
"getmodebase",
"(",
"mode",
")",
"==",
"\"L\"",
":",
"r",
",",
"g",
",",
"b",
"=",
"color",
"# ITU-R Recommendation 601-2 for nonlinear RGB",
"# scaled to 24 bits to match the convert's implementation.",
"color",
"=",
"(",
"r",
"*",
"19595",
"+",
"g",
"*",
"38470",
"+",
"b",
"*",
"7471",
"+",
"0x8000",
")",
">>",
"16",
"if",
"mode",
"[",
"-",
"1",
"]",
"==",
"\"A\"",
":",
"return",
"(",
"color",
",",
"alpha",
")",
"else",
":",
"if",
"mode",
"[",
"-",
"1",
"]",
"==",
"\"A\"",
":",
"return",
"color",
"+",
"(",
"alpha",
",",
")",
"return",
"color"
] | [
120,
0
] | [
146,
16
] | python | en | ['en', 'error', 'th'] | False |
contextfilter | (f) | Decorator for marking context dependent filters. The current
:class:`Context` will be passed as first argument.
| Decorator for marking context dependent filters. The current
:class:`Context` will be passed as first argument.
| def contextfilter(f):
"""Decorator for marking context dependent filters. The current
:class:`Context` will be passed as first argument.
"""
f.contextfilter = True
return f | [
"def",
"contextfilter",
"(",
"f",
")",
":",
"f",
".",
"contextfilter",
"=",
"True",
"return",
"f"
] | [
28,
0
] | [
33,
12
] | python | en | ['en', 'en', 'en'] | True |
evalcontextfilter | (f) | Decorator for marking eval-context dependent filters. An eval
context object is passed as first argument. For more information
about the eval context, see :ref:`eval-context`.
.. versionadded:: 2.4
| Decorator for marking eval-context dependent filters. An eval
context object is passed as first argument. For more information
about the eval context, see :ref:`eval-context`. | def evalcontextfilter(f):
"""Decorator for marking eval-context dependent filters. An eval
context object is passed as first argument. For more information
about the eval context, see :ref:`eval-context`.
.. versionadded:: 2.4
"""
f.evalcontextfilter = True
return f | [
"def",
"evalcontextfilter",
"(",
"f",
")",
":",
"f",
".",
"evalcontextfilter",
"=",
"True",
"return",
"f"
] | [
36,
0
] | [
44,
12
] | python | en | ['da', 'en', 'en'] | True |
environmentfilter | (f) | Decorator for marking environment dependent filters. The current
:class:`Environment` is passed to the filter as first argument.
| Decorator for marking environment dependent filters. The current
:class:`Environment` is passed to the filter as first argument.
| def environmentfilter(f):
"""Decorator for marking environment dependent filters. The current
:class:`Environment` is passed to the filter as first argument.
"""
f.environmentfilter = True
return f | [
"def",
"environmentfilter",
"(",
"f",
")",
":",
"f",
".",
"environmentfilter",
"=",
"True",
"return",
"f"
] | [
47,
0
] | [
52,
12
] | python | en | ['en', 'en', 'en'] | True |
ignore_case | (value) | For use as a postprocessor for :func:`make_attrgetter`. Converts strings
to lowercase and returns other types as-is. | For use as a postprocessor for :func:`make_attrgetter`. Converts strings
to lowercase and returns other types as-is. | def ignore_case(value):
"""For use as a postprocessor for :func:`make_attrgetter`. Converts strings
to lowercase and returns other types as-is."""
return value.lower() if isinstance(value, string_types) else value | [
"def",
"ignore_case",
"(",
"value",
")",
":",
"return",
"value",
".",
"lower",
"(",
")",
"if",
"isinstance",
"(",
"value",
",",
"string_types",
")",
"else",
"value"
] | [
55,
0
] | [
58,
70
] | python | en | ['en', 'en', 'en'] | True |
make_attrgetter | (environment, attribute, postprocess=None) | Returns a callable that looks up the given attribute from a
passed object with the rules of the environment. Dots are allowed
to access attributes of attributes. Integer parts in paths are
looked up as integers.
| Returns a callable that looks up the given attribute from a
passed object with the rules of the environment. Dots are allowed
to access attributes of attributes. Integer parts in paths are
looked up as integers.
| def make_attrgetter(environment, attribute, postprocess=None):
"""Returns a callable that looks up the given attribute from a
passed object with the rules of the environment. Dots are allowed
to access attributes of attributes. Integer parts in paths are
looked up as integers.
"""
if attribute is None:
attribute = []
elif isinstance(attribute, string_types):
attribute = [int(x) if x.isdigit() else x for x in attribute.split('.')]
else:
attribute = [attribute]
def attrgetter(item):
for part in attribute:
item = environment.getitem(item, part)
if postprocess is not None:
item = postprocess(item)
return item
return attrgetter | [
"def",
"make_attrgetter",
"(",
"environment",
",",
"attribute",
",",
"postprocess",
"=",
"None",
")",
":",
"if",
"attribute",
"is",
"None",
":",
"attribute",
"=",
"[",
"]",
"elif",
"isinstance",
"(",
"attribute",
",",
"string_types",
")",
":",
"attribute",
"=",
"[",
"int",
"(",
"x",
")",
"if",
"x",
".",
"isdigit",
"(",
")",
"else",
"x",
"for",
"x",
"in",
"attribute",
".",
"split",
"(",
"'.'",
")",
"]",
"else",
":",
"attribute",
"=",
"[",
"attribute",
"]",
"def",
"attrgetter",
"(",
"item",
")",
":",
"for",
"part",
"in",
"attribute",
":",
"item",
"=",
"environment",
".",
"getitem",
"(",
"item",
",",
"part",
")",
"if",
"postprocess",
"is",
"not",
"None",
":",
"item",
"=",
"postprocess",
"(",
"item",
")",
"return",
"item",
"return",
"attrgetter"
] | [
61,
0
] | [
83,
21
] | python | en | ['en', 'en', 'en'] | True |
do_forceescape | (value) | Enforce HTML escaping. This will probably double escape variables. | Enforce HTML escaping. This will probably double escape variables. | def do_forceescape(value):
"""Enforce HTML escaping. This will probably double escape variables."""
if hasattr(value, '__html__'):
value = value.__html__()
return escape(text_type(value)) | [
"def",
"do_forceescape",
"(",
"value",
")",
":",
"if",
"hasattr",
"(",
"value",
",",
"'__html__'",
")",
":",
"value",
"=",
"value",
".",
"__html__",
"(",
")",
"return",
"escape",
"(",
"text_type",
"(",
"value",
")",
")"
] | [
86,
0
] | [
90,
35
] | python | en | ['en', 'en', 'en'] | True |
do_urlencode | (value) | Escape strings for use in URLs (uses UTF-8 encoding). It accepts both
dictionaries and regular strings as well as pairwise iterables.
.. versionadded:: 2.7
| Escape strings for use in URLs (uses UTF-8 encoding). It accepts both
dictionaries and regular strings as well as pairwise iterables. | def do_urlencode(value):
"""Escape strings for use in URLs (uses UTF-8 encoding). It accepts both
dictionaries and regular strings as well as pairwise iterables.
.. versionadded:: 2.7
"""
itemiter = None
if isinstance(value, dict):
itemiter = iteritems(value)
elif not isinstance(value, string_types):
try:
itemiter = iter(value)
except TypeError:
pass
if itemiter is None:
return unicode_urlencode(value)
return u'&'.join(unicode_urlencode(k) + '=' +
unicode_urlencode(v, for_qs=True)
for k, v in itemiter) | [
"def",
"do_urlencode",
"(",
"value",
")",
":",
"itemiter",
"=",
"None",
"if",
"isinstance",
"(",
"value",
",",
"dict",
")",
":",
"itemiter",
"=",
"iteritems",
"(",
"value",
")",
"elif",
"not",
"isinstance",
"(",
"value",
",",
"string_types",
")",
":",
"try",
":",
"itemiter",
"=",
"iter",
"(",
"value",
")",
"except",
"TypeError",
":",
"pass",
"if",
"itemiter",
"is",
"None",
":",
"return",
"unicode_urlencode",
"(",
"value",
")",
"return",
"u'&'",
".",
"join",
"(",
"unicode_urlencode",
"(",
"k",
")",
"+",
"'='",
"+",
"unicode_urlencode",
"(",
"v",
",",
"for_qs",
"=",
"True",
")",
"for",
"k",
",",
"v",
"in",
"itemiter",
")"
] | [
93,
0
] | [
111,
42
] | python | en | ['en', 'en', 'en'] | True |
do_replace | (eval_ctx, s, old, new, count=None) | Return a copy of the value with all occurrences of a substring
replaced with a new one. The first argument is the substring
that should be replaced, the second is the replacement string.
If the optional third argument ``count`` is given, only the first
``count`` occurrences are replaced:
.. sourcecode:: jinja
{{ "Hello World"|replace("Hello", "Goodbye") }}
-> Goodbye World
{{ "aaaaargh"|replace("a", "d'oh, ", 2) }}
-> d'oh, d'oh, aaargh
| Return a copy of the value with all occurrences of a substring
replaced with a new one. The first argument is the substring
that should be replaced, the second is the replacement string.
If the optional third argument ``count`` is given, only the first
``count`` occurrences are replaced: | def do_replace(eval_ctx, s, old, new, count=None):
"""Return a copy of the value with all occurrences of a substring
replaced with a new one. The first argument is the substring
that should be replaced, the second is the replacement string.
If the optional third argument ``count`` is given, only the first
``count`` occurrences are replaced:
.. sourcecode:: jinja
{{ "Hello World"|replace("Hello", "Goodbye") }}
-> Goodbye World
{{ "aaaaargh"|replace("a", "d'oh, ", 2) }}
-> d'oh, d'oh, aaargh
"""
if count is None:
count = -1
if not eval_ctx.autoescape:
return text_type(s).replace(text_type(old), text_type(new), count)
if hasattr(old, '__html__') or hasattr(new, '__html__') and \
not hasattr(s, '__html__'):
s = escape(s)
else:
s = soft_unicode(s)
return s.replace(soft_unicode(old), soft_unicode(new), count) | [
"def",
"do_replace",
"(",
"eval_ctx",
",",
"s",
",",
"old",
",",
"new",
",",
"count",
"=",
"None",
")",
":",
"if",
"count",
"is",
"None",
":",
"count",
"=",
"-",
"1",
"if",
"not",
"eval_ctx",
".",
"autoescape",
":",
"return",
"text_type",
"(",
"s",
")",
".",
"replace",
"(",
"text_type",
"(",
"old",
")",
",",
"text_type",
"(",
"new",
")",
",",
"count",
")",
"if",
"hasattr",
"(",
"old",
",",
"'__html__'",
")",
"or",
"hasattr",
"(",
"new",
",",
"'__html__'",
")",
"and",
"not",
"hasattr",
"(",
"s",
",",
"'__html__'",
")",
":",
"s",
"=",
"escape",
"(",
"s",
")",
"else",
":",
"s",
"=",
"soft_unicode",
"(",
"s",
")",
"return",
"s",
".",
"replace",
"(",
"soft_unicode",
"(",
"old",
")",
",",
"soft_unicode",
"(",
"new",
")",
",",
"count",
")"
] | [
115,
0
] | [
139,
65
] | python | en | ['en', 'en', 'en'] | True |
do_upper | (s) | Convert a value to uppercase. | Convert a value to uppercase. | def do_upper(s):
"""Convert a value to uppercase."""
return soft_unicode(s).upper() | [
"def",
"do_upper",
"(",
"s",
")",
":",
"return",
"soft_unicode",
"(",
"s",
")",
".",
"upper",
"(",
")"
] | [
142,
0
] | [
144,
34
] | python | en | ['en', 'en', 'en'] | True |
do_lower | (s) | Convert a value to lowercase. | Convert a value to lowercase. | def do_lower(s):
"""Convert a value to lowercase."""
return soft_unicode(s).lower() | [
"def",
"do_lower",
"(",
"s",
")",
":",
"return",
"soft_unicode",
"(",
"s",
")",
".",
"lower",
"(",
")"
] | [
147,
0
] | [
149,
34
] | python | en | ['en', 'en', 'en'] | True |
do_xmlattr | (_eval_ctx, d, autospace=True) | Create an SGML/XML attribute string based on the items in a dict.
All values that are neither `none` nor `undefined` are automatically
escaped:
.. sourcecode:: html+jinja
<ul{{ {'class': 'my_list', 'missing': none,
'id': 'list-%d'|format(variable)}|xmlattr }}>
...
</ul>
Results in something like this:
.. sourcecode:: html
<ul class="my_list" id="list-42">
...
</ul>
As you can see it automatically prepends a space in front of the item
if the filter returned something unless the second parameter is false.
| Create an SGML/XML attribute string based on the items in a dict.
All values that are neither `none` nor `undefined` are automatically
escaped: | def do_xmlattr(_eval_ctx, d, autospace=True):
"""Create an SGML/XML attribute string based on the items in a dict.
All values that are neither `none` nor `undefined` are automatically
escaped:
.. sourcecode:: html+jinja
<ul{{ {'class': 'my_list', 'missing': none,
'id': 'list-%d'|format(variable)}|xmlattr }}>
...
</ul>
Results in something like this:
.. sourcecode:: html
<ul class="my_list" id="list-42">
...
</ul>
As you can see it automatically prepends a space in front of the item
if the filter returned something unless the second parameter is false.
"""
rv = u' '.join(
u'%s="%s"' % (escape(key), escape(value))
for key, value in iteritems(d)
if value is not None and not isinstance(value, Undefined)
)
if autospace and rv:
rv = u' ' + rv
if _eval_ctx.autoescape:
rv = Markup(rv)
return rv | [
"def",
"do_xmlattr",
"(",
"_eval_ctx",
",",
"d",
",",
"autospace",
"=",
"True",
")",
":",
"rv",
"=",
"u' '",
".",
"join",
"(",
"u'%s=\"%s\"'",
"%",
"(",
"escape",
"(",
"key",
")",
",",
"escape",
"(",
"value",
")",
")",
"for",
"key",
",",
"value",
"in",
"iteritems",
"(",
"d",
")",
"if",
"value",
"is",
"not",
"None",
"and",
"not",
"isinstance",
"(",
"value",
",",
"Undefined",
")",
")",
"if",
"autospace",
"and",
"rv",
":",
"rv",
"=",
"u' '",
"+",
"rv",
"if",
"_eval_ctx",
".",
"autoescape",
":",
"rv",
"=",
"Markup",
"(",
"rv",
")",
"return",
"rv"
] | [
153,
0
] | [
185,
13
] | python | en | ['en', 'en', 'en'] | True |
do_capitalize | (s) | Capitalize a value. The first character will be uppercase, all others
lowercase.
| Capitalize a value. The first character will be uppercase, all others
lowercase.
| def do_capitalize(s):
"""Capitalize a value. The first character will be uppercase, all others
lowercase.
"""
return soft_unicode(s).capitalize() | [
"def",
"do_capitalize",
"(",
"s",
")",
":",
"return",
"soft_unicode",
"(",
"s",
")",
".",
"capitalize",
"(",
")"
] | [
188,
0
] | [
192,
39
] | python | en | ['en', 'en', 'en'] | True |
do_title | (s) | Return a titlecased version of the value. I.e. words will start with
uppercase letters, all remaining characters are lowercase.
| Return a titlecased version of the value. I.e. words will start with
uppercase letters, all remaining characters are lowercase.
| def do_title(s):
"""Return a titlecased version of the value. I.e. words will start with
uppercase letters, all remaining characters are lowercase.
"""
return ''.join(
[item[0].upper() + item[1:].lower()
for item in _word_beginning_split_re.split(soft_unicode(s))
if item]) | [
"def",
"do_title",
"(",
"s",
")",
":",
"return",
"''",
".",
"join",
"(",
"[",
"item",
"[",
"0",
"]",
".",
"upper",
"(",
")",
"+",
"item",
"[",
"1",
":",
"]",
".",
"lower",
"(",
")",
"for",
"item",
"in",
"_word_beginning_split_re",
".",
"split",
"(",
"soft_unicode",
"(",
"s",
")",
")",
"if",
"item",
"]",
")"
] | [
195,
0
] | [
202,
18
] | python | en | ['en', 'en', 'en'] | True |
do_dictsort | (value, case_sensitive=False, by='key', reverse=False) | Sort a dict and yield (key, value) pairs. Because python dicts are
unsorted you may want to use this function to order them by either
key or value:
.. sourcecode:: jinja
{% for item in mydict|dictsort %}
sort the dict by key, case insensitive
{% for item in mydict|dictsort(reverse=true) %}
sort the dict by key, case insensitive, reverse order
{% for item in mydict|dictsort(true) %}
sort the dict by key, case sensitive
{% for item in mydict|dictsort(false, 'value') %}
sort the dict by value, case insensitive
| Sort a dict and yield (key, value) pairs. Because python dicts are
unsorted you may want to use this function to order them by either
key or value: | def do_dictsort(value, case_sensitive=False, by='key', reverse=False):
"""Sort a dict and yield (key, value) pairs. Because python dicts are
unsorted you may want to use this function to order them by either
key or value:
.. sourcecode:: jinja
{% for item in mydict|dictsort %}
sort the dict by key, case insensitive
{% for item in mydict|dictsort(reverse=true) %}
sort the dict by key, case insensitive, reverse order
{% for item in mydict|dictsort(true) %}
sort the dict by key, case sensitive
{% for item in mydict|dictsort(false, 'value') %}
sort the dict by value, case insensitive
"""
if by == 'key':
pos = 0
elif by == 'value':
pos = 1
else:
raise FilterArgumentError(
'You can only sort by either "key" or "value"'
)
def sort_func(item):
value = item[pos]
if not case_sensitive:
value = ignore_case(value)
return value
return sorted(value.items(), key=sort_func, reverse=reverse) | [
"def",
"do_dictsort",
"(",
"value",
",",
"case_sensitive",
"=",
"False",
",",
"by",
"=",
"'key'",
",",
"reverse",
"=",
"False",
")",
":",
"if",
"by",
"==",
"'key'",
":",
"pos",
"=",
"0",
"elif",
"by",
"==",
"'value'",
":",
"pos",
"=",
"1",
"else",
":",
"raise",
"FilterArgumentError",
"(",
"'You can only sort by either \"key\" or \"value\"'",
")",
"def",
"sort_func",
"(",
"item",
")",
":",
"value",
"=",
"item",
"[",
"pos",
"]",
"if",
"not",
"case_sensitive",
":",
"value",
"=",
"ignore_case",
"(",
"value",
")",
"return",
"value",
"return",
"sorted",
"(",
"value",
".",
"items",
"(",
")",
",",
"key",
"=",
"sort_func",
",",
"reverse",
"=",
"reverse",
")"
] | [
205,
0
] | [
241,
64
] | python | en | ['en', 'en', 'en'] | True |
do_sort | (
environment, value, reverse=False, case_sensitive=False, attribute=None
) | Sort an iterable. Per default it sorts ascending, if you pass it
true as first argument it will reverse the sorting.
If the iterable is made of strings the third parameter can be used to
control the case sensitiveness of the comparison which is disabled by
default.
.. sourcecode:: jinja
{% for item in iterable|sort %}
...
{% endfor %}
It is also possible to sort by an attribute (for example to sort
by the date of an object) by specifying the `attribute` parameter:
.. sourcecode:: jinja
{% for item in iterable|sort(attribute='date') %}
...
{% endfor %}
.. versionchanged:: 2.6
The `attribute` parameter was added.
| Sort an iterable. Per default it sorts ascending, if you pass it
true as first argument it will reverse the sorting. | def do_sort(
environment, value, reverse=False, case_sensitive=False, attribute=None
):
"""Sort an iterable. Per default it sorts ascending, if you pass it
true as first argument it will reverse the sorting.
If the iterable is made of strings the third parameter can be used to
control the case sensitiveness of the comparison which is disabled by
default.
.. sourcecode:: jinja
{% for item in iterable|sort %}
...
{% endfor %}
It is also possible to sort by an attribute (for example to sort
by the date of an object) by specifying the `attribute` parameter:
.. sourcecode:: jinja
{% for item in iterable|sort(attribute='date') %}
...
{% endfor %}
.. versionchanged:: 2.6
The `attribute` parameter was added.
"""
key_func = make_attrgetter(
environment, attribute,
postprocess=ignore_case if not case_sensitive else None
)
return sorted(value, key=key_func, reverse=reverse) | [
"def",
"do_sort",
"(",
"environment",
",",
"value",
",",
"reverse",
"=",
"False",
",",
"case_sensitive",
"=",
"False",
",",
"attribute",
"=",
"None",
")",
":",
"key_func",
"=",
"make_attrgetter",
"(",
"environment",
",",
"attribute",
",",
"postprocess",
"=",
"ignore_case",
"if",
"not",
"case_sensitive",
"else",
"None",
")",
"return",
"sorted",
"(",
"value",
",",
"key",
"=",
"key_func",
",",
"reverse",
"=",
"reverse",
")"
] | [
245,
0
] | [
277,
55
] | python | en | ['en', 'en', 'en'] | True |
do_unique | (environment, value, case_sensitive=False, attribute=None) | Returns a list of unique items from the the given iterable.
.. sourcecode:: jinja
{{ ['foo', 'bar', 'foobar', 'FooBar']|unique }}
-> ['foo', 'bar', 'foobar']
The unique items are yielded in the same order as their first occurrence in
the iterable passed to the filter.
:param case_sensitive: Treat upper and lower case strings as distinct.
:param attribute: Filter objects with unique values for this attribute.
| Returns a list of unique items from the the given iterable. | def do_unique(environment, value, case_sensitive=False, attribute=None):
"""Returns a list of unique items from the the given iterable.
.. sourcecode:: jinja
{{ ['foo', 'bar', 'foobar', 'FooBar']|unique }}
-> ['foo', 'bar', 'foobar']
The unique items are yielded in the same order as their first occurrence in
the iterable passed to the filter.
:param case_sensitive: Treat upper and lower case strings as distinct.
:param attribute: Filter objects with unique values for this attribute.
"""
getter = make_attrgetter(
environment, attribute,
postprocess=ignore_case if not case_sensitive else None
)
seen = set()
for item in value:
key = getter(item)
if key not in seen:
seen.add(key)
yield item | [
"def",
"do_unique",
"(",
"environment",
",",
"value",
",",
"case_sensitive",
"=",
"False",
",",
"attribute",
"=",
"None",
")",
":",
"getter",
"=",
"make_attrgetter",
"(",
"environment",
",",
"attribute",
",",
"postprocess",
"=",
"ignore_case",
"if",
"not",
"case_sensitive",
"else",
"None",
")",
"seen",
"=",
"set",
"(",
")",
"for",
"item",
"in",
"value",
":",
"key",
"=",
"getter",
"(",
"item",
")",
"if",
"key",
"not",
"in",
"seen",
":",
"seen",
".",
"add",
"(",
"key",
")",
"yield",
"item"
] | [
281,
0
] | [
306,
22
] | python | en | ['en', 'en', 'en'] | True |
do_min | (environment, value, case_sensitive=False, attribute=None) | Return the smallest item from the sequence.
.. sourcecode:: jinja
{{ [1, 2, 3]|min }}
-> 1
:param case_sensitive: Treat upper and lower case strings as distinct.
:param attribute: Get the object with the max value of this attribute.
| Return the smallest item from the sequence. | def do_min(environment, value, case_sensitive=False, attribute=None):
"""Return the smallest item from the sequence.
.. sourcecode:: jinja
{{ [1, 2, 3]|min }}
-> 1
:param case_sensitive: Treat upper and lower case strings as distinct.
:param attribute: Get the object with the max value of this attribute.
"""
return _min_or_max(environment, value, min, case_sensitive, attribute) | [
"def",
"do_min",
"(",
"environment",
",",
"value",
",",
"case_sensitive",
"=",
"False",
",",
"attribute",
"=",
"None",
")",
":",
"return",
"_min_or_max",
"(",
"environment",
",",
"value",
",",
"min",
",",
"case_sensitive",
",",
"attribute",
")"
] | [
325,
0
] | [
336,
74
] | python | en | ['en', 'en', 'en'] | True |
do_max | (environment, value, case_sensitive=False, attribute=None) | Return the largest item from the sequence.
.. sourcecode:: jinja
{{ [1, 2, 3]|max }}
-> 3
:param case_sensitive: Treat upper and lower case strings as distinct.
:param attribute: Get the object with the max value of this attribute.
| Return the largest item from the sequence. | def do_max(environment, value, case_sensitive=False, attribute=None):
"""Return the largest item from the sequence.
.. sourcecode:: jinja
{{ [1, 2, 3]|max }}
-> 3
:param case_sensitive: Treat upper and lower case strings as distinct.
:param attribute: Get the object with the max value of this attribute.
"""
return _min_or_max(environment, value, max, case_sensitive, attribute) | [
"def",
"do_max",
"(",
"environment",
",",
"value",
",",
"case_sensitive",
"=",
"False",
",",
"attribute",
"=",
"None",
")",
":",
"return",
"_min_or_max",
"(",
"environment",
",",
"value",
",",
"max",
",",
"case_sensitive",
",",
"attribute",
")"
] | [
340,
0
] | [
351,
74
] | python | en | ['en', 'en', 'en'] | True |
do_default | (value, default_value=u'', boolean=False) | If the value is undefined it will return the passed default value,
otherwise the value of the variable:
.. sourcecode:: jinja
{{ my_variable|default('my_variable is not defined') }}
This will output the value of ``my_variable`` if the variable was
defined, otherwise ``'my_variable is not defined'``. If you want
to use default with variables that evaluate to false you have to
set the second parameter to `true`:
.. sourcecode:: jinja
{{ ''|default('the string was empty', true) }}
| If the value is undefined it will return the passed default value,
otherwise the value of the variable: | def do_default(value, default_value=u'', boolean=False):
"""If the value is undefined it will return the passed default value,
otherwise the value of the variable:
.. sourcecode:: jinja
{{ my_variable|default('my_variable is not defined') }}
This will output the value of ``my_variable`` if the variable was
defined, otherwise ``'my_variable is not defined'``. If you want
to use default with variables that evaluate to false you have to
set the second parameter to `true`:
.. sourcecode:: jinja
{{ ''|default('the string was empty', true) }}
"""
if isinstance(value, Undefined) or (boolean and not value):
return default_value
return value | [
"def",
"do_default",
"(",
"value",
",",
"default_value",
"=",
"u''",
",",
"boolean",
"=",
"False",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"Undefined",
")",
"or",
"(",
"boolean",
"and",
"not",
"value",
")",
":",
"return",
"default_value",
"return",
"value"
] | [
354,
0
] | [
373,
16
] | python | en | ['en', 'en', 'en'] | True |
do_join | (eval_ctx, value, d=u'', attribute=None) | Return a string which is the concatenation of the strings in the
sequence. The separator between elements is an empty string per
default, you can define it with the optional parameter:
.. sourcecode:: jinja
{{ [1, 2, 3]|join('|') }}
-> 1|2|3
{{ [1, 2, 3]|join }}
-> 123
It is also possible to join certain attributes of an object:
.. sourcecode:: jinja
{{ users|join(', ', attribute='username') }}
.. versionadded:: 2.6
The `attribute` parameter was added.
| Return a string which is the concatenation of the strings in the
sequence. The separator between elements is an empty string per
default, you can define it with the optional parameter: | def do_join(eval_ctx, value, d=u'', attribute=None):
"""Return a string which is the concatenation of the strings in the
sequence. The separator between elements is an empty string per
default, you can define it with the optional parameter:
.. sourcecode:: jinja
{{ [1, 2, 3]|join('|') }}
-> 1|2|3
{{ [1, 2, 3]|join }}
-> 123
It is also possible to join certain attributes of an object:
.. sourcecode:: jinja
{{ users|join(', ', attribute='username') }}
.. versionadded:: 2.6
The `attribute` parameter was added.
"""
if attribute is not None:
value = imap(make_attrgetter(eval_ctx.environment, attribute), value)
# no automatic escaping? joining is a lot eaiser then
if not eval_ctx.autoescape:
return text_type(d).join(imap(text_type, value))
# if the delimiter doesn't have an html representation we check
# if any of the items has. If yes we do a coercion to Markup
if not hasattr(d, '__html__'):
value = list(value)
do_escape = False
for idx, item in enumerate(value):
if hasattr(item, '__html__'):
do_escape = True
else:
value[idx] = text_type(item)
if do_escape:
d = escape(d)
else:
d = text_type(d)
return d.join(value)
# no html involved, to normal joining
return soft_unicode(d).join(imap(soft_unicode, value)) | [
"def",
"do_join",
"(",
"eval_ctx",
",",
"value",
",",
"d",
"=",
"u''",
",",
"attribute",
"=",
"None",
")",
":",
"if",
"attribute",
"is",
"not",
"None",
":",
"value",
"=",
"imap",
"(",
"make_attrgetter",
"(",
"eval_ctx",
".",
"environment",
",",
"attribute",
")",
",",
"value",
")",
"# no automatic escaping? joining is a lot eaiser then",
"if",
"not",
"eval_ctx",
".",
"autoescape",
":",
"return",
"text_type",
"(",
"d",
")",
".",
"join",
"(",
"imap",
"(",
"text_type",
",",
"value",
")",
")",
"# if the delimiter doesn't have an html representation we check",
"# if any of the items has. If yes we do a coercion to Markup",
"if",
"not",
"hasattr",
"(",
"d",
",",
"'__html__'",
")",
":",
"value",
"=",
"list",
"(",
"value",
")",
"do_escape",
"=",
"False",
"for",
"idx",
",",
"item",
"in",
"enumerate",
"(",
"value",
")",
":",
"if",
"hasattr",
"(",
"item",
",",
"'__html__'",
")",
":",
"do_escape",
"=",
"True",
"else",
":",
"value",
"[",
"idx",
"]",
"=",
"text_type",
"(",
"item",
")",
"if",
"do_escape",
":",
"d",
"=",
"escape",
"(",
"d",
")",
"else",
":",
"d",
"=",
"text_type",
"(",
"d",
")",
"return",
"d",
".",
"join",
"(",
"value",
")",
"# no html involved, to normal joining",
"return",
"soft_unicode",
"(",
"d",
")",
".",
"join",
"(",
"imap",
"(",
"soft_unicode",
",",
"value",
")",
")"
] | [
377,
0
] | [
423,
58
] | python | en | ['en', 'en', 'en'] | True |
do_center | (value, width=80) | Centers the value in a field of a given width. | Centers the value in a field of a given width. | def do_center(value, width=80):
"""Centers the value in a field of a given width."""
return text_type(value).center(width) | [
"def",
"do_center",
"(",
"value",
",",
"width",
"=",
"80",
")",
":",
"return",
"text_type",
"(",
"value",
")",
".",
"center",
"(",
"width",
")"
] | [
426,
0
] | [
428,
41
] | python | en | ['en', 'en', 'en'] | True |
do_first | (environment, seq) | Return the first item of a sequence. | Return the first item of a sequence. | def do_first(environment, seq):
"""Return the first item of a sequence."""
try:
return next(iter(seq))
except StopIteration:
return environment.undefined('No first item, sequence was empty.') | [
"def",
"do_first",
"(",
"environment",
",",
"seq",
")",
":",
"try",
":",
"return",
"next",
"(",
"iter",
"(",
"seq",
")",
")",
"except",
"StopIteration",
":",
"return",
"environment",
".",
"undefined",
"(",
"'No first item, sequence was empty.'",
")"
] | [
432,
0
] | [
437,
74
] | python | en | ['en', 'en', 'en'] | True |
do_last | (environment, seq) | Return the last item of a sequence. | Return the last item of a sequence. | def do_last(environment, seq):
"""Return the last item of a sequence."""
try:
return next(iter(reversed(seq)))
except StopIteration:
return environment.undefined('No last item, sequence was empty.') | [
"def",
"do_last",
"(",
"environment",
",",
"seq",
")",
":",
"try",
":",
"return",
"next",
"(",
"iter",
"(",
"reversed",
"(",
"seq",
")",
")",
")",
"except",
"StopIteration",
":",
"return",
"environment",
".",
"undefined",
"(",
"'No last item, sequence was empty.'",
")"
] | [
441,
0
] | [
446,
73
] | python | en | ['en', 'en', 'en'] | True |
do_random | (context, seq) | Return a random item from the sequence. | Return a random item from the sequence. | def do_random(context, seq):
"""Return a random item from the sequence."""
try:
return random.choice(seq)
except IndexError:
return context.environment.undefined('No random item, sequence was empty.') | [
"def",
"do_random",
"(",
"context",
",",
"seq",
")",
":",
"try",
":",
"return",
"random",
".",
"choice",
"(",
"seq",
")",
"except",
"IndexError",
":",
"return",
"context",
".",
"environment",
".",
"undefined",
"(",
"'No random item, sequence was empty.'",
")"
] | [
450,
0
] | [
455,
83
] | python | en | ['en', 'en', 'en'] | True |
do_filesizeformat | (value, binary=False) | Format the value like a 'human-readable' file size (i.e. 13 kB,
4.1 MB, 102 Bytes, etc). Per default decimal prefixes are used (Mega,
Giga, etc.), if the second parameter is set to `True` the binary
prefixes are used (Mebi, Gibi).
| Format the value like a 'human-readable' file size (i.e. 13 kB,
4.1 MB, 102 Bytes, etc). Per default decimal prefixes are used (Mega,
Giga, etc.), if the second parameter is set to `True` the binary
prefixes are used (Mebi, Gibi).
| def do_filesizeformat(value, binary=False):
"""Format the value like a 'human-readable' file size (i.e. 13 kB,
4.1 MB, 102 Bytes, etc). Per default decimal prefixes are used (Mega,
Giga, etc.), if the second parameter is set to `True` the binary
prefixes are used (Mebi, Gibi).
"""
bytes = float(value)
base = binary and 1024 or 1000
prefixes = [
(binary and 'KiB' or 'kB'),
(binary and 'MiB' or 'MB'),
(binary and 'GiB' or 'GB'),
(binary and 'TiB' or 'TB'),
(binary and 'PiB' or 'PB'),
(binary and 'EiB' or 'EB'),
(binary and 'ZiB' or 'ZB'),
(binary and 'YiB' or 'YB')
]
if bytes == 1:
return '1 Byte'
elif bytes < base:
return '%d Bytes' % bytes
else:
for i, prefix in enumerate(prefixes):
unit = base ** (i + 2)
if bytes < unit:
return '%.1f %s' % ((base * bytes / unit), prefix)
return '%.1f %s' % ((base * bytes / unit), prefix) | [
"def",
"do_filesizeformat",
"(",
"value",
",",
"binary",
"=",
"False",
")",
":",
"bytes",
"=",
"float",
"(",
"value",
")",
"base",
"=",
"binary",
"and",
"1024",
"or",
"1000",
"prefixes",
"=",
"[",
"(",
"binary",
"and",
"'KiB'",
"or",
"'kB'",
")",
",",
"(",
"binary",
"and",
"'MiB'",
"or",
"'MB'",
")",
",",
"(",
"binary",
"and",
"'GiB'",
"or",
"'GB'",
")",
",",
"(",
"binary",
"and",
"'TiB'",
"or",
"'TB'",
")",
",",
"(",
"binary",
"and",
"'PiB'",
"or",
"'PB'",
")",
",",
"(",
"binary",
"and",
"'EiB'",
"or",
"'EB'",
")",
",",
"(",
"binary",
"and",
"'ZiB'",
"or",
"'ZB'",
")",
",",
"(",
"binary",
"and",
"'YiB'",
"or",
"'YB'",
")",
"]",
"if",
"bytes",
"==",
"1",
":",
"return",
"'1 Byte'",
"elif",
"bytes",
"<",
"base",
":",
"return",
"'%d Bytes'",
"%",
"bytes",
"else",
":",
"for",
"i",
",",
"prefix",
"in",
"enumerate",
"(",
"prefixes",
")",
":",
"unit",
"=",
"base",
"**",
"(",
"i",
"+",
"2",
")",
"if",
"bytes",
"<",
"unit",
":",
"return",
"'%.1f %s'",
"%",
"(",
"(",
"base",
"*",
"bytes",
"/",
"unit",
")",
",",
"prefix",
")",
"return",
"'%.1f %s'",
"%",
"(",
"(",
"base",
"*",
"bytes",
"/",
"unit",
")",
",",
"prefix",
")"
] | [
458,
0
] | [
485,
58
] | python | en | ['en', 'sm', 'en'] | True |
do_pprint | (value, verbose=False) | Pretty print a variable. Useful for debugging.
With Jinja 1.2 onwards you can pass it a parameter. If this parameter
is truthy the output will be more verbose (this requires `pretty`)
| Pretty print a variable. Useful for debugging. | def do_pprint(value, verbose=False):
"""Pretty print a variable. Useful for debugging.
With Jinja 1.2 onwards you can pass it a parameter. If this parameter
is truthy the output will be more verbose (this requires `pretty`)
"""
return pformat(value, verbose=verbose) | [
"def",
"do_pprint",
"(",
"value",
",",
"verbose",
"=",
"False",
")",
":",
"return",
"pformat",
"(",
"value",
",",
"verbose",
"=",
"verbose",
")"
] | [
488,
0
] | [
494,
42
] | python | en | ['en', 'en', 'en'] | True |
do_urlize | (eval_ctx, value, trim_url_limit=None, nofollow=False,
target=None, rel=None) | Converts URLs in plain text into clickable links.
If you pass the filter an additional integer it will shorten the urls
to that number. Also a third argument exists that makes the urls
"nofollow":
.. sourcecode:: jinja
{{ mytext|urlize(40, true) }}
links are shortened to 40 chars and defined with rel="nofollow"
If *target* is specified, the ``target`` attribute will be added to the
``<a>`` tag:
.. sourcecode:: jinja
{{ mytext|urlize(40, target='_blank') }}
.. versionchanged:: 2.8+
The *target* parameter was added.
| Converts URLs in plain text into clickable links. | def do_urlize(eval_ctx, value, trim_url_limit=None, nofollow=False,
target=None, rel=None):
"""Converts URLs in plain text into clickable links.
If you pass the filter an additional integer it will shorten the urls
to that number. Also a third argument exists that makes the urls
"nofollow":
.. sourcecode:: jinja
{{ mytext|urlize(40, true) }}
links are shortened to 40 chars and defined with rel="nofollow"
If *target* is specified, the ``target`` attribute will be added to the
``<a>`` tag:
.. sourcecode:: jinja
{{ mytext|urlize(40, target='_blank') }}
.. versionchanged:: 2.8+
The *target* parameter was added.
"""
policies = eval_ctx.environment.policies
rel = set((rel or '').split() or [])
if nofollow:
rel.add('nofollow')
rel.update((policies['urlize.rel'] or '').split())
if target is None:
target = policies['urlize.target']
rel = ' '.join(sorted(rel)) or None
rv = urlize(value, trim_url_limit, rel=rel, target=target)
if eval_ctx.autoescape:
rv = Markup(rv)
return rv | [
"def",
"do_urlize",
"(",
"eval_ctx",
",",
"value",
",",
"trim_url_limit",
"=",
"None",
",",
"nofollow",
"=",
"False",
",",
"target",
"=",
"None",
",",
"rel",
"=",
"None",
")",
":",
"policies",
"=",
"eval_ctx",
".",
"environment",
".",
"policies",
"rel",
"=",
"set",
"(",
"(",
"rel",
"or",
"''",
")",
".",
"split",
"(",
")",
"or",
"[",
"]",
")",
"if",
"nofollow",
":",
"rel",
".",
"add",
"(",
"'nofollow'",
")",
"rel",
".",
"update",
"(",
"(",
"policies",
"[",
"'urlize.rel'",
"]",
"or",
"''",
")",
".",
"split",
"(",
")",
")",
"if",
"target",
"is",
"None",
":",
"target",
"=",
"policies",
"[",
"'urlize.target'",
"]",
"rel",
"=",
"' '",
".",
"join",
"(",
"sorted",
"(",
"rel",
")",
")",
"or",
"None",
"rv",
"=",
"urlize",
"(",
"value",
",",
"trim_url_limit",
",",
"rel",
"=",
"rel",
",",
"target",
"=",
"target",
")",
"if",
"eval_ctx",
".",
"autoescape",
":",
"rv",
"=",
"Markup",
"(",
"rv",
")",
"return",
"rv"
] | [
498,
0
] | [
532,
13
] | python | en | ['en', 'en', 'en'] | True |
do_indent | (
s, width=4, first=False, blank=False, indentfirst=None
) | Return a copy of the string with each line indented by 4 spaces. The
first line and blank lines are not indented by default.
:param width: Number of spaces to indent by.
:param first: Don't skip indenting the first line.
:param blank: Don't skip indenting empty lines.
.. versionchanged:: 2.10
Blank lines are not indented by default.
Rename the ``indentfirst`` argument to ``first``.
| Return a copy of the string with each line indented by 4 spaces. The
first line and blank lines are not indented by default. | def do_indent(
s, width=4, first=False, blank=False, indentfirst=None
):
"""Return a copy of the string with each line indented by 4 spaces. The
first line and blank lines are not indented by default.
:param width: Number of spaces to indent by.
:param first: Don't skip indenting the first line.
:param blank: Don't skip indenting empty lines.
.. versionchanged:: 2.10
Blank lines are not indented by default.
Rename the ``indentfirst`` argument to ``first``.
"""
if indentfirst is not None:
warnings.warn(DeprecationWarning(
'The "indentfirst" argument is renamed to "first".'
), stacklevel=2)
first = indentfirst
s += u'\n' # this quirk is necessary for splitlines method
indention = u' ' * width
if blank:
rv = (u'\n' + indention).join(s.splitlines())
else:
lines = s.splitlines()
rv = lines.pop(0)
if lines:
rv += u'\n' + u'\n'.join(
indention + line if line else line for line in lines
)
if first:
rv = indention + rv
return rv | [
"def",
"do_indent",
"(",
"s",
",",
"width",
"=",
"4",
",",
"first",
"=",
"False",
",",
"blank",
"=",
"False",
",",
"indentfirst",
"=",
"None",
")",
":",
"if",
"indentfirst",
"is",
"not",
"None",
":",
"warnings",
".",
"warn",
"(",
"DeprecationWarning",
"(",
"'The \"indentfirst\" argument is renamed to \"first\".'",
")",
",",
"stacklevel",
"=",
"2",
")",
"first",
"=",
"indentfirst",
"s",
"+=",
"u'\\n'",
"# this quirk is necessary for splitlines method",
"indention",
"=",
"u' '",
"*",
"width",
"if",
"blank",
":",
"rv",
"=",
"(",
"u'\\n'",
"+",
"indention",
")",
".",
"join",
"(",
"s",
".",
"splitlines",
"(",
")",
")",
"else",
":",
"lines",
"=",
"s",
".",
"splitlines",
"(",
")",
"rv",
"=",
"lines",
".",
"pop",
"(",
"0",
")",
"if",
"lines",
":",
"rv",
"+=",
"u'\\n'",
"+",
"u'\\n'",
".",
"join",
"(",
"indention",
"+",
"line",
"if",
"line",
"else",
"line",
"for",
"line",
"in",
"lines",
")",
"if",
"first",
":",
"rv",
"=",
"indention",
"+",
"rv",
"return",
"rv"
] | [
535,
0
] | [
573,
13
] | python | en | ['en', 'en', 'en'] | True |
do_truncate | (env, s, length=255, killwords=False, end='...', leeway=None) | Return a truncated copy of the string. The length is specified
with the first parameter which defaults to ``255``. If the second
parameter is ``true`` the filter will cut the text at length. Otherwise
it will discard the last word. If the text was in fact
truncated it will append an ellipsis sign (``"..."``). If you want a
different ellipsis sign than ``"..."`` you can specify it using the
third parameter. Strings that only exceed the length by the tolerance
margin given in the fourth parameter will not be truncated.
.. sourcecode:: jinja
{{ "foo bar baz qux"|truncate(9) }}
-> "foo..."
{{ "foo bar baz qux"|truncate(9, True) }}
-> "foo ba..."
{{ "foo bar baz qux"|truncate(11) }}
-> "foo bar baz qux"
{{ "foo bar baz qux"|truncate(11, False, '...', 0) }}
-> "foo bar..."
The default leeway on newer Jinja2 versions is 5 and was 0 before but
can be reconfigured globally.
| Return a truncated copy of the string. The length is specified
with the first parameter which defaults to ``255``. If the second
parameter is ``true`` the filter will cut the text at length. Otherwise
it will discard the last word. If the text was in fact
truncated it will append an ellipsis sign (``"..."``). If you want a
different ellipsis sign than ``"..."`` you can specify it using the
third parameter. Strings that only exceed the length by the tolerance
margin given in the fourth parameter will not be truncated. | def do_truncate(env, s, length=255, killwords=False, end='...', leeway=None):
"""Return a truncated copy of the string. The length is specified
with the first parameter which defaults to ``255``. If the second
parameter is ``true`` the filter will cut the text at length. Otherwise
it will discard the last word. If the text was in fact
truncated it will append an ellipsis sign (``"..."``). If you want a
different ellipsis sign than ``"..."`` you can specify it using the
third parameter. Strings that only exceed the length by the tolerance
margin given in the fourth parameter will not be truncated.
.. sourcecode:: jinja
{{ "foo bar baz qux"|truncate(9) }}
-> "foo..."
{{ "foo bar baz qux"|truncate(9, True) }}
-> "foo ba..."
{{ "foo bar baz qux"|truncate(11) }}
-> "foo bar baz qux"
{{ "foo bar baz qux"|truncate(11, False, '...', 0) }}
-> "foo bar..."
The default leeway on newer Jinja2 versions is 5 and was 0 before but
can be reconfigured globally.
"""
if leeway is None:
leeway = env.policies['truncate.leeway']
assert length >= len(end), 'expected length >= %s, got %s' % (len(end), length)
assert leeway >= 0, 'expected leeway >= 0, got %s' % leeway
if len(s) <= length + leeway:
return s
if killwords:
return s[:length - len(end)] + end
result = s[:length - len(end)].rsplit(' ', 1)[0]
return result + end | [
"def",
"do_truncate",
"(",
"env",
",",
"s",
",",
"length",
"=",
"255",
",",
"killwords",
"=",
"False",
",",
"end",
"=",
"'...'",
",",
"leeway",
"=",
"None",
")",
":",
"if",
"leeway",
"is",
"None",
":",
"leeway",
"=",
"env",
".",
"policies",
"[",
"'truncate.leeway'",
"]",
"assert",
"length",
">=",
"len",
"(",
"end",
")",
",",
"'expected length >= %s, got %s'",
"%",
"(",
"len",
"(",
"end",
")",
",",
"length",
")",
"assert",
"leeway",
">=",
"0",
",",
"'expected leeway >= 0, got %s'",
"%",
"leeway",
"if",
"len",
"(",
"s",
")",
"<=",
"length",
"+",
"leeway",
":",
"return",
"s",
"if",
"killwords",
":",
"return",
"s",
"[",
":",
"length",
"-",
"len",
"(",
"end",
")",
"]",
"+",
"end",
"result",
"=",
"s",
"[",
":",
"length",
"-",
"len",
"(",
"end",
")",
"]",
".",
"rsplit",
"(",
"' '",
",",
"1",
")",
"[",
"0",
"]",
"return",
"result",
"+",
"end"
] | [
577,
0
] | [
610,
23
] | python | en | ['en', 'en', 'en'] | True |
do_wordwrap | (environment, s, width=79, break_long_words=True,
wrapstring=None) |
Return a copy of the string passed to the filter wrapped after
``79`` characters. You can override this default using the first
parameter. If you set the second parameter to `false` Jinja will not
split words apart if they are longer than `width`. By default, the newlines
will be the default newlines for the environment, but this can be changed
using the wrapstring keyword argument.
.. versionadded:: 2.7
Added support for the `wrapstring` parameter.
|
Return a copy of the string passed to the filter wrapped after
``79`` characters. You can override this default using the first
parameter. If you set the second parameter to `false` Jinja will not
split words apart if they are longer than `width`. By default, the newlines
will be the default newlines for the environment, but this can be changed
using the wrapstring keyword argument. | def do_wordwrap(environment, s, width=79, break_long_words=True,
wrapstring=None):
"""
Return a copy of the string passed to the filter wrapped after
``79`` characters. You can override this default using the first
parameter. If you set the second parameter to `false` Jinja will not
split words apart if they are longer than `width`. By default, the newlines
will be the default newlines for the environment, but this can be changed
using the wrapstring keyword argument.
.. versionadded:: 2.7
Added support for the `wrapstring` parameter.
"""
if not wrapstring:
wrapstring = environment.newline_sequence
import textwrap
return wrapstring.join(textwrap.wrap(s, width=width, expand_tabs=False,
replace_whitespace=False,
break_long_words=break_long_words)) | [
"def",
"do_wordwrap",
"(",
"environment",
",",
"s",
",",
"width",
"=",
"79",
",",
"break_long_words",
"=",
"True",
",",
"wrapstring",
"=",
"None",
")",
":",
"if",
"not",
"wrapstring",
":",
"wrapstring",
"=",
"environment",
".",
"newline_sequence",
"import",
"textwrap",
"return",
"wrapstring",
".",
"join",
"(",
"textwrap",
".",
"wrap",
"(",
"s",
",",
"width",
"=",
"width",
",",
"expand_tabs",
"=",
"False",
",",
"replace_whitespace",
"=",
"False",
",",
"break_long_words",
"=",
"break_long_words",
")",
")"
] | [
614,
0
] | [
632,
70
] | python | en | ['en', 'error', 'th'] | False |
do_wordcount | (s) | Count the words in that string. | Count the words in that string. | def do_wordcount(s):
"""Count the words in that string."""
return len(_word_re.findall(s)) | [
"def",
"do_wordcount",
"(",
"s",
")",
":",
"return",
"len",
"(",
"_word_re",
".",
"findall",
"(",
"s",
")",
")"
] | [
635,
0
] | [
637,
35
] | python | en | ['en', 'en', 'en'] | True |
do_int | (value, default=0, base=10) | Convert the value into an integer. If the
conversion doesn't work it will return ``0``. You can
override this default using the first parameter. You
can also override the default base (10) in the second
parameter, which handles input with prefixes such as
0b, 0o and 0x for bases 2, 8 and 16 respectively.
The base is ignored for decimal numbers and non-string values.
| Convert the value into an integer. If the
conversion doesn't work it will return ``0``. You can
override this default using the first parameter. You
can also override the default base (10) in the second
parameter, which handles input with prefixes such as
0b, 0o and 0x for bases 2, 8 and 16 respectively.
The base is ignored for decimal numbers and non-string values.
| def do_int(value, default=0, base=10):
"""Convert the value into an integer. If the
conversion doesn't work it will return ``0``. You can
override this default using the first parameter. You
can also override the default base (10) in the second
parameter, which handles input with prefixes such as
0b, 0o and 0x for bases 2, 8 and 16 respectively.
The base is ignored for decimal numbers and non-string values.
"""
try:
if isinstance(value, string_types):
return int(value, base)
return int(value)
except (TypeError, ValueError):
# this quirk is necessary so that "42.23"|int gives 42.
try:
return int(float(value))
except (TypeError, ValueError):
return default | [
"def",
"do_int",
"(",
"value",
",",
"default",
"=",
"0",
",",
"base",
"=",
"10",
")",
":",
"try",
":",
"if",
"isinstance",
"(",
"value",
",",
"string_types",
")",
":",
"return",
"int",
"(",
"value",
",",
"base",
")",
"return",
"int",
"(",
"value",
")",
"except",
"(",
"TypeError",
",",
"ValueError",
")",
":",
"# this quirk is necessary so that \"42.23\"|int gives 42.",
"try",
":",
"return",
"int",
"(",
"float",
"(",
"value",
")",
")",
"except",
"(",
"TypeError",
",",
"ValueError",
")",
":",
"return",
"default"
] | [
640,
0
] | [
658,
26
] | python | en | ['en', 'en', 'en'] | True |
do_float | (value, default=0.0) | Convert the value into a floating point number. If the
conversion doesn't work it will return ``0.0``. You can
override this default using the first parameter.
| Convert the value into a floating point number. If the
conversion doesn't work it will return ``0.0``. You can
override this default using the first parameter.
| def do_float(value, default=0.0):
"""Convert the value into a floating point number. If the
conversion doesn't work it will return ``0.0``. You can
override this default using the first parameter.
"""
try:
return float(value)
except (TypeError, ValueError):
return default | [
"def",
"do_float",
"(",
"value",
",",
"default",
"=",
"0.0",
")",
":",
"try",
":",
"return",
"float",
"(",
"value",
")",
"except",
"(",
"TypeError",
",",
"ValueError",
")",
":",
"return",
"default"
] | [
661,
0
] | [
669,
22
] | python | en | ['en', 'en', 'en'] | True |
do_format | (value, *args, **kwargs) |
Apply python string formatting on an object:
.. sourcecode:: jinja
{{ "%s - %s"|format("Hello?", "Foo!") }}
-> Hello? - Foo!
|
Apply python string formatting on an object: | def do_format(value, *args, **kwargs):
"""
Apply python string formatting on an object:
.. sourcecode:: jinja
{{ "%s - %s"|format("Hello?", "Foo!") }}
-> Hello? - Foo!
"""
if args and kwargs:
raise FilterArgumentError('can\'t handle positional and keyword '
'arguments at the same time')
return soft_unicode(value) % (kwargs or args) | [
"def",
"do_format",
"(",
"value",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"args",
"and",
"kwargs",
":",
"raise",
"FilterArgumentError",
"(",
"'can\\'t handle positional and keyword '",
"'arguments at the same time'",
")",
"return",
"soft_unicode",
"(",
"value",
")",
"%",
"(",
"kwargs",
"or",
"args",
")"
] | [
672,
0
] | [
684,
49
] | python | en | ['en', 'error', 'th'] | False |
do_trim | (value) | Strip leading and trailing whitespace. | Strip leading and trailing whitespace. | def do_trim(value):
"""Strip leading and trailing whitespace."""
return soft_unicode(value).strip() | [
"def",
"do_trim",
"(",
"value",
")",
":",
"return",
"soft_unicode",
"(",
"value",
")",
".",
"strip",
"(",
")"
] | [
687,
0
] | [
689,
38
] | python | en | ['en', 'en', 'en'] | True |
do_striptags | (value) | Strip SGML/XML tags and replace adjacent whitespace by one space.
| Strip SGML/XML tags and replace adjacent whitespace by one space.
| def do_striptags(value):
"""Strip SGML/XML tags and replace adjacent whitespace by one space.
"""
if hasattr(value, '__html__'):
value = value.__html__()
return Markup(text_type(value)).striptags() | [
"def",
"do_striptags",
"(",
"value",
")",
":",
"if",
"hasattr",
"(",
"value",
",",
"'__html__'",
")",
":",
"value",
"=",
"value",
".",
"__html__",
"(",
")",
"return",
"Markup",
"(",
"text_type",
"(",
"value",
")",
")",
".",
"striptags",
"(",
")"
] | [
692,
0
] | [
697,
47
] | python | en | ['en', 'en', 'en'] | True |
do_slice | (value, slices, fill_with=None) | Slice an iterator and return a list of lists containing
those items. Useful if you want to create a div containing
three ul tags that represent columns:
.. sourcecode:: html+jinja
<div class="columwrapper">
{%- for column in items|slice(3) %}
<ul class="column-{{ loop.index }}">
{%- for item in column %}
<li>{{ item }}</li>
{%- endfor %}
</ul>
{%- endfor %}
</div>
If you pass it a second argument it's used to fill missing
values on the last iteration.
| Slice an iterator and return a list of lists containing
those items. Useful if you want to create a div containing
three ul tags that represent columns: | def do_slice(value, slices, fill_with=None):
"""Slice an iterator and return a list of lists containing
those items. Useful if you want to create a div containing
three ul tags that represent columns:
.. sourcecode:: html+jinja
<div class="columwrapper">
{%- for column in items|slice(3) %}
<ul class="column-{{ loop.index }}">
{%- for item in column %}
<li>{{ item }}</li>
{%- endfor %}
</ul>
{%- endfor %}
</div>
If you pass it a second argument it's used to fill missing
values on the last iteration.
"""
seq = list(value)
length = len(seq)
items_per_slice = length // slices
slices_with_extra = length % slices
offset = 0
for slice_number in range(slices):
start = offset + slice_number * items_per_slice
if slice_number < slices_with_extra:
offset += 1
end = offset + (slice_number + 1) * items_per_slice
tmp = seq[start:end]
if fill_with is not None and slice_number >= slices_with_extra:
tmp.append(fill_with)
yield tmp | [
"def",
"do_slice",
"(",
"value",
",",
"slices",
",",
"fill_with",
"=",
"None",
")",
":",
"seq",
"=",
"list",
"(",
"value",
")",
"length",
"=",
"len",
"(",
"seq",
")",
"items_per_slice",
"=",
"length",
"//",
"slices",
"slices_with_extra",
"=",
"length",
"%",
"slices",
"offset",
"=",
"0",
"for",
"slice_number",
"in",
"range",
"(",
"slices",
")",
":",
"start",
"=",
"offset",
"+",
"slice_number",
"*",
"items_per_slice",
"if",
"slice_number",
"<",
"slices_with_extra",
":",
"offset",
"+=",
"1",
"end",
"=",
"offset",
"+",
"(",
"slice_number",
"+",
"1",
")",
"*",
"items_per_slice",
"tmp",
"=",
"seq",
"[",
"start",
":",
"end",
"]",
"if",
"fill_with",
"is",
"not",
"None",
"and",
"slice_number",
">=",
"slices_with_extra",
":",
"tmp",
".",
"append",
"(",
"fill_with",
")",
"yield",
"tmp"
] | [
700,
0
] | [
733,
17
] | python | en | ['en', 'en', 'en'] | True |
do_batch | (value, linecount, fill_with=None) |
A filter that batches items. It works pretty much like `slice`
just the other way round. It returns a list of lists with the
given number of items. If you provide a second parameter this
is used to fill up missing items. See this example:
.. sourcecode:: html+jinja
<table>
{%- for row in items|batch(3, ' ') %}
<tr>
{%- for column in row %}
<td>{{ column }}</td>
{%- endfor %}
</tr>
{%- endfor %}
</table>
|
A filter that batches items. It works pretty much like `slice`
just the other way round. It returns a list of lists with the
given number of items. If you provide a second parameter this
is used to fill up missing items. See this example: | def do_batch(value, linecount, fill_with=None):
"""
A filter that batches items. It works pretty much like `slice`
just the other way round. It returns a list of lists with the
given number of items. If you provide a second parameter this
is used to fill up missing items. See this example:
.. sourcecode:: html+jinja
<table>
{%- for row in items|batch(3, ' ') %}
<tr>
{%- for column in row %}
<td>{{ column }}</td>
{%- endfor %}
</tr>
{%- endfor %}
</table>
"""
tmp = []
for item in value:
if len(tmp) == linecount:
yield tmp
tmp = []
tmp.append(item)
if tmp:
if fill_with is not None and len(tmp) < linecount:
tmp += [fill_with] * (linecount - len(tmp))
yield tmp | [
"def",
"do_batch",
"(",
"value",
",",
"linecount",
",",
"fill_with",
"=",
"None",
")",
":",
"tmp",
"=",
"[",
"]",
"for",
"item",
"in",
"value",
":",
"if",
"len",
"(",
"tmp",
")",
"==",
"linecount",
":",
"yield",
"tmp",
"tmp",
"=",
"[",
"]",
"tmp",
".",
"append",
"(",
"item",
")",
"if",
"tmp",
":",
"if",
"fill_with",
"is",
"not",
"None",
"and",
"len",
"(",
"tmp",
")",
"<",
"linecount",
":",
"tmp",
"+=",
"[",
"fill_with",
"]",
"*",
"(",
"linecount",
"-",
"len",
"(",
"tmp",
")",
")",
"yield",
"tmp"
] | [
736,
0
] | [
764,
17
] | python | en | ['en', 'error', 'th'] | False |
do_round | (value, precision=0, method='common') | Round the number to a given precision. The first
parameter specifies the precision (default is ``0``), the
second the rounding method:
- ``'common'`` rounds either up or down
- ``'ceil'`` always rounds up
- ``'floor'`` always rounds down
If you don't specify a method ``'common'`` is used.
.. sourcecode:: jinja
{{ 42.55|round }}
-> 43.0
{{ 42.55|round(1, 'floor') }}
-> 42.5
Note that even if rounded to 0 precision, a float is returned. If
you need a real integer, pipe it through `int`:
.. sourcecode:: jinja
{{ 42.55|round|int }}
-> 43
| Round the number to a given precision. The first
parameter specifies the precision (default is ``0``), the
second the rounding method: | def do_round(value, precision=0, method='common'):
"""Round the number to a given precision. The first
parameter specifies the precision (default is ``0``), the
second the rounding method:
- ``'common'`` rounds either up or down
- ``'ceil'`` always rounds up
- ``'floor'`` always rounds down
If you don't specify a method ``'common'`` is used.
.. sourcecode:: jinja
{{ 42.55|round }}
-> 43.0
{{ 42.55|round(1, 'floor') }}
-> 42.5
Note that even if rounded to 0 precision, a float is returned. If
you need a real integer, pipe it through `int`:
.. sourcecode:: jinja
{{ 42.55|round|int }}
-> 43
"""
if not method in ('common', 'ceil', 'floor'):
raise FilterArgumentError('method must be common, ceil or floor')
if method == 'common':
return round(value, precision)
func = getattr(math, method)
return func(value * (10 ** precision)) / (10 ** precision) | [
"def",
"do_round",
"(",
"value",
",",
"precision",
"=",
"0",
",",
"method",
"=",
"'common'",
")",
":",
"if",
"not",
"method",
"in",
"(",
"'common'",
",",
"'ceil'",
",",
"'floor'",
")",
":",
"raise",
"FilterArgumentError",
"(",
"'method must be common, ceil or floor'",
")",
"if",
"method",
"==",
"'common'",
":",
"return",
"round",
"(",
"value",
",",
"precision",
")",
"func",
"=",
"getattr",
"(",
"math",
",",
"method",
")",
"return",
"func",
"(",
"value",
"*",
"(",
"10",
"**",
"precision",
")",
")",
"/",
"(",
"10",
"**",
"precision",
")"
] | [
767,
0
] | [
798,
62
] | python | en | ['en', 'en', 'en'] | True |
do_groupby | (environment, value, attribute) | Group a sequence of objects by a common attribute.
If you for example have a list of dicts or objects that represent persons
with `gender`, `first_name` and `last_name` attributes and you want to
group all users by genders you can do something like the following
snippet:
.. sourcecode:: html+jinja
<ul>
{% for group in persons|groupby('gender') %}
<li>{{ group.grouper }}<ul>
{% for person in group.list %}
<li>{{ person.first_name }} {{ person.last_name }}</li>
{% endfor %}</ul></li>
{% endfor %}
</ul>
Additionally it's possible to use tuple unpacking for the grouper and
list:
.. sourcecode:: html+jinja
<ul>
{% for grouper, list in persons|groupby('gender') %}
...
{% endfor %}
</ul>
As you can see the item we're grouping by is stored in the `grouper`
attribute and the `list` contains all the objects that have this grouper
in common.
.. versionchanged:: 2.6
It's now possible to use dotted notation to group by the child
attribute of another attribute.
| Group a sequence of objects by a common attribute. | def do_groupby(environment, value, attribute):
"""Group a sequence of objects by a common attribute.
If you for example have a list of dicts or objects that represent persons
with `gender`, `first_name` and `last_name` attributes and you want to
group all users by genders you can do something like the following
snippet:
.. sourcecode:: html+jinja
<ul>
{% for group in persons|groupby('gender') %}
<li>{{ group.grouper }}<ul>
{% for person in group.list %}
<li>{{ person.first_name }} {{ person.last_name }}</li>
{% endfor %}</ul></li>
{% endfor %}
</ul>
Additionally it's possible to use tuple unpacking for the grouper and
list:
.. sourcecode:: html+jinja
<ul>
{% for grouper, list in persons|groupby('gender') %}
...
{% endfor %}
</ul>
As you can see the item we're grouping by is stored in the `grouper`
attribute and the `list` contains all the objects that have this grouper
in common.
.. versionchanged:: 2.6
It's now possible to use dotted notation to group by the child
attribute of another attribute.
"""
expr = make_attrgetter(environment, attribute)
return [_GroupTuple(key, list(values)) for key, values
in groupby(sorted(value, key=expr), expr)] | [
"def",
"do_groupby",
"(",
"environment",
",",
"value",
",",
"attribute",
")",
":",
"expr",
"=",
"make_attrgetter",
"(",
"environment",
",",
"attribute",
")",
"return",
"[",
"_GroupTuple",
"(",
"key",
",",
"list",
"(",
"values",
")",
")",
"for",
"key",
",",
"values",
"in",
"groupby",
"(",
"sorted",
"(",
"value",
",",
"key",
"=",
"expr",
")",
",",
"expr",
")",
"]"
] | [
811,
0
] | [
851,
54
] | python | en | ['en', 'en', 'en'] | True |
do_sum | (environment, iterable, attribute=None, start=0) | Returns the sum of a sequence of numbers plus the value of parameter
'start' (which defaults to 0). When the sequence is empty it returns
start.
It is also possible to sum up only certain attributes:
.. sourcecode:: jinja
Total: {{ items|sum(attribute='price') }}
.. versionchanged:: 2.6
The `attribute` parameter was added to allow suming up over
attributes. Also the `start` parameter was moved on to the right.
| Returns the sum of a sequence of numbers plus the value of parameter
'start' (which defaults to 0). When the sequence is empty it returns
start. | def do_sum(environment, iterable, attribute=None, start=0):
"""Returns the sum of a sequence of numbers plus the value of parameter
'start' (which defaults to 0). When the sequence is empty it returns
start.
It is also possible to sum up only certain attributes:
.. sourcecode:: jinja
Total: {{ items|sum(attribute='price') }}
.. versionchanged:: 2.6
The `attribute` parameter was added to allow suming up over
attributes. Also the `start` parameter was moved on to the right.
"""
if attribute is not None:
iterable = imap(make_attrgetter(environment, attribute), iterable)
return sum(iterable, start) | [
"def",
"do_sum",
"(",
"environment",
",",
"iterable",
",",
"attribute",
"=",
"None",
",",
"start",
"=",
"0",
")",
":",
"if",
"attribute",
"is",
"not",
"None",
":",
"iterable",
"=",
"imap",
"(",
"make_attrgetter",
"(",
"environment",
",",
"attribute",
")",
",",
"iterable",
")",
"return",
"sum",
"(",
"iterable",
",",
"start",
")"
] | [
855,
0
] | [
872,
31
] | python | en | ['en', 'en', 'en'] | True |
do_list | (value) | Convert the value into a list. If it was a string the returned list
will be a list of characters.
| Convert the value into a list. If it was a string the returned list
will be a list of characters.
| def do_list(value):
"""Convert the value into a list. If it was a string the returned list
will be a list of characters.
"""
return list(value) | [
"def",
"do_list",
"(",
"value",
")",
":",
"return",
"list",
"(",
"value",
")"
] | [
875,
0
] | [
879,
22
] | python | en | ['en', 'en', 'en'] | True |
do_mark_safe | (value) | Mark the value as safe which means that in an environment with automatic
escaping enabled this variable will not be escaped.
| Mark the value as safe which means that in an environment with automatic
escaping enabled this variable will not be escaped.
| def do_mark_safe(value):
"""Mark the value as safe which means that in an environment with automatic
escaping enabled this variable will not be escaped.
"""
return Markup(value) | [
"def",
"do_mark_safe",
"(",
"value",
")",
":",
"return",
"Markup",
"(",
"value",
")"
] | [
882,
0
] | [
886,
24
] | python | en | ['en', 'en', 'en'] | True |
do_mark_unsafe | (value) | Mark a value as unsafe. This is the reverse operation for :func:`safe`. | Mark a value as unsafe. This is the reverse operation for :func:`safe`. | def do_mark_unsafe(value):
"""Mark a value as unsafe. This is the reverse operation for :func:`safe`."""
return text_type(value) | [
"def",
"do_mark_unsafe",
"(",
"value",
")",
":",
"return",
"text_type",
"(",
"value",
")"
] | [
889,
0
] | [
891,
27
] | python | en | ['en', 'en', 'en'] | True |
do_reverse | (value) | Reverse the object or return an iterator that iterates over it the other
way round.
| Reverse the object or return an iterator that iterates over it the other
way round.
| def do_reverse(value):
"""Reverse the object or return an iterator that iterates over it the other
way round.
"""
if isinstance(value, string_types):
return value[::-1]
try:
return reversed(value)
except TypeError:
try:
rv = list(value)
rv.reverse()
return rv
except TypeError:
raise FilterArgumentError('argument must be iterable') | [
"def",
"do_reverse",
"(",
"value",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"string_types",
")",
":",
"return",
"value",
"[",
":",
":",
"-",
"1",
"]",
"try",
":",
"return",
"reversed",
"(",
"value",
")",
"except",
"TypeError",
":",
"try",
":",
"rv",
"=",
"list",
"(",
"value",
")",
"rv",
".",
"reverse",
"(",
")",
"return",
"rv",
"except",
"TypeError",
":",
"raise",
"FilterArgumentError",
"(",
"'argument must be iterable'",
")"
] | [
894,
0
] | [
908,
66
] | python | en | ['en', 'en', 'en'] | True |
do_attr | (environment, obj, name) | Get an attribute of an object. ``foo|attr("bar")`` works like
``foo.bar`` just that always an attribute is returned and items are not
looked up.
See :ref:`Notes on subscriptions <notes-on-subscriptions>` for more details.
| Get an attribute of an object. ``foo|attr("bar")`` works like
``foo.bar`` just that always an attribute is returned and items are not
looked up. | def do_attr(environment, obj, name):
"""Get an attribute of an object. ``foo|attr("bar")`` works like
``foo.bar`` just that always an attribute is returned and items are not
looked up.
See :ref:`Notes on subscriptions <notes-on-subscriptions>` for more details.
"""
try:
name = str(name)
except UnicodeError:
pass
else:
try:
value = getattr(obj, name)
except AttributeError:
pass
else:
if environment.sandboxed and not \
environment.is_safe_attribute(obj, name, value):
return environment.unsafe_undefined(obj, name)
return value
return environment.undefined(obj=obj, name=name) | [
"def",
"do_attr",
"(",
"environment",
",",
"obj",
",",
"name",
")",
":",
"try",
":",
"name",
"=",
"str",
"(",
"name",
")",
"except",
"UnicodeError",
":",
"pass",
"else",
":",
"try",
":",
"value",
"=",
"getattr",
"(",
"obj",
",",
"name",
")",
"except",
"AttributeError",
":",
"pass",
"else",
":",
"if",
"environment",
".",
"sandboxed",
"and",
"not",
"environment",
".",
"is_safe_attribute",
"(",
"obj",
",",
"name",
",",
"value",
")",
":",
"return",
"environment",
".",
"unsafe_undefined",
"(",
"obj",
",",
"name",
")",
"return",
"value",
"return",
"environment",
".",
"undefined",
"(",
"obj",
"=",
"obj",
",",
"name",
"=",
"name",
")"
] | [
912,
0
] | [
933,
52
] | python | en | ['en', 'en', 'en'] | True |
do_map | (*args, **kwargs) | Applies a filter on a sequence of objects or looks up an attribute.
This is useful when dealing with lists of objects but you are really
only interested in a certain value of it.
The basic usage is mapping on an attribute. Imagine you have a list
of users but you are only interested in a list of usernames:
.. sourcecode:: jinja
Users on this page: {{ users|map(attribute='username')|join(', ') }}
Alternatively you can let it invoke a filter by passing the name of the
filter and the arguments afterwards. A good example would be applying a
text conversion filter on a sequence:
.. sourcecode:: jinja
Users on this page: {{ titles|map('lower')|join(', ') }}
.. versionadded:: 2.7
| Applies a filter on a sequence of objects or looks up an attribute.
This is useful when dealing with lists of objects but you are really
only interested in a certain value of it. | def do_map(*args, **kwargs):
"""Applies a filter on a sequence of objects or looks up an attribute.
This is useful when dealing with lists of objects but you are really
only interested in a certain value of it.
The basic usage is mapping on an attribute. Imagine you have a list
of users but you are only interested in a list of usernames:
.. sourcecode:: jinja
Users on this page: {{ users|map(attribute='username')|join(', ') }}
Alternatively you can let it invoke a filter by passing the name of the
filter and the arguments afterwards. A good example would be applying a
text conversion filter on a sequence:
.. sourcecode:: jinja
Users on this page: {{ titles|map('lower')|join(', ') }}
.. versionadded:: 2.7
"""
seq, func = prepare_map(args, kwargs)
if seq:
for item in seq:
yield func(item) | [
"def",
"do_map",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"seq",
",",
"func",
"=",
"prepare_map",
"(",
"args",
",",
"kwargs",
")",
"if",
"seq",
":",
"for",
"item",
"in",
"seq",
":",
"yield",
"func",
"(",
"item",
")"
] | [
937,
0
] | [
962,
28
] | python | en | ['en', 'en', 'en'] | True |
do_select | (*args, **kwargs) | Filters a sequence of objects by applying a test to each object,
and only selecting the objects with the test succeeding.
If no test is specified, each object will be evaluated as a boolean.
Example usage:
.. sourcecode:: jinja
{{ numbers|select("odd") }}
{{ numbers|select("odd") }}
{{ numbers|select("divisibleby", 3) }}
{{ numbers|select("lessthan", 42) }}
{{ strings|select("equalto", "mystring") }}
.. versionadded:: 2.7
| Filters a sequence of objects by applying a test to each object,
and only selecting the objects with the test succeeding. | def do_select(*args, **kwargs):
"""Filters a sequence of objects by applying a test to each object,
and only selecting the objects with the test succeeding.
If no test is specified, each object will be evaluated as a boolean.
Example usage:
.. sourcecode:: jinja
{{ numbers|select("odd") }}
{{ numbers|select("odd") }}
{{ numbers|select("divisibleby", 3) }}
{{ numbers|select("lessthan", 42) }}
{{ strings|select("equalto", "mystring") }}
.. versionadded:: 2.7
"""
return select_or_reject(args, kwargs, lambda x: x, False) | [
"def",
"do_select",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"select_or_reject",
"(",
"args",
",",
"kwargs",
",",
"lambda",
"x",
":",
"x",
",",
"False",
")"
] | [
966,
0
] | [
984,
61
] | python | en | ['en', 'en', 'en'] | True |
do_reject | (*args, **kwargs) | Filters a sequence of objects by applying a test to each object,
and rejecting the objects with the test succeeding.
If no test is specified, each object will be evaluated as a boolean.
Example usage:
.. sourcecode:: jinja
{{ numbers|reject("odd") }}
.. versionadded:: 2.7
| Filters a sequence of objects by applying a test to each object,
and rejecting the objects with the test succeeding. | def do_reject(*args, **kwargs):
"""Filters a sequence of objects by applying a test to each object,
and rejecting the objects with the test succeeding.
If no test is specified, each object will be evaluated as a boolean.
Example usage:
.. sourcecode:: jinja
{{ numbers|reject("odd") }}
.. versionadded:: 2.7
"""
return select_or_reject(args, kwargs, lambda x: not x, False) | [
"def",
"do_reject",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"select_or_reject",
"(",
"args",
",",
"kwargs",
",",
"lambda",
"x",
":",
"not",
"x",
",",
"False",
")"
] | [
988,
0
] | [
1002,
65
] | python | en | ['en', 'en', 'en'] | True |
do_selectattr | (*args, **kwargs) | Filters a sequence of objects by applying a test to the specified
attribute of each object, and only selecting the objects with the
test succeeding.
If no test is specified, the attribute's value will be evaluated as
a boolean.
Example usage:
.. sourcecode:: jinja
{{ users|selectattr("is_active") }}
{{ users|selectattr("email", "none") }}
.. versionadded:: 2.7
| Filters a sequence of objects by applying a test to the specified
attribute of each object, and only selecting the objects with the
test succeeding. | def do_selectattr(*args, **kwargs):
"""Filters a sequence of objects by applying a test to the specified
attribute of each object, and only selecting the objects with the
test succeeding.
If no test is specified, the attribute's value will be evaluated as
a boolean.
Example usage:
.. sourcecode:: jinja
{{ users|selectattr("is_active") }}
{{ users|selectattr("email", "none") }}
.. versionadded:: 2.7
"""
return select_or_reject(args, kwargs, lambda x: x, True) | [
"def",
"do_selectattr",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"select_or_reject",
"(",
"args",
",",
"kwargs",
",",
"lambda",
"x",
":",
"x",
",",
"True",
")"
] | [
1006,
0
] | [
1023,
60
] | python | en | ['en', 'en', 'en'] | True |
do_rejectattr | (*args, **kwargs) | Filters a sequence of objects by applying a test to the specified
attribute of each object, and rejecting the objects with the test
succeeding.
If no test is specified, the attribute's value will be evaluated as
a boolean.
.. sourcecode:: jinja
{{ users|rejectattr("is_active") }}
{{ users|rejectattr("email", "none") }}
.. versionadded:: 2.7
| Filters a sequence of objects by applying a test to the specified
attribute of each object, and rejecting the objects with the test
succeeding. | def do_rejectattr(*args, **kwargs):
"""Filters a sequence of objects by applying a test to the specified
attribute of each object, and rejecting the objects with the test
succeeding.
If no test is specified, the attribute's value will be evaluated as
a boolean.
.. sourcecode:: jinja
{{ users|rejectattr("is_active") }}
{{ users|rejectattr("email", "none") }}
.. versionadded:: 2.7
"""
return select_or_reject(args, kwargs, lambda x: not x, True) | [
"def",
"do_rejectattr",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"select_or_reject",
"(",
"args",
",",
"kwargs",
",",
"lambda",
"x",
":",
"not",
"x",
",",
"True",
")"
] | [
1027,
0
] | [
1042,
64
] | python | en | ['en', 'en', 'en'] | True |
do_tojson | (eval_ctx, value, indent=None) | Dumps a structure to JSON so that it's safe to use in ``<script>``
tags. It accepts the same arguments and returns a JSON string. Note that
this is available in templates through the ``|tojson`` filter which will
also mark the result as safe. Due to how this function escapes certain
characters this is safe even if used outside of ``<script>`` tags.
The following characters are escaped in strings:
- ``<``
- ``>``
- ``&``
- ``'``
This makes it safe to embed such strings in any place in HTML with the
notable exception of double quoted attributes. In that case single
quote your attributes or HTML escape it in addition.
The indent parameter can be used to enable pretty printing. Set it to
the number of spaces that the structures should be indented with.
Note that this filter is for use in HTML contexts only.
.. versionadded:: 2.9
| Dumps a structure to JSON so that it's safe to use in ``<script>``
tags. It accepts the same arguments and returns a JSON string. Note that
this is available in templates through the ``|tojson`` filter which will
also mark the result as safe. Due to how this function escapes certain
characters this is safe even if used outside of ``<script>`` tags. | def do_tojson(eval_ctx, value, indent=None):
"""Dumps a structure to JSON so that it's safe to use in ``<script>``
tags. It accepts the same arguments and returns a JSON string. Note that
this is available in templates through the ``|tojson`` filter which will
also mark the result as safe. Due to how this function escapes certain
characters this is safe even if used outside of ``<script>`` tags.
The following characters are escaped in strings:
- ``<``
- ``>``
- ``&``
- ``'``
This makes it safe to embed such strings in any place in HTML with the
notable exception of double quoted attributes. In that case single
quote your attributes or HTML escape it in addition.
The indent parameter can be used to enable pretty printing. Set it to
the number of spaces that the structures should be indented with.
Note that this filter is for use in HTML contexts only.
.. versionadded:: 2.9
"""
policies = eval_ctx.environment.policies
dumper = policies['json.dumps_function']
options = policies['json.dumps_kwargs']
if indent is not None:
options = dict(options)
options['indent'] = indent
return htmlsafe_json_dumps(value, dumper=dumper, **options) | [
"def",
"do_tojson",
"(",
"eval_ctx",
",",
"value",
",",
"indent",
"=",
"None",
")",
":",
"policies",
"=",
"eval_ctx",
".",
"environment",
".",
"policies",
"dumper",
"=",
"policies",
"[",
"'json.dumps_function'",
"]",
"options",
"=",
"policies",
"[",
"'json.dumps_kwargs'",
"]",
"if",
"indent",
"is",
"not",
"None",
":",
"options",
"=",
"dict",
"(",
"options",
")",
"options",
"[",
"'indent'",
"]",
"=",
"indent",
"return",
"htmlsafe_json_dumps",
"(",
"value",
",",
"dumper",
"=",
"dumper",
",",
"*",
"*",
"options",
")"
] | [
1046,
0
] | [
1077,
63
] | python | en | ['en', 'en', 'en'] | True |
to_list | (value) |
Put value into a list if it's not already one. Return an empty list if
value is None.
|
Put value into a list if it's not already one. Return an empty list if
value is None.
| def to_list(value):
"""
Put value into a list if it's not already one. Return an empty list if
value is None.
"""
if value is None:
value = []
elif not isinstance(value, list):
value = [value]
return value | [
"def",
"to_list",
"(",
"value",
")",
":",
"if",
"value",
"is",
"None",
":",
"value",
"=",
"[",
"]",
"elif",
"not",
"isinstance",
"(",
"value",
",",
"list",
")",
":",
"value",
"=",
"[",
"value",
"]",
"return",
"value"
] | [
51,
0
] | [
60,
16
] | python | en | ['en', 'error', 'th'] | False |
connections_support_transactions | (aliases=None) |
Return whether or not all (or specified) connections support
transactions.
|
Return whether or not all (or specified) connections support
transactions.
| def connections_support_transactions(aliases=None):
"""
Return whether or not all (or specified) connections support
transactions.
"""
conns = connections.all() if aliases is None else (connections[alias] for alias in aliases)
return all(conn.features.supports_transactions for conn in conns) | [
"def",
"connections_support_transactions",
"(",
"aliases",
"=",
"None",
")",
":",
"conns",
"=",
"connections",
".",
"all",
"(",
")",
"if",
"aliases",
"is",
"None",
"else",
"(",
"connections",
"[",
"alias",
"]",
"for",
"alias",
"in",
"aliases",
")",
"return",
"all",
"(",
"conn",
".",
"features",
".",
"supports_transactions",
"for",
"conn",
"in",
"conns",
")"
] | [
1084,
0
] | [
1090,
69
] | python | en | ['en', 'error', 'th'] | False |
skipIfDBFeature | (*features) | Skip a test if a database has at least one of the named features. | Skip a test if a database has at least one of the named features. | def skipIfDBFeature(*features):
"""Skip a test if a database has at least one of the named features."""
return _deferredSkip(
lambda: any(getattr(connection.features, feature, False) for feature in features),
"Database has feature(s) %s" % ", ".join(features),
'skipIfDBFeature',
) | [
"def",
"skipIfDBFeature",
"(",
"*",
"features",
")",
":",
"return",
"_deferredSkip",
"(",
"lambda",
":",
"any",
"(",
"getattr",
"(",
"connection",
".",
"features",
",",
"feature",
",",
"False",
")",
"for",
"feature",
"in",
"features",
")",
",",
"\"Database has feature(s) %s\"",
"%",
"\", \"",
".",
"join",
"(",
"features",
")",
",",
"'skipIfDBFeature'",
",",
")"
] | [
1340,
0
] | [
1346,
5
] | python | en | ['en', 'en', 'en'] | True |
skipUnlessDBFeature | (*features) | Skip a test unless a database has all the named features. | Skip a test unless a database has all the named features. | def skipUnlessDBFeature(*features):
"""Skip a test unless a database has all the named features."""
return _deferredSkip(
lambda: not all(getattr(connection.features, feature, False) for feature in features),
"Database doesn't support feature(s): %s" % ", ".join(features),
'skipUnlessDBFeature',
) | [
"def",
"skipUnlessDBFeature",
"(",
"*",
"features",
")",
":",
"return",
"_deferredSkip",
"(",
"lambda",
":",
"not",
"all",
"(",
"getattr",
"(",
"connection",
".",
"features",
",",
"feature",
",",
"False",
")",
"for",
"feature",
"in",
"features",
")",
",",
"\"Database doesn't support feature(s): %s\"",
"%",
"\", \"",
".",
"join",
"(",
"features",
")",
",",
"'skipUnlessDBFeature'",
",",
")"
] | [
1349,
0
] | [
1355,
5
] | python | en | ['en', 'en', 'en'] | True |
skipUnlessAnyDBFeature | (*features) | Skip a test unless a database has any of the named features. | Skip a test unless a database has any of the named features. | def skipUnlessAnyDBFeature(*features):
"""Skip a test unless a database has any of the named features."""
return _deferredSkip(
lambda: not any(getattr(connection.features, feature, False) for feature in features),
"Database doesn't support any of the feature(s): %s" % ", ".join(features),
'skipUnlessAnyDBFeature',
) | [
"def",
"skipUnlessAnyDBFeature",
"(",
"*",
"features",
")",
":",
"return",
"_deferredSkip",
"(",
"lambda",
":",
"not",
"any",
"(",
"getattr",
"(",
"connection",
".",
"features",
",",
"feature",
",",
"False",
")",
"for",
"feature",
"in",
"features",
")",
",",
"\"Database doesn't support any of the feature(s): %s\"",
"%",
"\", \"",
".",
"join",
"(",
"features",
")",
",",
"'skipUnlessAnyDBFeature'",
",",
")"
] | [
1358,
0
] | [
1364,
5
] | python | en | ['en', 'en', 'en'] | True |
SimpleTestCase.__call__ | (self, result=None) |
Wrapper around default __call__ method to perform common Django test
set up. This means that user-defined Test Cases aren't required to
include a call to super().setUp().
|
Wrapper around default __call__ method to perform common Django test
set up. This means that user-defined Test Cases aren't required to
include a call to super().setUp().
| def __call__(self, result=None):
"""
Wrapper around default __call__ method to perform common Django test
set up. This means that user-defined Test Cases aren't required to
include a call to super().setUp().
"""
self._setup_and_call(result) | [
"def",
"__call__",
"(",
"self",
",",
"result",
"=",
"None",
")",
":",
"self",
".",
"_setup_and_call",
"(",
"result",
")"
] | [
238,
4
] | [
244,
36
] | python | en | ['en', 'error', 'th'] | False |
SimpleTestCase.debug | (self) | Perform the same as __call__(), without catching the exception. | Perform the same as __call__(), without catching the exception. | def debug(self):
"""Perform the same as __call__(), without catching the exception."""
debug_result = _DebugResult()
self._setup_and_call(debug_result, debug=True) | [
"def",
"debug",
"(",
"self",
")",
":",
"debug_result",
"=",
"_DebugResult",
"(",
")",
"self",
".",
"_setup_and_call",
"(",
"debug_result",
",",
"debug",
"=",
"True",
")"
] | [
246,
4
] | [
249,
54
] | python | en | ['en', 'en', 'en'] | True |
SimpleTestCase._setup_and_call | (self, result, debug=False) |
Perform the following in order: pre-setup, run test, post-teardown,
skipping pre/post hooks if test is set to be skipped.
If debug=True, reraise any errors in setup and use super().debug()
instead of __call__() to run the test.
|
Perform the following in order: pre-setup, run test, post-teardown,
skipping pre/post hooks if test is set to be skipped. | def _setup_and_call(self, result, debug=False):
"""
Perform the following in order: pre-setup, run test, post-teardown,
skipping pre/post hooks if test is set to be skipped.
If debug=True, reraise any errors in setup and use super().debug()
instead of __call__() to run the test.
"""
testMethod = getattr(self, self._testMethodName)
skipped = (
getattr(self.__class__, "__unittest_skip__", False) or
getattr(testMethod, "__unittest_skip__", False)
)
# Convert async test methods.
if asyncio.iscoroutinefunction(testMethod):
setattr(self, self._testMethodName, async_to_sync(testMethod))
if not skipped:
try:
self._pre_setup()
except Exception:
if debug:
raise
result.addError(self, sys.exc_info())
return
if debug:
super().debug()
else:
super().__call__(result)
if not skipped:
try:
self._post_teardown()
except Exception:
if debug:
raise
result.addError(self, sys.exc_info())
return | [
"def",
"_setup_and_call",
"(",
"self",
",",
"result",
",",
"debug",
"=",
"False",
")",
":",
"testMethod",
"=",
"getattr",
"(",
"self",
",",
"self",
".",
"_testMethodName",
")",
"skipped",
"=",
"(",
"getattr",
"(",
"self",
".",
"__class__",
",",
"\"__unittest_skip__\"",
",",
"False",
")",
"or",
"getattr",
"(",
"testMethod",
",",
"\"__unittest_skip__\"",
",",
"False",
")",
")",
"# Convert async test methods.",
"if",
"asyncio",
".",
"iscoroutinefunction",
"(",
"testMethod",
")",
":",
"setattr",
"(",
"self",
",",
"self",
".",
"_testMethodName",
",",
"async_to_sync",
"(",
"testMethod",
")",
")",
"if",
"not",
"skipped",
":",
"try",
":",
"self",
".",
"_pre_setup",
"(",
")",
"except",
"Exception",
":",
"if",
"debug",
":",
"raise",
"result",
".",
"addError",
"(",
"self",
",",
"sys",
".",
"exc_info",
"(",
")",
")",
"return",
"if",
"debug",
":",
"super",
"(",
")",
".",
"debug",
"(",
")",
"else",
":",
"super",
"(",
")",
".",
"__call__",
"(",
"result",
")",
"if",
"not",
"skipped",
":",
"try",
":",
"self",
".",
"_post_teardown",
"(",
")",
"except",
"Exception",
":",
"if",
"debug",
":",
"raise",
"result",
".",
"addError",
"(",
"self",
",",
"sys",
".",
"exc_info",
"(",
")",
")",
"return"
] | [
251,
4
] | [
288,
22
] | python | en | ['en', 'error', 'th'] | False |
SimpleTestCase._pre_setup | (self) |
Perform pre-test setup:
* Create a test client.
* Clear the mail test outbox.
|
Perform pre-test setup:
* Create a test client.
* Clear the mail test outbox.
| def _pre_setup(self):
"""
Perform pre-test setup:
* Create a test client.
* Clear the mail test outbox.
"""
self.client = self.client_class()
self.async_client = self.async_client_class()
mail.outbox = [] | [
"def",
"_pre_setup",
"(",
"self",
")",
":",
"self",
".",
"client",
"=",
"self",
".",
"client_class",
"(",
")",
"self",
".",
"async_client",
"=",
"self",
".",
"async_client_class",
"(",
")",
"mail",
".",
"outbox",
"=",
"[",
"]"
] | [
290,
4
] | [
298,
24
] | python | en | ['en', 'error', 'th'] | False |
SimpleTestCase._post_teardown | (self) | Perform post-test things. | Perform post-test things. | def _post_teardown(self):
"""Perform post-test things."""
pass | [
"def",
"_post_teardown",
"(",
"self",
")",
":",
"pass"
] | [
300,
4
] | [
302,
12
] | python | en | ['en', 'en', 'en'] | True |
SimpleTestCase.settings | (self, **kwargs) |
A context manager that temporarily sets a setting and reverts to the
original value when exiting the context.
|
A context manager that temporarily sets a setting and reverts to the
original value when exiting the context.
| def settings(self, **kwargs):
"""
A context manager that temporarily sets a setting and reverts to the
original value when exiting the context.
"""
return override_settings(**kwargs) | [
"def",
"settings",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"override_settings",
"(",
"*",
"*",
"kwargs",
")"
] | [
304,
4
] | [
309,
42
] | python | en | ['en', 'error', 'th'] | False |
SimpleTestCase.modify_settings | (self, **kwargs) |
A context manager that temporarily applies changes a list setting and
reverts back to the original value when exiting the context.
|
A context manager that temporarily applies changes a list setting and
reverts back to the original value when exiting the context.
| def modify_settings(self, **kwargs):
"""
A context manager that temporarily applies changes a list setting and
reverts back to the original value when exiting the context.
"""
return modify_settings(**kwargs) | [
"def",
"modify_settings",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"modify_settings",
"(",
"*",
"*",
"kwargs",
")"
] | [
311,
4
] | [
316,
40
] | python | en | ['en', 'error', 'th'] | False |
SimpleTestCase.assertRedirects | (self, response, expected_url, status_code=302,
target_status_code=200, msg_prefix='',
fetch_redirect_response=True) |
Assert that a response redirected to a specific URL and that the
redirect URL can be loaded.
Won't work for external links since it uses the test client to do a
request (use fetch_redirect_response=False to check such links without
fetching them).
|
Assert that a response redirected to a specific URL and that the
redirect URL can be loaded. | def assertRedirects(self, response, expected_url, status_code=302,
target_status_code=200, msg_prefix='',
fetch_redirect_response=True):
"""
Assert that a response redirected to a specific URL and that the
redirect URL can be loaded.
Won't work for external links since it uses the test client to do a
request (use fetch_redirect_response=False to check such links without
fetching them).
"""
if msg_prefix:
msg_prefix += ": "
if hasattr(response, 'redirect_chain'):
# The request was a followed redirect
self.assertTrue(
response.redirect_chain,
msg_prefix + "Response didn't redirect as expected: Response code was %d (expected %d)"
% (response.status_code, status_code)
)
self.assertEqual(
response.redirect_chain[0][1], status_code,
msg_prefix + "Initial response didn't redirect as expected: Response code was %d (expected %d)"
% (response.redirect_chain[0][1], status_code)
)
url, status_code = response.redirect_chain[-1]
self.assertEqual(
response.status_code, target_status_code,
msg_prefix + "Response didn't redirect as expected: Final Response code was %d (expected %d)"
% (response.status_code, target_status_code)
)
else:
# Not a followed redirect
self.assertEqual(
response.status_code, status_code,
msg_prefix + "Response didn't redirect as expected: Response code was %d (expected %d)"
% (response.status_code, status_code)
)
url = response.url
scheme, netloc, path, query, fragment = urlsplit(url)
# Prepend the request path to handle relative path redirects.
if not path.startswith('/'):
url = urljoin(response.request['PATH_INFO'], url)
path = urljoin(response.request['PATH_INFO'], path)
if fetch_redirect_response:
# netloc might be empty, or in cases where Django tests the
# HTTP scheme, the convention is for netloc to be 'testserver'.
# Trust both as "internal" URLs here.
domain, port = split_domain_port(netloc)
if domain and not validate_host(domain, settings.ALLOWED_HOSTS):
raise ValueError(
"The test client is unable to fetch remote URLs (got %s). "
"If the host is served by Django, add '%s' to ALLOWED_HOSTS. "
"Otherwise, use assertRedirects(..., fetch_redirect_response=False)."
% (url, domain)
)
# Get the redirection page, using the same client that was used
# to obtain the original response.
extra = response.client.extra or {}
redirect_response = response.client.get(
path,
QueryDict(query),
secure=(scheme == 'https'),
**extra,
)
self.assertEqual(
redirect_response.status_code, target_status_code,
msg_prefix + "Couldn't retrieve redirection page '%s': response code was %d (expected %d)"
% (path, redirect_response.status_code, target_status_code)
)
self.assertURLEqual(
url, expected_url,
msg_prefix + "Response redirected to '%s', expected '%s'" % (url, expected_url)
) | [
"def",
"assertRedirects",
"(",
"self",
",",
"response",
",",
"expected_url",
",",
"status_code",
"=",
"302",
",",
"target_status_code",
"=",
"200",
",",
"msg_prefix",
"=",
"''",
",",
"fetch_redirect_response",
"=",
"True",
")",
":",
"if",
"msg_prefix",
":",
"msg_prefix",
"+=",
"\": \"",
"if",
"hasattr",
"(",
"response",
",",
"'redirect_chain'",
")",
":",
"# The request was a followed redirect",
"self",
".",
"assertTrue",
"(",
"response",
".",
"redirect_chain",
",",
"msg_prefix",
"+",
"\"Response didn't redirect as expected: Response code was %d (expected %d)\"",
"%",
"(",
"response",
".",
"status_code",
",",
"status_code",
")",
")",
"self",
".",
"assertEqual",
"(",
"response",
".",
"redirect_chain",
"[",
"0",
"]",
"[",
"1",
"]",
",",
"status_code",
",",
"msg_prefix",
"+",
"\"Initial response didn't redirect as expected: Response code was %d (expected %d)\"",
"%",
"(",
"response",
".",
"redirect_chain",
"[",
"0",
"]",
"[",
"1",
"]",
",",
"status_code",
")",
")",
"url",
",",
"status_code",
"=",
"response",
".",
"redirect_chain",
"[",
"-",
"1",
"]",
"self",
".",
"assertEqual",
"(",
"response",
".",
"status_code",
",",
"target_status_code",
",",
"msg_prefix",
"+",
"\"Response didn't redirect as expected: Final Response code was %d (expected %d)\"",
"%",
"(",
"response",
".",
"status_code",
",",
"target_status_code",
")",
")",
"else",
":",
"# Not a followed redirect",
"self",
".",
"assertEqual",
"(",
"response",
".",
"status_code",
",",
"status_code",
",",
"msg_prefix",
"+",
"\"Response didn't redirect as expected: Response code was %d (expected %d)\"",
"%",
"(",
"response",
".",
"status_code",
",",
"status_code",
")",
")",
"url",
"=",
"response",
".",
"url",
"scheme",
",",
"netloc",
",",
"path",
",",
"query",
",",
"fragment",
"=",
"urlsplit",
"(",
"url",
")",
"# Prepend the request path to handle relative path redirects.",
"if",
"not",
"path",
".",
"startswith",
"(",
"'/'",
")",
":",
"url",
"=",
"urljoin",
"(",
"response",
".",
"request",
"[",
"'PATH_INFO'",
"]",
",",
"url",
")",
"path",
"=",
"urljoin",
"(",
"response",
".",
"request",
"[",
"'PATH_INFO'",
"]",
",",
"path",
")",
"if",
"fetch_redirect_response",
":",
"# netloc might be empty, or in cases where Django tests the",
"# HTTP scheme, the convention is for netloc to be 'testserver'.",
"# Trust both as \"internal\" URLs here.",
"domain",
",",
"port",
"=",
"split_domain_port",
"(",
"netloc",
")",
"if",
"domain",
"and",
"not",
"validate_host",
"(",
"domain",
",",
"settings",
".",
"ALLOWED_HOSTS",
")",
":",
"raise",
"ValueError",
"(",
"\"The test client is unable to fetch remote URLs (got %s). \"",
"\"If the host is served by Django, add '%s' to ALLOWED_HOSTS. \"",
"\"Otherwise, use assertRedirects(..., fetch_redirect_response=False).\"",
"%",
"(",
"url",
",",
"domain",
")",
")",
"# Get the redirection page, using the same client that was used",
"# to obtain the original response.",
"extra",
"=",
"response",
".",
"client",
".",
"extra",
"or",
"{",
"}",
"redirect_response",
"=",
"response",
".",
"client",
".",
"get",
"(",
"path",
",",
"QueryDict",
"(",
"query",
")",
",",
"secure",
"=",
"(",
"scheme",
"==",
"'https'",
")",
",",
"*",
"*",
"extra",
",",
")",
"self",
".",
"assertEqual",
"(",
"redirect_response",
".",
"status_code",
",",
"target_status_code",
",",
"msg_prefix",
"+",
"\"Couldn't retrieve redirection page '%s': response code was %d (expected %d)\"",
"%",
"(",
"path",
",",
"redirect_response",
".",
"status_code",
",",
"target_status_code",
")",
")",
"self",
".",
"assertURLEqual",
"(",
"url",
",",
"expected_url",
",",
"msg_prefix",
"+",
"\"Response redirected to '%s', expected '%s'\"",
"%",
"(",
"url",
",",
"expected_url",
")",
")"
] | [
318,
4
] | [
400,
9
] | python | en | ['en', 'error', 'th'] | False |
SimpleTestCase.assertURLEqual | (self, url1, url2, msg_prefix='') |
Assert that two URLs are the same, ignoring the order of query string
parameters except for parameters with the same name.
For example, /path/?x=1&y=2 is equal to /path/?y=2&x=1, but
/path/?a=1&a=2 isn't equal to /path/?a=2&a=1.
|
Assert that two URLs are the same, ignoring the order of query string
parameters except for parameters with the same name. | def assertURLEqual(self, url1, url2, msg_prefix=''):
"""
Assert that two URLs are the same, ignoring the order of query string
parameters except for parameters with the same name.
For example, /path/?x=1&y=2 is equal to /path/?y=2&x=1, but
/path/?a=1&a=2 isn't equal to /path/?a=2&a=1.
"""
def normalize(url):
"""Sort the URL's query string parameters."""
url = str(url) # Coerce reverse_lazy() URLs.
scheme, netloc, path, params, query, fragment = urlparse(url)
query_parts = sorted(parse_qsl(query))
return urlunparse((scheme, netloc, path, params, urlencode(query_parts), fragment))
self.assertEqual(
normalize(url1), normalize(url2),
msg_prefix + "Expected '%s' to equal '%s'." % (url1, url2)
) | [
"def",
"assertURLEqual",
"(",
"self",
",",
"url1",
",",
"url2",
",",
"msg_prefix",
"=",
"''",
")",
":",
"def",
"normalize",
"(",
"url",
")",
":",
"\"\"\"Sort the URL's query string parameters.\"\"\"",
"url",
"=",
"str",
"(",
"url",
")",
"# Coerce reverse_lazy() URLs.",
"scheme",
",",
"netloc",
",",
"path",
",",
"params",
",",
"query",
",",
"fragment",
"=",
"urlparse",
"(",
"url",
")",
"query_parts",
"=",
"sorted",
"(",
"parse_qsl",
"(",
"query",
")",
")",
"return",
"urlunparse",
"(",
"(",
"scheme",
",",
"netloc",
",",
"path",
",",
"params",
",",
"urlencode",
"(",
"query_parts",
")",
",",
"fragment",
")",
")",
"self",
".",
"assertEqual",
"(",
"normalize",
"(",
"url1",
")",
",",
"normalize",
"(",
"url2",
")",
",",
"msg_prefix",
"+",
"\"Expected '%s' to equal '%s'.\"",
"%",
"(",
"url1",
",",
"url2",
")",
")"
] | [
402,
4
] | [
420,
9
] | python | en | ['en', 'error', 'th'] | False |
SimpleTestCase.assertContains | (self, response, text, count=None, status_code=200, msg_prefix='', html=False) |
Assert that a response indicates that some content was retrieved
successfully, (i.e., the HTTP status code was as expected) and that
``text`` occurs ``count`` times in the content of the response.
If ``count`` is None, the count doesn't matter - the assertion is true
if the text occurs at least once in the response.
|
Assert that a response indicates that some content was retrieved
successfully, (i.e., the HTTP status code was as expected) and that
``text`` occurs ``count`` times in the content of the response.
If ``count`` is None, the count doesn't matter - the assertion is true
if the text occurs at least once in the response.
| def assertContains(self, response, text, count=None, status_code=200, msg_prefix='', html=False):
"""
Assert that a response indicates that some content was retrieved
successfully, (i.e., the HTTP status code was as expected) and that
``text`` occurs ``count`` times in the content of the response.
If ``count`` is None, the count doesn't matter - the assertion is true
if the text occurs at least once in the response.
"""
text_repr, real_count, msg_prefix = self._assert_contains(
response, text, status_code, msg_prefix, html)
if count is not None:
self.assertEqual(
real_count, count,
msg_prefix + "Found %d instances of %s in response (expected %d)" % (real_count, text_repr, count)
)
else:
self.assertTrue(real_count != 0, msg_prefix + "Couldn't find %s in response" % text_repr) | [
"def",
"assertContains",
"(",
"self",
",",
"response",
",",
"text",
",",
"count",
"=",
"None",
",",
"status_code",
"=",
"200",
",",
"msg_prefix",
"=",
"''",
",",
"html",
"=",
"False",
")",
":",
"text_repr",
",",
"real_count",
",",
"msg_prefix",
"=",
"self",
".",
"_assert_contains",
"(",
"response",
",",
"text",
",",
"status_code",
",",
"msg_prefix",
",",
"html",
")",
"if",
"count",
"is",
"not",
"None",
":",
"self",
".",
"assertEqual",
"(",
"real_count",
",",
"count",
",",
"msg_prefix",
"+",
"\"Found %d instances of %s in response (expected %d)\"",
"%",
"(",
"real_count",
",",
"text_repr",
",",
"count",
")",
")",
"else",
":",
"self",
".",
"assertTrue",
"(",
"real_count",
"!=",
"0",
",",
"msg_prefix",
"+",
"\"Couldn't find %s in response\"",
"%",
"text_repr",
")"
] | [
453,
4
] | [
470,
101
] | python | en | ['en', 'error', 'th'] | False |
SimpleTestCase.assertNotContains | (self, response, text, status_code=200, msg_prefix='', html=False) |
Assert that a response indicates that some content was retrieved
successfully, (i.e., the HTTP status code was as expected) and that
``text`` doesn't occurs in the content of the response.
|
Assert that a response indicates that some content was retrieved
successfully, (i.e., the HTTP status code was as expected) and that
``text`` doesn't occurs in the content of the response.
| def assertNotContains(self, response, text, status_code=200, msg_prefix='', html=False):
"""
Assert that a response indicates that some content was retrieved
successfully, (i.e., the HTTP status code was as expected) and that
``text`` doesn't occurs in the content of the response.
"""
text_repr, real_count, msg_prefix = self._assert_contains(
response, text, status_code, msg_prefix, html)
self.assertEqual(real_count, 0, msg_prefix + "Response should not contain %s" % text_repr) | [
"def",
"assertNotContains",
"(",
"self",
",",
"response",
",",
"text",
",",
"status_code",
"=",
"200",
",",
"msg_prefix",
"=",
"''",
",",
"html",
"=",
"False",
")",
":",
"text_repr",
",",
"real_count",
",",
"msg_prefix",
"=",
"self",
".",
"_assert_contains",
"(",
"response",
",",
"text",
",",
"status_code",
",",
"msg_prefix",
",",
"html",
")",
"self",
".",
"assertEqual",
"(",
"real_count",
",",
"0",
",",
"msg_prefix",
"+",
"\"Response should not contain %s\"",
"%",
"text_repr",
")"
] | [
472,
4
] | [
481,
98
] | python | en | ['en', 'error', 'th'] | False |
SimpleTestCase.assertFormError | (self, response, form, field, errors, msg_prefix='') |
Assert that a form used to render the response has a specific field
error.
|
Assert that a form used to render the response has a specific field
error.
| def assertFormError(self, response, form, field, errors, msg_prefix=''):
"""
Assert that a form used to render the response has a specific field
error.
"""
if msg_prefix:
msg_prefix += ": "
# Put context(s) into a list to simplify processing.
contexts = to_list(response.context)
if not contexts:
self.fail(msg_prefix + "Response did not use any contexts to render the response")
# Put error(s) into a list to simplify processing.
errors = to_list(errors)
# Search all contexts for the error.
found_form = False
for i, context in enumerate(contexts):
if form not in context:
continue
found_form = True
for err in errors:
if field:
if field in context[form].errors:
field_errors = context[form].errors[field]
self.assertTrue(
err in field_errors,
msg_prefix + "The field '%s' on form '%s' in"
" context %d does not contain the error '%s'"
" (actual errors: %s)" %
(field, form, i, err, repr(field_errors))
)
elif field in context[form].fields:
self.fail(
msg_prefix + "The field '%s' on form '%s' in context %d contains no errors" %
(field, form, i)
)
else:
self.fail(
msg_prefix + "The form '%s' in context %d does not contain the field '%s'" %
(form, i, field)
)
else:
non_field_errors = context[form].non_field_errors()
self.assertTrue(
err in non_field_errors,
msg_prefix + "The form '%s' in context %d does not"
" contain the non-field error '%s'"
" (actual errors: %s)" %
(form, i, err, non_field_errors or 'none')
)
if not found_form:
self.fail(msg_prefix + "The form '%s' was not used to render the response" % form) | [
"def",
"assertFormError",
"(",
"self",
",",
"response",
",",
"form",
",",
"field",
",",
"errors",
",",
"msg_prefix",
"=",
"''",
")",
":",
"if",
"msg_prefix",
":",
"msg_prefix",
"+=",
"\": \"",
"# Put context(s) into a list to simplify processing.",
"contexts",
"=",
"to_list",
"(",
"response",
".",
"context",
")",
"if",
"not",
"contexts",
":",
"self",
".",
"fail",
"(",
"msg_prefix",
"+",
"\"Response did not use any contexts to render the response\"",
")",
"# Put error(s) into a list to simplify processing.",
"errors",
"=",
"to_list",
"(",
"errors",
")",
"# Search all contexts for the error.",
"found_form",
"=",
"False",
"for",
"i",
",",
"context",
"in",
"enumerate",
"(",
"contexts",
")",
":",
"if",
"form",
"not",
"in",
"context",
":",
"continue",
"found_form",
"=",
"True",
"for",
"err",
"in",
"errors",
":",
"if",
"field",
":",
"if",
"field",
"in",
"context",
"[",
"form",
"]",
".",
"errors",
":",
"field_errors",
"=",
"context",
"[",
"form",
"]",
".",
"errors",
"[",
"field",
"]",
"self",
".",
"assertTrue",
"(",
"err",
"in",
"field_errors",
",",
"msg_prefix",
"+",
"\"The field '%s' on form '%s' in\"",
"\" context %d does not contain the error '%s'\"",
"\" (actual errors: %s)\"",
"%",
"(",
"field",
",",
"form",
",",
"i",
",",
"err",
",",
"repr",
"(",
"field_errors",
")",
")",
")",
"elif",
"field",
"in",
"context",
"[",
"form",
"]",
".",
"fields",
":",
"self",
".",
"fail",
"(",
"msg_prefix",
"+",
"\"The field '%s' on form '%s' in context %d contains no errors\"",
"%",
"(",
"field",
",",
"form",
",",
"i",
")",
")",
"else",
":",
"self",
".",
"fail",
"(",
"msg_prefix",
"+",
"\"The form '%s' in context %d does not contain the field '%s'\"",
"%",
"(",
"form",
",",
"i",
",",
"field",
")",
")",
"else",
":",
"non_field_errors",
"=",
"context",
"[",
"form",
"]",
".",
"non_field_errors",
"(",
")",
"self",
".",
"assertTrue",
"(",
"err",
"in",
"non_field_errors",
",",
"msg_prefix",
"+",
"\"The form '%s' in context %d does not\"",
"\" contain the non-field error '%s'\"",
"\" (actual errors: %s)\"",
"%",
"(",
"form",
",",
"i",
",",
"err",
",",
"non_field_errors",
"or",
"'none'",
")",
")",
"if",
"not",
"found_form",
":",
"self",
".",
"fail",
"(",
"msg_prefix",
"+",
"\"The form '%s' was not used to render the response\"",
"%",
"form",
")"
] | [
483,
4
] | [
536,
94
] | python | en | ['en', 'error', 'th'] | False |
SimpleTestCase.assertFormsetError | (self, response, formset, form_index, field, errors,
msg_prefix='') |
Assert that a formset used to render the response has a specific error.
For field errors, specify the ``form_index`` and the ``field``.
For non-field errors, specify the ``form_index`` and the ``field`` as
None.
For non-form errors, specify ``form_index`` as None and the ``field``
as None.
|
Assert that a formset used to render the response has a specific error. | def assertFormsetError(self, response, formset, form_index, field, errors,
msg_prefix=''):
"""
Assert that a formset used to render the response has a specific error.
For field errors, specify the ``form_index`` and the ``field``.
For non-field errors, specify the ``form_index`` and the ``field`` as
None.
For non-form errors, specify ``form_index`` as None and the ``field``
as None.
"""
# Add punctuation to msg_prefix
if msg_prefix:
msg_prefix += ": "
# Put context(s) into a list to simplify processing.
contexts = to_list(response.context)
if not contexts:
self.fail(msg_prefix + 'Response did not use any contexts to '
'render the response')
# Put error(s) into a list to simplify processing.
errors = to_list(errors)
# Search all contexts for the error.
found_formset = False
for i, context in enumerate(contexts):
if formset not in context:
continue
found_formset = True
for err in errors:
if field is not None:
if field in context[formset].forms[form_index].errors:
field_errors = context[formset].forms[form_index].errors[field]
self.assertTrue(
err in field_errors,
msg_prefix + "The field '%s' on formset '%s', "
"form %d in context %d does not contain the "
"error '%s' (actual errors: %s)" %
(field, formset, form_index, i, err, repr(field_errors))
)
elif field in context[formset].forms[form_index].fields:
self.fail(
msg_prefix + "The field '%s' on formset '%s', form %d in context %d contains no errors"
% (field, formset, form_index, i)
)
else:
self.fail(
msg_prefix + "The formset '%s', form %d in context %d does not contain the field '%s'"
% (formset, form_index, i, field)
)
elif form_index is not None:
non_field_errors = context[formset].forms[form_index].non_field_errors()
self.assertFalse(
not non_field_errors,
msg_prefix + "The formset '%s', form %d in context %d "
"does not contain any non-field errors." % (formset, form_index, i)
)
self.assertTrue(
err in non_field_errors,
msg_prefix + "The formset '%s', form %d in context %d "
"does not contain the non-field error '%s' (actual errors: %s)"
% (formset, form_index, i, err, repr(non_field_errors))
)
else:
non_form_errors = context[formset].non_form_errors()
self.assertFalse(
not non_form_errors,
msg_prefix + "The formset '%s' in context %d does not "
"contain any non-form errors." % (formset, i)
)
self.assertTrue(
err in non_form_errors,
msg_prefix + "The formset '%s' in context %d does not "
"contain the non-form error '%s' (actual errors: %s)"
% (formset, i, err, repr(non_form_errors))
)
if not found_formset:
self.fail(msg_prefix + "The formset '%s' was not used to render the response" % formset) | [
"def",
"assertFormsetError",
"(",
"self",
",",
"response",
",",
"formset",
",",
"form_index",
",",
"field",
",",
"errors",
",",
"msg_prefix",
"=",
"''",
")",
":",
"# Add punctuation to msg_prefix",
"if",
"msg_prefix",
":",
"msg_prefix",
"+=",
"\": \"",
"# Put context(s) into a list to simplify processing.",
"contexts",
"=",
"to_list",
"(",
"response",
".",
"context",
")",
"if",
"not",
"contexts",
":",
"self",
".",
"fail",
"(",
"msg_prefix",
"+",
"'Response did not use any contexts to '",
"'render the response'",
")",
"# Put error(s) into a list to simplify processing.",
"errors",
"=",
"to_list",
"(",
"errors",
")",
"# Search all contexts for the error.",
"found_formset",
"=",
"False",
"for",
"i",
",",
"context",
"in",
"enumerate",
"(",
"contexts",
")",
":",
"if",
"formset",
"not",
"in",
"context",
":",
"continue",
"found_formset",
"=",
"True",
"for",
"err",
"in",
"errors",
":",
"if",
"field",
"is",
"not",
"None",
":",
"if",
"field",
"in",
"context",
"[",
"formset",
"]",
".",
"forms",
"[",
"form_index",
"]",
".",
"errors",
":",
"field_errors",
"=",
"context",
"[",
"formset",
"]",
".",
"forms",
"[",
"form_index",
"]",
".",
"errors",
"[",
"field",
"]",
"self",
".",
"assertTrue",
"(",
"err",
"in",
"field_errors",
",",
"msg_prefix",
"+",
"\"The field '%s' on formset '%s', \"",
"\"form %d in context %d does not contain the \"",
"\"error '%s' (actual errors: %s)\"",
"%",
"(",
"field",
",",
"formset",
",",
"form_index",
",",
"i",
",",
"err",
",",
"repr",
"(",
"field_errors",
")",
")",
")",
"elif",
"field",
"in",
"context",
"[",
"formset",
"]",
".",
"forms",
"[",
"form_index",
"]",
".",
"fields",
":",
"self",
".",
"fail",
"(",
"msg_prefix",
"+",
"\"The field '%s' on formset '%s', form %d in context %d contains no errors\"",
"%",
"(",
"field",
",",
"formset",
",",
"form_index",
",",
"i",
")",
")",
"else",
":",
"self",
".",
"fail",
"(",
"msg_prefix",
"+",
"\"The formset '%s', form %d in context %d does not contain the field '%s'\"",
"%",
"(",
"formset",
",",
"form_index",
",",
"i",
",",
"field",
")",
")",
"elif",
"form_index",
"is",
"not",
"None",
":",
"non_field_errors",
"=",
"context",
"[",
"formset",
"]",
".",
"forms",
"[",
"form_index",
"]",
".",
"non_field_errors",
"(",
")",
"self",
".",
"assertFalse",
"(",
"not",
"non_field_errors",
",",
"msg_prefix",
"+",
"\"The formset '%s', form %d in context %d \"",
"\"does not contain any non-field errors.\"",
"%",
"(",
"formset",
",",
"form_index",
",",
"i",
")",
")",
"self",
".",
"assertTrue",
"(",
"err",
"in",
"non_field_errors",
",",
"msg_prefix",
"+",
"\"The formset '%s', form %d in context %d \"",
"\"does not contain the non-field error '%s' (actual errors: %s)\"",
"%",
"(",
"formset",
",",
"form_index",
",",
"i",
",",
"err",
",",
"repr",
"(",
"non_field_errors",
")",
")",
")",
"else",
":",
"non_form_errors",
"=",
"context",
"[",
"formset",
"]",
".",
"non_form_errors",
"(",
")",
"self",
".",
"assertFalse",
"(",
"not",
"non_form_errors",
",",
"msg_prefix",
"+",
"\"The formset '%s' in context %d does not \"",
"\"contain any non-form errors.\"",
"%",
"(",
"formset",
",",
"i",
")",
")",
"self",
".",
"assertTrue",
"(",
"err",
"in",
"non_form_errors",
",",
"msg_prefix",
"+",
"\"The formset '%s' in context %d does not \"",
"\"contain the non-form error '%s' (actual errors: %s)\"",
"%",
"(",
"formset",
",",
"i",
",",
"err",
",",
"repr",
"(",
"non_form_errors",
")",
")",
")",
"if",
"not",
"found_formset",
":",
"self",
".",
"fail",
"(",
"msg_prefix",
"+",
"\"The formset '%s' was not used to render the response\"",
"%",
"formset",
")"
] | [
538,
4
] | [
616,
100
] | python | en | ['en', 'error', 'th'] | False |
SimpleTestCase.assertTemplateUsed | (self, response=None, template_name=None, msg_prefix='', count=None) |
Assert that the template with the provided name was used in rendering
the response. Also usable as context manager.
|
Assert that the template with the provided name was used in rendering
the response. Also usable as context manager.
| def assertTemplateUsed(self, response=None, template_name=None, msg_prefix='', count=None):
"""
Assert that the template with the provided name was used in rendering
the response. Also usable as context manager.
"""
context_mgr_template, template_names, msg_prefix = self._assert_template_used(
response, template_name, msg_prefix)
if context_mgr_template:
# Use assertTemplateUsed as context manager.
return _AssertTemplateUsedContext(self, context_mgr_template)
if not template_names:
self.fail(msg_prefix + "No templates used to render the response")
self.assertTrue(
template_name in template_names,
msg_prefix + "Template '%s' was not a template used to render"
" the response. Actual template(s) used: %s"
% (template_name, ', '.join(template_names))
)
if count is not None:
self.assertEqual(
template_names.count(template_name), count,
msg_prefix + "Template '%s' was expected to be rendered %d "
"time(s) but was actually rendered %d time(s)."
% (template_name, count, template_names.count(template_name))
) | [
"def",
"assertTemplateUsed",
"(",
"self",
",",
"response",
"=",
"None",
",",
"template_name",
"=",
"None",
",",
"msg_prefix",
"=",
"''",
",",
"count",
"=",
"None",
")",
":",
"context_mgr_template",
",",
"template_names",
",",
"msg_prefix",
"=",
"self",
".",
"_assert_template_used",
"(",
"response",
",",
"template_name",
",",
"msg_prefix",
")",
"if",
"context_mgr_template",
":",
"# Use assertTemplateUsed as context manager.",
"return",
"_AssertTemplateUsedContext",
"(",
"self",
",",
"context_mgr_template",
")",
"if",
"not",
"template_names",
":",
"self",
".",
"fail",
"(",
"msg_prefix",
"+",
"\"No templates used to render the response\"",
")",
"self",
".",
"assertTrue",
"(",
"template_name",
"in",
"template_names",
",",
"msg_prefix",
"+",
"\"Template '%s' was not a template used to render\"",
"\" the response. Actual template(s) used: %s\"",
"%",
"(",
"template_name",
",",
"', '",
".",
"join",
"(",
"template_names",
")",
")",
")",
"if",
"count",
"is",
"not",
"None",
":",
"self",
".",
"assertEqual",
"(",
"template_names",
".",
"count",
"(",
"template_name",
")",
",",
"count",
",",
"msg_prefix",
"+",
"\"Template '%s' was expected to be rendered %d \"",
"\"time(s) but was actually rendered %d time(s).\"",
"%",
"(",
"template_name",
",",
"count",
",",
"template_names",
".",
"count",
"(",
"template_name",
")",
")",
")"
] | [
642,
4
] | [
669,
13
] | python | en | ['en', 'error', 'th'] | False |
SimpleTestCase.assertTemplateNotUsed | (self, response=None, template_name=None, msg_prefix='') |
Assert that the template with the provided name was NOT used in
rendering the response. Also usable as context manager.
|
Assert that the template with the provided name was NOT used in
rendering the response. Also usable as context manager.
| def assertTemplateNotUsed(self, response=None, template_name=None, msg_prefix=''):
"""
Assert that the template with the provided name was NOT used in
rendering the response. Also usable as context manager.
"""
context_mgr_template, template_names, msg_prefix = self._assert_template_used(
response, template_name, msg_prefix
)
if context_mgr_template:
# Use assertTemplateNotUsed as context manager.
return _AssertTemplateNotUsedContext(self, context_mgr_template)
self.assertFalse(
template_name in template_names,
msg_prefix + "Template '%s' was used unexpectedly in rendering the response" % template_name
) | [
"def",
"assertTemplateNotUsed",
"(",
"self",
",",
"response",
"=",
"None",
",",
"template_name",
"=",
"None",
",",
"msg_prefix",
"=",
"''",
")",
":",
"context_mgr_template",
",",
"template_names",
",",
"msg_prefix",
"=",
"self",
".",
"_assert_template_used",
"(",
"response",
",",
"template_name",
",",
"msg_prefix",
")",
"if",
"context_mgr_template",
":",
"# Use assertTemplateNotUsed as context manager.",
"return",
"_AssertTemplateNotUsedContext",
"(",
"self",
",",
"context_mgr_template",
")",
"self",
".",
"assertFalse",
"(",
"template_name",
"in",
"template_names",
",",
"msg_prefix",
"+",
"\"Template '%s' was used unexpectedly in rendering the response\"",
"%",
"template_name",
")"
] | [
671,
4
] | [
686,
9
] | python | en | ['en', 'error', 'th'] | False |
SimpleTestCase.assertRaisesMessage | (self, expected_exception, expected_message, *args, **kwargs) |
Assert that expected_message is found in the message of a raised
exception.
Args:
expected_exception: Exception class expected to be raised.
expected_message: expected error message string value.
args: Function to be called and extra positional args.
kwargs: Extra kwargs.
|
Assert that expected_message is found in the message of a raised
exception. | def assertRaisesMessage(self, expected_exception, expected_message, *args, **kwargs):
"""
Assert that expected_message is found in the message of a raised
exception.
Args:
expected_exception: Exception class expected to be raised.
expected_message: expected error message string value.
args: Function to be called and extra positional args.
kwargs: Extra kwargs.
"""
return self._assertFooMessage(
self.assertRaises, 'exception', expected_exception, expected_message,
*args, **kwargs
) | [
"def",
"assertRaisesMessage",
"(",
"self",
",",
"expected_exception",
",",
"expected_message",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"_assertFooMessage",
"(",
"self",
".",
"assertRaises",
",",
"'exception'",
",",
"expected_exception",
",",
"expected_message",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | [
706,
4
] | [
720,
9
] | python | en | ['en', 'error', 'th'] | False |
SimpleTestCase.assertWarnsMessage | (self, expected_warning, expected_message, *args, **kwargs) |
Same as assertRaisesMessage but for assertWarns() instead of
assertRaises().
|
Same as assertRaisesMessage but for assertWarns() instead of
assertRaises().
| def assertWarnsMessage(self, expected_warning, expected_message, *args, **kwargs):
"""
Same as assertRaisesMessage but for assertWarns() instead of
assertRaises().
"""
return self._assertFooMessage(
self.assertWarns, 'warning', expected_warning, expected_message,
*args, **kwargs
) | [
"def",
"assertWarnsMessage",
"(",
"self",
",",
"expected_warning",
",",
"expected_message",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"_assertFooMessage",
"(",
"self",
".",
"assertWarns",
",",
"'warning'",
",",
"expected_warning",
",",
"expected_message",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | [
722,
4
] | [
730,
9
] | python | en | ['en', 'error', 'th'] | False |
SimpleTestCase.assertFieldOutput | (self, fieldclass, valid, invalid, field_args=None,
field_kwargs=None, empty_value='') |
Assert that a form field behaves correctly with various inputs.
Args:
fieldclass: the class of the field to be tested.
valid: a dictionary mapping valid inputs to their expected
cleaned values.
invalid: a dictionary mapping invalid inputs to one or more
raised error messages.
field_args: the args passed to instantiate the field
field_kwargs: the kwargs passed to instantiate the field
empty_value: the expected clean output for inputs in empty_values
|
Assert that a form field behaves correctly with various inputs. | def assertFieldOutput(self, fieldclass, valid, invalid, field_args=None,
field_kwargs=None, empty_value=''):
"""
Assert that a form field behaves correctly with various inputs.
Args:
fieldclass: the class of the field to be tested.
valid: a dictionary mapping valid inputs to their expected
cleaned values.
invalid: a dictionary mapping invalid inputs to one or more
raised error messages.
field_args: the args passed to instantiate the field
field_kwargs: the kwargs passed to instantiate the field
empty_value: the expected clean output for inputs in empty_values
"""
if field_args is None:
field_args = []
if field_kwargs is None:
field_kwargs = {}
required = fieldclass(*field_args, **field_kwargs)
optional = fieldclass(*field_args, **{**field_kwargs, 'required': False})
# test valid inputs
for input, output in valid.items():
self.assertEqual(required.clean(input), output)
self.assertEqual(optional.clean(input), output)
# test invalid inputs
for input, errors in invalid.items():
with self.assertRaises(ValidationError) as context_manager:
required.clean(input)
self.assertEqual(context_manager.exception.messages, errors)
with self.assertRaises(ValidationError) as context_manager:
optional.clean(input)
self.assertEqual(context_manager.exception.messages, errors)
# test required inputs
error_required = [required.error_messages['required']]
for e in required.empty_values:
with self.assertRaises(ValidationError) as context_manager:
required.clean(e)
self.assertEqual(context_manager.exception.messages, error_required)
self.assertEqual(optional.clean(e), empty_value)
# test that max_length and min_length are always accepted
if issubclass(fieldclass, CharField):
field_kwargs.update({'min_length': 2, 'max_length': 20})
self.assertIsInstance(fieldclass(*field_args, **field_kwargs), fieldclass) | [
"def",
"assertFieldOutput",
"(",
"self",
",",
"fieldclass",
",",
"valid",
",",
"invalid",
",",
"field_args",
"=",
"None",
",",
"field_kwargs",
"=",
"None",
",",
"empty_value",
"=",
"''",
")",
":",
"if",
"field_args",
"is",
"None",
":",
"field_args",
"=",
"[",
"]",
"if",
"field_kwargs",
"is",
"None",
":",
"field_kwargs",
"=",
"{",
"}",
"required",
"=",
"fieldclass",
"(",
"*",
"field_args",
",",
"*",
"*",
"field_kwargs",
")",
"optional",
"=",
"fieldclass",
"(",
"*",
"field_args",
",",
"*",
"*",
"{",
"*",
"*",
"field_kwargs",
",",
"'required'",
":",
"False",
"}",
")",
"# test valid inputs",
"for",
"input",
",",
"output",
"in",
"valid",
".",
"items",
"(",
")",
":",
"self",
".",
"assertEqual",
"(",
"required",
".",
"clean",
"(",
"input",
")",
",",
"output",
")",
"self",
".",
"assertEqual",
"(",
"optional",
".",
"clean",
"(",
"input",
")",
",",
"output",
")",
"# test invalid inputs",
"for",
"input",
",",
"errors",
"in",
"invalid",
".",
"items",
"(",
")",
":",
"with",
"self",
".",
"assertRaises",
"(",
"ValidationError",
")",
"as",
"context_manager",
":",
"required",
".",
"clean",
"(",
"input",
")",
"self",
".",
"assertEqual",
"(",
"context_manager",
".",
"exception",
".",
"messages",
",",
"errors",
")",
"with",
"self",
".",
"assertRaises",
"(",
"ValidationError",
")",
"as",
"context_manager",
":",
"optional",
".",
"clean",
"(",
"input",
")",
"self",
".",
"assertEqual",
"(",
"context_manager",
".",
"exception",
".",
"messages",
",",
"errors",
")",
"# test required inputs",
"error_required",
"=",
"[",
"required",
".",
"error_messages",
"[",
"'required'",
"]",
"]",
"for",
"e",
"in",
"required",
".",
"empty_values",
":",
"with",
"self",
".",
"assertRaises",
"(",
"ValidationError",
")",
"as",
"context_manager",
":",
"required",
".",
"clean",
"(",
"e",
")",
"self",
".",
"assertEqual",
"(",
"context_manager",
".",
"exception",
".",
"messages",
",",
"error_required",
")",
"self",
".",
"assertEqual",
"(",
"optional",
".",
"clean",
"(",
"e",
")",
",",
"empty_value",
")",
"# test that max_length and min_length are always accepted",
"if",
"issubclass",
"(",
"fieldclass",
",",
"CharField",
")",
":",
"field_kwargs",
".",
"update",
"(",
"{",
"'min_length'",
":",
"2",
",",
"'max_length'",
":",
"20",
"}",
")",
"self",
".",
"assertIsInstance",
"(",
"fieldclass",
"(",
"*",
"field_args",
",",
"*",
"*",
"field_kwargs",
")",
",",
"fieldclass",
")"
] | [
732,
4
] | [
776,
86
] | python | en | ['en', 'error', 'th'] | False |
SimpleTestCase.assertHTMLEqual | (self, html1, html2, msg=None) |
Assert that two HTML snippets are semantically the same.
Whitespace in most cases is ignored, and attribute ordering is not
significant. The arguments must be valid HTML.
|
Assert that two HTML snippets are semantically the same.
Whitespace in most cases is ignored, and attribute ordering is not
significant. The arguments must be valid HTML.
| def assertHTMLEqual(self, html1, html2, msg=None):
"""
Assert that two HTML snippets are semantically the same.
Whitespace in most cases is ignored, and attribute ordering is not
significant. The arguments must be valid HTML.
"""
dom1 = assert_and_parse_html(self, html1, msg, 'First argument is not valid HTML:')
dom2 = assert_and_parse_html(self, html2, msg, 'Second argument is not valid HTML:')
if dom1 != dom2:
standardMsg = '%s != %s' % (
safe_repr(dom1, True), safe_repr(dom2, True))
diff = ('\n' + '\n'.join(difflib.ndiff(
str(dom1).splitlines(), str(dom2).splitlines(),
)))
standardMsg = self._truncateMessage(standardMsg, diff)
self.fail(self._formatMessage(msg, standardMsg)) | [
"def",
"assertHTMLEqual",
"(",
"self",
",",
"html1",
",",
"html2",
",",
"msg",
"=",
"None",
")",
":",
"dom1",
"=",
"assert_and_parse_html",
"(",
"self",
",",
"html1",
",",
"msg",
",",
"'First argument is not valid HTML:'",
")",
"dom2",
"=",
"assert_and_parse_html",
"(",
"self",
",",
"html2",
",",
"msg",
",",
"'Second argument is not valid HTML:'",
")",
"if",
"dom1",
"!=",
"dom2",
":",
"standardMsg",
"=",
"'%s != %s'",
"%",
"(",
"safe_repr",
"(",
"dom1",
",",
"True",
")",
",",
"safe_repr",
"(",
"dom2",
",",
"True",
")",
")",
"diff",
"=",
"(",
"'\\n'",
"+",
"'\\n'",
".",
"join",
"(",
"difflib",
".",
"ndiff",
"(",
"str",
"(",
"dom1",
")",
".",
"splitlines",
"(",
")",
",",
"str",
"(",
"dom2",
")",
".",
"splitlines",
"(",
")",
",",
")",
")",
")",
"standardMsg",
"=",
"self",
".",
"_truncateMessage",
"(",
"standardMsg",
",",
"diff",
")",
"self",
".",
"fail",
"(",
"self",
".",
"_formatMessage",
"(",
"msg",
",",
"standardMsg",
")",
")"
] | [
778,
4
] | [
794,
60
] | python | en | ['en', 'error', 'th'] | False |
SimpleTestCase.assertHTMLNotEqual | (self, html1, html2, msg=None) | Assert that two HTML snippets are not semantically equivalent. | Assert that two HTML snippets are not semantically equivalent. | def assertHTMLNotEqual(self, html1, html2, msg=None):
"""Assert that two HTML snippets are not semantically equivalent."""
dom1 = assert_and_parse_html(self, html1, msg, 'First argument is not valid HTML:')
dom2 = assert_and_parse_html(self, html2, msg, 'Second argument is not valid HTML:')
if dom1 == dom2:
standardMsg = '%s == %s' % (
safe_repr(dom1, True), safe_repr(dom2, True))
self.fail(self._formatMessage(msg, standardMsg)) | [
"def",
"assertHTMLNotEqual",
"(",
"self",
",",
"html1",
",",
"html2",
",",
"msg",
"=",
"None",
")",
":",
"dom1",
"=",
"assert_and_parse_html",
"(",
"self",
",",
"html1",
",",
"msg",
",",
"'First argument is not valid HTML:'",
")",
"dom2",
"=",
"assert_and_parse_html",
"(",
"self",
",",
"html2",
",",
"msg",
",",
"'Second argument is not valid HTML:'",
")",
"if",
"dom1",
"==",
"dom2",
":",
"standardMsg",
"=",
"'%s == %s'",
"%",
"(",
"safe_repr",
"(",
"dom1",
",",
"True",
")",
",",
"safe_repr",
"(",
"dom2",
",",
"True",
")",
")",
"self",
".",
"fail",
"(",
"self",
".",
"_formatMessage",
"(",
"msg",
",",
"standardMsg",
")",
")"
] | [
796,
4
] | [
804,
60
] | python | en | ['en', 'en', 'en'] | True |
SimpleTestCase.assertJSONEqual | (self, raw, expected_data, msg=None) |
Assert that the JSON fragments raw and expected_data are equal.
Usual JSON non-significant whitespace rules apply as the heavyweight
is delegated to the json library.
|
Assert that the JSON fragments raw and expected_data are equal.
Usual JSON non-significant whitespace rules apply as the heavyweight
is delegated to the json library.
| def assertJSONEqual(self, raw, expected_data, msg=None):
"""
Assert that the JSON fragments raw and expected_data are equal.
Usual JSON non-significant whitespace rules apply as the heavyweight
is delegated to the json library.
"""
try:
data = json.loads(raw)
except json.JSONDecodeError:
self.fail("First argument is not valid JSON: %r" % raw)
if isinstance(expected_data, str):
try:
expected_data = json.loads(expected_data)
except ValueError:
self.fail("Second argument is not valid JSON: %r" % expected_data)
self.assertEqual(data, expected_data, msg=msg) | [
"def",
"assertJSONEqual",
"(",
"self",
",",
"raw",
",",
"expected_data",
",",
"msg",
"=",
"None",
")",
":",
"try",
":",
"data",
"=",
"json",
".",
"loads",
"(",
"raw",
")",
"except",
"json",
".",
"JSONDecodeError",
":",
"self",
".",
"fail",
"(",
"\"First argument is not valid JSON: %r\"",
"%",
"raw",
")",
"if",
"isinstance",
"(",
"expected_data",
",",
"str",
")",
":",
"try",
":",
"expected_data",
"=",
"json",
".",
"loads",
"(",
"expected_data",
")",
"except",
"ValueError",
":",
"self",
".",
"fail",
"(",
"\"Second argument is not valid JSON: %r\"",
"%",
"expected_data",
")",
"self",
".",
"assertEqual",
"(",
"data",
",",
"expected_data",
",",
"msg",
"=",
"msg",
")"
] | [
818,
4
] | [
833,
54
] | python | en | ['en', 'error', 'th'] | False |
SimpleTestCase.assertJSONNotEqual | (self, raw, expected_data, msg=None) |
Assert that the JSON fragments raw and expected_data are not equal.
Usual JSON non-significant whitespace rules apply as the heavyweight
is delegated to the json library.
|
Assert that the JSON fragments raw and expected_data are not equal.
Usual JSON non-significant whitespace rules apply as the heavyweight
is delegated to the json library.
| def assertJSONNotEqual(self, raw, expected_data, msg=None):
"""
Assert that the JSON fragments raw and expected_data are not equal.
Usual JSON non-significant whitespace rules apply as the heavyweight
is delegated to the json library.
"""
try:
data = json.loads(raw)
except json.JSONDecodeError:
self.fail("First argument is not valid JSON: %r" % raw)
if isinstance(expected_data, str):
try:
expected_data = json.loads(expected_data)
except json.JSONDecodeError:
self.fail("Second argument is not valid JSON: %r" % expected_data)
self.assertNotEqual(data, expected_data, msg=msg) | [
"def",
"assertJSONNotEqual",
"(",
"self",
",",
"raw",
",",
"expected_data",
",",
"msg",
"=",
"None",
")",
":",
"try",
":",
"data",
"=",
"json",
".",
"loads",
"(",
"raw",
")",
"except",
"json",
".",
"JSONDecodeError",
":",
"self",
".",
"fail",
"(",
"\"First argument is not valid JSON: %r\"",
"%",
"raw",
")",
"if",
"isinstance",
"(",
"expected_data",
",",
"str",
")",
":",
"try",
":",
"expected_data",
"=",
"json",
".",
"loads",
"(",
"expected_data",
")",
"except",
"json",
".",
"JSONDecodeError",
":",
"self",
".",
"fail",
"(",
"\"Second argument is not valid JSON: %r\"",
"%",
"expected_data",
")",
"self",
".",
"assertNotEqual",
"(",
"data",
",",
"expected_data",
",",
"msg",
"=",
"msg",
")"
] | [
835,
4
] | [
850,
57
] | python | en | ['en', 'error', 'th'] | False |
SimpleTestCase.assertXMLEqual | (self, xml1, xml2, msg=None) |
Assert that two XML snippets are semantically the same.
Whitespace in most cases is ignored and attribute ordering is not
significant. The arguments must be valid XML.
|
Assert that two XML snippets are semantically the same.
Whitespace in most cases is ignored and attribute ordering is not
significant. The arguments must be valid XML.
| def assertXMLEqual(self, xml1, xml2, msg=None):
"""
Assert that two XML snippets are semantically the same.
Whitespace in most cases is ignored and attribute ordering is not
significant. The arguments must be valid XML.
"""
try:
result = compare_xml(xml1, xml2)
except Exception as e:
standardMsg = 'First or second argument is not valid XML\n%s' % e
self.fail(self._formatMessage(msg, standardMsg))
else:
if not result:
standardMsg = '%s != %s' % (safe_repr(xml1, True), safe_repr(xml2, True))
diff = ('\n' + '\n'.join(
difflib.ndiff(xml1.splitlines(), xml2.splitlines())
))
standardMsg = self._truncateMessage(standardMsg, diff)
self.fail(self._formatMessage(msg, standardMsg)) | [
"def",
"assertXMLEqual",
"(",
"self",
",",
"xml1",
",",
"xml2",
",",
"msg",
"=",
"None",
")",
":",
"try",
":",
"result",
"=",
"compare_xml",
"(",
"xml1",
",",
"xml2",
")",
"except",
"Exception",
"as",
"e",
":",
"standardMsg",
"=",
"'First or second argument is not valid XML\\n%s'",
"%",
"e",
"self",
".",
"fail",
"(",
"self",
".",
"_formatMessage",
"(",
"msg",
",",
"standardMsg",
")",
")",
"else",
":",
"if",
"not",
"result",
":",
"standardMsg",
"=",
"'%s != %s'",
"%",
"(",
"safe_repr",
"(",
"xml1",
",",
"True",
")",
",",
"safe_repr",
"(",
"xml2",
",",
"True",
")",
")",
"diff",
"=",
"(",
"'\\n'",
"+",
"'\\n'",
".",
"join",
"(",
"difflib",
".",
"ndiff",
"(",
"xml1",
".",
"splitlines",
"(",
")",
",",
"xml2",
".",
"splitlines",
"(",
")",
")",
")",
")",
"standardMsg",
"=",
"self",
".",
"_truncateMessage",
"(",
"standardMsg",
",",
"diff",
")",
"self",
".",
"fail",
"(",
"self",
".",
"_formatMessage",
"(",
"msg",
",",
"standardMsg",
")",
")"
] | [
852,
4
] | [
870,
64
] | python | en | ['en', 'error', 'th'] | False |
SimpleTestCase.assertXMLNotEqual | (self, xml1, xml2, msg=None) |
Assert that two XML snippets are not semantically equivalent.
Whitespace in most cases is ignored and attribute ordering is not
significant. The arguments must be valid XML.
|
Assert that two XML snippets are not semantically equivalent.
Whitespace in most cases is ignored and attribute ordering is not
significant. The arguments must be valid XML.
| def assertXMLNotEqual(self, xml1, xml2, msg=None):
"""
Assert that two XML snippets are not semantically equivalent.
Whitespace in most cases is ignored and attribute ordering is not
significant. The arguments must be valid XML.
"""
try:
result = compare_xml(xml1, xml2)
except Exception as e:
standardMsg = 'First or second argument is not valid XML\n%s' % e
self.fail(self._formatMessage(msg, standardMsg))
else:
if result:
standardMsg = '%s == %s' % (safe_repr(xml1, True), safe_repr(xml2, True))
self.fail(self._formatMessage(msg, standardMsg)) | [
"def",
"assertXMLNotEqual",
"(",
"self",
",",
"xml1",
",",
"xml2",
",",
"msg",
"=",
"None",
")",
":",
"try",
":",
"result",
"=",
"compare_xml",
"(",
"xml1",
",",
"xml2",
")",
"except",
"Exception",
"as",
"e",
":",
"standardMsg",
"=",
"'First or second argument is not valid XML\\n%s'",
"%",
"e",
"self",
".",
"fail",
"(",
"self",
".",
"_formatMessage",
"(",
"msg",
",",
"standardMsg",
")",
")",
"else",
":",
"if",
"result",
":",
"standardMsg",
"=",
"'%s == %s'",
"%",
"(",
"safe_repr",
"(",
"xml1",
",",
"True",
")",
",",
"safe_repr",
"(",
"xml2",
",",
"True",
")",
")",
"self",
".",
"fail",
"(",
"self",
".",
"_formatMessage",
"(",
"msg",
",",
"standardMsg",
")",
")"
] | [
872,
4
] | [
886,
64
] | python | en | ['en', 'error', 'th'] | False |
TransactionTestCase._pre_setup | (self) |
Perform pre-test setup:
* If the class has an 'available_apps' attribute, restrict the app
registry to these applications, then fire the post_migrate signal --
it must run with the correct set of applications for the test case.
* If the class has a 'fixtures' attribute, install those fixtures.
|
Perform pre-test setup:
* If the class has an 'available_apps' attribute, restrict the app
registry to these applications, then fire the post_migrate signal --
it must run with the correct set of applications for the test case.
* If the class has a 'fixtures' attribute, install those fixtures.
| def _pre_setup(self):
"""
Perform pre-test setup:
* If the class has an 'available_apps' attribute, restrict the app
registry to these applications, then fire the post_migrate signal --
it must run with the correct set of applications for the test case.
* If the class has a 'fixtures' attribute, install those fixtures.
"""
super()._pre_setup()
if self.available_apps is not None:
apps.set_available_apps(self.available_apps)
setting_changed.send(
sender=settings._wrapped.__class__,
setting='INSTALLED_APPS',
value=self.available_apps,
enter=True,
)
for db_name in self._databases_names(include_mirrors=False):
emit_post_migrate_signal(verbosity=0, interactive=False, db=db_name)
try:
self._fixture_setup()
except Exception:
if self.available_apps is not None:
apps.unset_available_apps()
setting_changed.send(
sender=settings._wrapped.__class__,
setting='INSTALLED_APPS',
value=settings.INSTALLED_APPS,
enter=False,
)
raise
# Clear the queries_log so that it's less likely to overflow (a single
# test probably won't execute 9K queries). If queries_log overflows,
# then assertNumQueries() doesn't work.
for db_name in self._databases_names(include_mirrors=False):
connections[db_name].queries_log.clear() | [
"def",
"_pre_setup",
"(",
"self",
")",
":",
"super",
"(",
")",
".",
"_pre_setup",
"(",
")",
"if",
"self",
".",
"available_apps",
"is",
"not",
"None",
":",
"apps",
".",
"set_available_apps",
"(",
"self",
".",
"available_apps",
")",
"setting_changed",
".",
"send",
"(",
"sender",
"=",
"settings",
".",
"_wrapped",
".",
"__class__",
",",
"setting",
"=",
"'INSTALLED_APPS'",
",",
"value",
"=",
"self",
".",
"available_apps",
",",
"enter",
"=",
"True",
",",
")",
"for",
"db_name",
"in",
"self",
".",
"_databases_names",
"(",
"include_mirrors",
"=",
"False",
")",
":",
"emit_post_migrate_signal",
"(",
"verbosity",
"=",
"0",
",",
"interactive",
"=",
"False",
",",
"db",
"=",
"db_name",
")",
"try",
":",
"self",
".",
"_fixture_setup",
"(",
")",
"except",
"Exception",
":",
"if",
"self",
".",
"available_apps",
"is",
"not",
"None",
":",
"apps",
".",
"unset_available_apps",
"(",
")",
"setting_changed",
".",
"send",
"(",
"sender",
"=",
"settings",
".",
"_wrapped",
".",
"__class__",
",",
"setting",
"=",
"'INSTALLED_APPS'",
",",
"value",
"=",
"settings",
".",
"INSTALLED_APPS",
",",
"enter",
"=",
"False",
",",
")",
"raise",
"# Clear the queries_log so that it's less likely to overflow (a single",
"# test probably won't execute 9K queries). If queries_log overflows,",
"# then assertNumQueries() doesn't work.",
"for",
"db_name",
"in",
"self",
".",
"_databases_names",
"(",
"include_mirrors",
"=",
"False",
")",
":",
"connections",
"[",
"db_name",
"]",
".",
"queries_log",
".",
"clear",
"(",
")"
] | [
914,
4
] | [
949,
52
] | python | en | ['en', 'error', 'th'] | False |
TransactionTestCase._post_teardown | (self) |
Perform post-test things:
* Flush the contents of the database to leave a clean slate. If the
class has an 'available_apps' attribute, don't fire post_migrate.
* Force-close the connection so the next test gets a clean cursor.
|
Perform post-test things:
* Flush the contents of the database to leave a clean slate. If the
class has an 'available_apps' attribute, don't fire post_migrate.
* Force-close the connection so the next test gets a clean cursor.
| def _post_teardown(self):
"""
Perform post-test things:
* Flush the contents of the database to leave a clean slate. If the
class has an 'available_apps' attribute, don't fire post_migrate.
* Force-close the connection so the next test gets a clean cursor.
"""
try:
self._fixture_teardown()
super()._post_teardown()
if self._should_reload_connections():
# Some DB cursors include SQL statements as part of cursor
# creation. If you have a test that does a rollback, the effect
# of these statements is lost, which can affect the operation of
# tests (e.g., losing a timezone setting causing objects to be
# created with the wrong time). To make sure this doesn't
# happen, get a clean connection at the start of every test.
for conn in connections.all():
conn.close()
finally:
if self.available_apps is not None:
apps.unset_available_apps()
setting_changed.send(sender=settings._wrapped.__class__,
setting='INSTALLED_APPS',
value=settings.INSTALLED_APPS,
enter=False) | [
"def",
"_post_teardown",
"(",
"self",
")",
":",
"try",
":",
"self",
".",
"_fixture_teardown",
"(",
")",
"super",
"(",
")",
".",
"_post_teardown",
"(",
")",
"if",
"self",
".",
"_should_reload_connections",
"(",
")",
":",
"# Some DB cursors include SQL statements as part of cursor",
"# creation. If you have a test that does a rollback, the effect",
"# of these statements is lost, which can affect the operation of",
"# tests (e.g., losing a timezone setting causing objects to be",
"# created with the wrong time). To make sure this doesn't",
"# happen, get a clean connection at the start of every test.",
"for",
"conn",
"in",
"connections",
".",
"all",
"(",
")",
":",
"conn",
".",
"close",
"(",
")",
"finally",
":",
"if",
"self",
".",
"available_apps",
"is",
"not",
"None",
":",
"apps",
".",
"unset_available_apps",
"(",
")",
"setting_changed",
".",
"send",
"(",
"sender",
"=",
"settings",
".",
"_wrapped",
".",
"__class__",
",",
"setting",
"=",
"'INSTALLED_APPS'",
",",
"value",
"=",
"settings",
".",
"INSTALLED_APPS",
",",
"enter",
"=",
"False",
")"
] | [
997,
4
] | [
1022,
49
] | python | en | ['en', 'error', 'th'] | False |
TestCase._enter_atomics | (cls) | Open atomic blocks for multiple databases. | Open atomic blocks for multiple databases. | def _enter_atomics(cls):
"""Open atomic blocks for multiple databases."""
atomics = {}
for db_name in cls._databases_names():
atomics[db_name] = transaction.atomic(using=db_name)
atomics[db_name].__enter__()
return atomics | [
"def",
"_enter_atomics",
"(",
"cls",
")",
":",
"atomics",
"=",
"{",
"}",
"for",
"db_name",
"in",
"cls",
".",
"_databases_names",
"(",
")",
":",
"atomics",
"[",
"db_name",
"]",
"=",
"transaction",
".",
"atomic",
"(",
"using",
"=",
"db_name",
")",
"atomics",
"[",
"db_name",
"]",
".",
"__enter__",
"(",
")",
"return",
"atomics"
] | [
1160,
4
] | [
1166,
22
] | python | en | ['en', 'no', 'en'] | True |
TestCase._rollback_atomics | (cls, atomics) | Rollback atomic blocks opened by the previous method. | Rollback atomic blocks opened by the previous method. | def _rollback_atomics(cls, atomics):
"""Rollback atomic blocks opened by the previous method."""
for db_name in reversed(cls._databases_names()):
transaction.set_rollback(True, using=db_name)
atomics[db_name].__exit__(None, None, None) | [
"def",
"_rollback_atomics",
"(",
"cls",
",",
"atomics",
")",
":",
"for",
"db_name",
"in",
"reversed",
"(",
"cls",
".",
"_databases_names",
"(",
")",
")",
":",
"transaction",
".",
"set_rollback",
"(",
"True",
",",
"using",
"=",
"db_name",
")",
"atomics",
"[",
"db_name",
"]",
".",
"__exit__",
"(",
"None",
",",
"None",
",",
"None",
")"
] | [
1169,
4
] | [
1173,
55
] | python | en | ['en', 'en', 'en'] | True |
TestCase.setUpTestData | (cls) | Load initial data for the TestCase. | Load initial data for the TestCase. | def setUpTestData(cls):
"""Load initial data for the TestCase."""
pass | [
"def",
"setUpTestData",
"(",
"cls",
")",
":",
"pass"
] | [
1222,
4
] | [
1224,
12
] | python | en | ['en', 'en', 'en'] | True |
TestCase.captureOnCommitCallbacks | (cls, *, using=DEFAULT_DB_ALIAS, execute=False) | Context manager to capture transaction.on_commit() callbacks. | Context manager to capture transaction.on_commit() callbacks. | def captureOnCommitCallbacks(cls, *, using=DEFAULT_DB_ALIAS, execute=False):
"""Context manager to capture transaction.on_commit() callbacks."""
callbacks = []
start_count = len(connections[using].run_on_commit)
try:
yield callbacks
finally:
run_on_commit = connections[using].run_on_commit[start_count:]
callbacks[:] = [func for sids, func in run_on_commit]
if execute:
for callback in callbacks:
callback() | [
"def",
"captureOnCommitCallbacks",
"(",
"cls",
",",
"*",
",",
"using",
"=",
"DEFAULT_DB_ALIAS",
",",
"execute",
"=",
"False",
")",
":",
"callbacks",
"=",
"[",
"]",
"start_count",
"=",
"len",
"(",
"connections",
"[",
"using",
"]",
".",
"run_on_commit",
")",
"try",
":",
"yield",
"callbacks",
"finally",
":",
"run_on_commit",
"=",
"connections",
"[",
"using",
"]",
".",
"run_on_commit",
"[",
"start_count",
":",
"]",
"callbacks",
"[",
":",
"]",
"=",
"[",
"func",
"for",
"sids",
",",
"func",
"in",
"run_on_commit",
"]",
"if",
"execute",
":",
"for",
"callback",
"in",
"callbacks",
":",
"callback",
"(",
")"
] | [
1259,
4
] | [
1270,
30
] | python | en | ['en', 'en', 'en'] | True |
FSFilesHandler._should_handle | (self, path) |
Check if the path should be handled. Ignore the path if:
* the host is provided as part of the base_url
* the request's path isn't under the media path (or equal)
|
Check if the path should be handled. Ignore the path if:
* the host is provided as part of the base_url
* the request's path isn't under the media path (or equal)
| def _should_handle(self, path):
"""
Check if the path should be handled. Ignore the path if:
* the host is provided as part of the base_url
* the request's path isn't under the media path (or equal)
"""
return path.startswith(self.base_url[2]) and not self.base_url[1] | [
"def",
"_should_handle",
"(",
"self",
",",
"path",
")",
":",
"return",
"path",
".",
"startswith",
"(",
"self",
".",
"base_url",
"[",
"2",
"]",
")",
"and",
"not",
"self",
".",
"base_url",
"[",
"1",
"]"
] | [
1386,
4
] | [
1392,
73
] | python | en | ['en', 'error', 'th'] | False |
FSFilesHandler.file_path | (self, url) | Return the relative path to the file on disk for the given URL. | Return the relative path to the file on disk for the given URL. | def file_path(self, url):
"""Return the relative path to the file on disk for the given URL."""
relative_url = url[len(self.base_url[2]):]
return url2pathname(relative_url) | [
"def",
"file_path",
"(",
"self",
",",
"url",
")",
":",
"relative_url",
"=",
"url",
"[",
"len",
"(",
"self",
".",
"base_url",
"[",
"2",
"]",
")",
":",
"]",
"return",
"url2pathname",
"(",
"relative_url",
")"
] | [
1394,
4
] | [
1397,
41
] | python | en | ['en', 'en', 'en'] | True |
LiveServerThread.run | (self) |
Set up the live server and databases, and then loop over handling
HTTP requests.
|
Set up the live server and databases, and then loop over handling
HTTP requests.
| def run(self):
"""
Set up the live server and databases, and then loop over handling
HTTP requests.
"""
if self.connections_override:
# Override this thread's database connections with the ones
# provided by the main thread.
for alias, conn in self.connections_override.items():
connections[alias] = conn
try:
# Create the handler for serving static and media files
handler = self.static_handler(_MediaFilesHandler(WSGIHandler()))
self.httpd = self._create_server()
# If binding to port zero, assign the port allocated by the OS.
if self.port == 0:
self.port = self.httpd.server_address[1]
self.httpd.set_app(handler)
self.is_ready.set()
self.httpd.serve_forever()
except Exception as e:
self.error = e
self.is_ready.set()
finally:
connections.close_all() | [
"def",
"run",
"(",
"self",
")",
":",
"if",
"self",
".",
"connections_override",
":",
"# Override this thread's database connections with the ones",
"# provided by the main thread.",
"for",
"alias",
",",
"conn",
"in",
"self",
".",
"connections_override",
".",
"items",
"(",
")",
":",
"connections",
"[",
"alias",
"]",
"=",
"conn",
"try",
":",
"# Create the handler for serving static and media files",
"handler",
"=",
"self",
".",
"static_handler",
"(",
"_MediaFilesHandler",
"(",
"WSGIHandler",
"(",
")",
")",
")",
"self",
".",
"httpd",
"=",
"self",
".",
"_create_server",
"(",
")",
"# If binding to port zero, assign the port allocated by the OS.",
"if",
"self",
".",
"port",
"==",
"0",
":",
"self",
".",
"port",
"=",
"self",
".",
"httpd",
".",
"server_address",
"[",
"1",
"]",
"self",
".",
"httpd",
".",
"set_app",
"(",
"handler",
")",
"self",
".",
"is_ready",
".",
"set",
"(",
")",
"self",
".",
"httpd",
".",
"serve_forever",
"(",
")",
"except",
"Exception",
"as",
"e",
":",
"self",
".",
"error",
"=",
"e",
"self",
".",
"is_ready",
".",
"set",
"(",
")",
"finally",
":",
"connections",
".",
"close_all",
"(",
")"
] | [
1460,
4
] | [
1484,
35
] | python | en | ['en', 'error', 'th'] | False |
flatpage | (request, url) |
Public interface to the flat page view.
Models: `flatpages.flatpages`
Templates: Uses the template defined by the ``template_name`` field,
or :template:`flatpages/default.html` if template_name is not defined.
Context:
flatpage
`flatpages.flatpages` object
|
Public interface to the flat page view. | def flatpage(request, url):
"""
Public interface to the flat page view.
Models: `flatpages.flatpages`
Templates: Uses the template defined by the ``template_name`` field,
or :template:`flatpages/default.html` if template_name is not defined.
Context:
flatpage
`flatpages.flatpages` object
"""
if not url.startswith('/'):
url = '/' + url
site_id = get_current_site(request).id
try:
f = get_object_or_404(FlatPage, url=url, sites=site_id)
except Http404:
if not url.endswith('/') and settings.APPEND_SLASH:
url += '/'
f = get_object_or_404(FlatPage, url=url, sites=site_id)
return HttpResponsePermanentRedirect('%s/' % request.path)
else:
raise
return render_flatpage(request, f) | [
"def",
"flatpage",
"(",
"request",
",",
"url",
")",
":",
"if",
"not",
"url",
".",
"startswith",
"(",
"'/'",
")",
":",
"url",
"=",
"'/'",
"+",
"url",
"site_id",
"=",
"get_current_site",
"(",
"request",
")",
".",
"id",
"try",
":",
"f",
"=",
"get_object_or_404",
"(",
"FlatPage",
",",
"url",
"=",
"url",
",",
"sites",
"=",
"site_id",
")",
"except",
"Http404",
":",
"if",
"not",
"url",
".",
"endswith",
"(",
"'/'",
")",
"and",
"settings",
".",
"APPEND_SLASH",
":",
"url",
"+=",
"'/'",
"f",
"=",
"get_object_or_404",
"(",
"FlatPage",
",",
"url",
"=",
"url",
",",
"sites",
"=",
"site_id",
")",
"return",
"HttpResponsePermanentRedirect",
"(",
"'%s/'",
"%",
"request",
".",
"path",
")",
"else",
":",
"raise",
"return",
"render_flatpage",
"(",
"request",
",",
"f",
")"
] | [
21,
0
] | [
44,
38
] | python | en | ['en', 'error', 'th'] | False |
render_flatpage | (request, f) |
Internal interface to the flat page view.
|
Internal interface to the flat page view.
| def render_flatpage(request, f):
"""
Internal interface to the flat page view.
"""
# If registration is required for accessing this page, and the user isn't
# logged in, redirect to the login page.
if f.registration_required and not request.user.is_authenticated:
from django.contrib.auth.views import redirect_to_login
return redirect_to_login(request.path)
if f.template_name:
template = loader.select_template((f.template_name, DEFAULT_TEMPLATE))
else:
template = loader.get_template(DEFAULT_TEMPLATE)
# To avoid having to always use the "|safe" filter in flatpage templates,
# mark the title and content as already safe (since they are raw HTML
# content in the first place).
f.title = mark_safe(f.title)
f.content = mark_safe(f.content)
return HttpResponse(template.render({'flatpage': f}, request)) | [
"def",
"render_flatpage",
"(",
"request",
",",
"f",
")",
":",
"# If registration is required for accessing this page, and the user isn't",
"# logged in, redirect to the login page.",
"if",
"f",
".",
"registration_required",
"and",
"not",
"request",
".",
"user",
".",
"is_authenticated",
":",
"from",
"django",
".",
"contrib",
".",
"auth",
".",
"views",
"import",
"redirect_to_login",
"return",
"redirect_to_login",
"(",
"request",
".",
"path",
")",
"if",
"f",
".",
"template_name",
":",
"template",
"=",
"loader",
".",
"select_template",
"(",
"(",
"f",
".",
"template_name",
",",
"DEFAULT_TEMPLATE",
")",
")",
"else",
":",
"template",
"=",
"loader",
".",
"get_template",
"(",
"DEFAULT_TEMPLATE",
")",
"# To avoid having to always use the \"|safe\" filter in flatpage templates,",
"# mark the title and content as already safe (since they are raw HTML",
"# content in the first place).",
"f",
".",
"title",
"=",
"mark_safe",
"(",
"f",
".",
"title",
")",
"f",
".",
"content",
"=",
"mark_safe",
"(",
"f",
".",
"content",
")",
"return",
"HttpResponse",
"(",
"template",
".",
"render",
"(",
"{",
"'flatpage'",
":",
"f",
"}",
",",
"request",
")",
")"
] | [
48,
0
] | [
68,
66
] | python | en | ['en', 'error', 'th'] | False |
GenerateConfig | (context) | Entry function to generate the DM config. | Entry function to generate the DM config. | def GenerateConfig(context):
"""Entry function to generate the DM config."""
props = context.properties
length = props.setdefault(PROPERTY_LENGTH, MIN_LENGTH)
include_symbols = props.setdefault(PROPERTY_INCLUDE_SYMBOLS, False)
if not isinstance(include_symbols, bool):
raise InputError('%s must be a boolean' % PROPERTY_INCLUDE_SYMBOLS)
content = {
'resources': [],
'outputs': [{
'name': 'password',
'value': GeneratePassword(length, include_symbols)
}]
}
return yaml.dump(content) | [
"def",
"GenerateConfig",
"(",
"context",
")",
":",
"props",
"=",
"context",
".",
"properties",
"length",
"=",
"props",
".",
"setdefault",
"(",
"PROPERTY_LENGTH",
",",
"MIN_LENGTH",
")",
"include_symbols",
"=",
"props",
".",
"setdefault",
"(",
"PROPERTY_INCLUDE_SYMBOLS",
",",
"False",
")",
"if",
"not",
"isinstance",
"(",
"include_symbols",
",",
"bool",
")",
":",
"raise",
"InputError",
"(",
"'%s must be a boolean'",
"%",
"PROPERTY_INCLUDE_SYMBOLS",
")",
"content",
"=",
"{",
"'resources'",
":",
"[",
"]",
",",
"'outputs'",
":",
"[",
"{",
"'name'",
":",
"'password'",
",",
"'value'",
":",
"GeneratePassword",
"(",
"length",
",",
"include_symbols",
")",
"}",
"]",
"}",
"return",
"yaml",
".",
"dump",
"(",
"content",
")"
] | [
68,
0
] | [
84,
27
] | python | en | ['en', 'en', 'en'] | True |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.