id int32 0 252k | repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1 value | code stringlengths 51 19.8k | code_tokens list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 |
|---|---|---|---|---|---|---|---|---|---|---|---|
245,600 | pgjones/quart | quart/routing.py | Rule.provides_defaults_for | def provides_defaults_for(self, rule: 'Rule', **values: Any) -> bool:
"""Returns true if this rule provides defaults for the argument and values."""
defaults_match = all(
values[key] == self.defaults[key] for key in self.defaults if key in values # noqa: S101, E501
)
return self != rule and bool(self.defaults) and defaults_match | python | def provides_defaults_for(self, rule: 'Rule', **values: Any) -> bool:
defaults_match = all(
values[key] == self.defaults[key] for key in self.defaults if key in values # noqa: S101, E501
)
return self != rule and bool(self.defaults) and defaults_match | [
"def",
"provides_defaults_for",
"(",
"self",
",",
"rule",
":",
"'Rule'",
",",
"*",
"*",
"values",
":",
"Any",
")",
"->",
"bool",
":",
"defaults_match",
"=",
"all",
"(",
"values",
"[",
"key",
"]",
"==",
"self",
".",
"defaults",
"[",
"key",
"]",
"for",... | Returns true if this rule provides defaults for the argument and values. | [
"Returns",
"true",
"if",
"this",
"rule",
"provides",
"defaults",
"for",
"the",
"argument",
"and",
"values",
"."
] | 7cb2d3bd98e8746025764f2b933abc12041fa175 | https://github.com/pgjones/quart/blob/7cb2d3bd98e8746025764f2b933abc12041fa175/quart/routing.py#L362-L367 |
245,601 | pgjones/quart | quart/routing.py | Rule.build | def build(self, **values: Any) -> str:
"""Build this rule into a path using the values given."""
converted_values = {
key: self._converters[key].to_url(value)
for key, value in values.items()
if key in self._converters
}
result = self._builder.format(**converted_values).split('|', 1)[1]
query_string = urlencode(
{
key: value
for key, value in values.items()
if key not in self._converters and key not in self.defaults
},
doseq=True,
)
if query_string:
result = "{}?{}".format(result, query_string)
return result | python | def build(self, **values: Any) -> str:
converted_values = {
key: self._converters[key].to_url(value)
for key, value in values.items()
if key in self._converters
}
result = self._builder.format(**converted_values).split('|', 1)[1]
query_string = urlencode(
{
key: value
for key, value in values.items()
if key not in self._converters and key not in self.defaults
},
doseq=True,
)
if query_string:
result = "{}?{}".format(result, query_string)
return result | [
"def",
"build",
"(",
"self",
",",
"*",
"*",
"values",
":",
"Any",
")",
"->",
"str",
":",
"converted_values",
"=",
"{",
"key",
":",
"self",
".",
"_converters",
"[",
"key",
"]",
".",
"to_url",
"(",
"value",
")",
"for",
"key",
",",
"value",
"in",
"v... | Build this rule into a path using the values given. | [
"Build",
"this",
"rule",
"into",
"a",
"path",
"using",
"the",
"values",
"given",
"."
] | 7cb2d3bd98e8746025764f2b933abc12041fa175 | https://github.com/pgjones/quart/blob/7cb2d3bd98e8746025764f2b933abc12041fa175/quart/routing.py#L369-L387 |
245,602 | pgjones/quart | quart/routing.py | Rule.buildable | def buildable(self, values: Optional[dict]=None, method: Optional[str]=None) -> bool:
"""Return True if this rule can build with the values and method."""
if method is not None and method not in self.methods:
return False
defaults_match = all(
values[key] == self.defaults[key] for key in self.defaults if key in values # noqa: S101, E501
)
return defaults_match and set(values.keys()) >= set(self._converters.keys()) | python | def buildable(self, values: Optional[dict]=None, method: Optional[str]=None) -> bool:
if method is not None and method not in self.methods:
return False
defaults_match = all(
values[key] == self.defaults[key] for key in self.defaults if key in values # noqa: S101, E501
)
return defaults_match and set(values.keys()) >= set(self._converters.keys()) | [
"def",
"buildable",
"(",
"self",
",",
"values",
":",
"Optional",
"[",
"dict",
"]",
"=",
"None",
",",
"method",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
")",
"->",
"bool",
":",
"if",
"method",
"is",
"not",
"None",
"and",
"method",
"not",
"in",... | Return True if this rule can build with the values and method. | [
"Return",
"True",
"if",
"this",
"rule",
"can",
"build",
"with",
"the",
"values",
"and",
"method",
"."
] | 7cb2d3bd98e8746025764f2b933abc12041fa175 | https://github.com/pgjones/quart/blob/7cb2d3bd98e8746025764f2b933abc12041fa175/quart/routing.py#L389-L396 |
245,603 | pgjones/quart | quart/routing.py | Rule.bind | def bind(self, map: Map) -> None:
"""Bind the Rule to a Map and compile it."""
if self.map is not None:
raise RuntimeError(f"{self!r} is already bound to {self.map!r}")
self.map = map
pattern = ''
builder = ''
full_rule = "{}\\|{}".format(self.host or '', self.rule)
for part in _parse_rule(full_rule):
if isinstance(part, VariablePart):
converter = self.map.converters[part.converter](
*part.arguments[0], **part.arguments[1],
)
pattern += f"(?P<{part.name}>{converter.regex})"
self._converters[part.name] = converter
builder += '{' + part.name + '}'
self._weights.append(WeightedPart(True, converter.weight))
else:
builder += part
pattern += part
self._weights.append(WeightedPart(False, -len(part)))
if not self.is_leaf or not self.strict_slashes:
# Pattern should match with or without a trailing slash
pattern = f"{pattern.rstrip('/')}(?<!/)(?P<__slash__>/?)$"
else:
pattern = f"{pattern}$"
self._pattern = re.compile(pattern)
self._builder = builder | python | def bind(self, map: Map) -> None:
if self.map is not None:
raise RuntimeError(f"{self!r} is already bound to {self.map!r}")
self.map = map
pattern = ''
builder = ''
full_rule = "{}\\|{}".format(self.host or '', self.rule)
for part in _parse_rule(full_rule):
if isinstance(part, VariablePart):
converter = self.map.converters[part.converter](
*part.arguments[0], **part.arguments[1],
)
pattern += f"(?P<{part.name}>{converter.regex})"
self._converters[part.name] = converter
builder += '{' + part.name + '}'
self._weights.append(WeightedPart(True, converter.weight))
else:
builder += part
pattern += part
self._weights.append(WeightedPart(False, -len(part)))
if not self.is_leaf or not self.strict_slashes:
# Pattern should match with or without a trailing slash
pattern = f"{pattern.rstrip('/')}(?<!/)(?P<__slash__>/?)$"
else:
pattern = f"{pattern}$"
self._pattern = re.compile(pattern)
self._builder = builder | [
"def",
"bind",
"(",
"self",
",",
"map",
":",
"Map",
")",
"->",
"None",
":",
"if",
"self",
".",
"map",
"is",
"not",
"None",
":",
"raise",
"RuntimeError",
"(",
"f\"{self!r} is already bound to {self.map!r}\"",
")",
"self",
".",
"map",
"=",
"map",
"pattern",
... | Bind the Rule to a Map and compile it. | [
"Bind",
"the",
"Rule",
"to",
"a",
"Map",
"and",
"compile",
"it",
"."
] | 7cb2d3bd98e8746025764f2b933abc12041fa175 | https://github.com/pgjones/quart/blob/7cb2d3bd98e8746025764f2b933abc12041fa175/quart/routing.py#L398-L427 |
245,604 | pgjones/quart | quart/routing.py | Rule.match_key | def match_key(self) -> Tuple[bool, bool, int, List[WeightedPart]]:
"""A Key to sort the rules by weight for matching.
The key leads to ordering:
- By first order by defaults as they are simple rules without
conversions.
- Then on the complexity of the rule, i.e. does it have any
converted parts. This is as simple rules are quick to match
or reject.
- Then by the number of parts, with more complex (more parts)
first.
- Finally by the weights themselves. Note that weights are also
sub keyed by converter first then weight second.
"""
if self.map is None:
raise RuntimeError(f"{self!r} is not bound to a Map")
complex_rule = any(weight.converter for weight in self._weights)
return (not bool(self.defaults), complex_rule, -len(self._weights), self._weights) | python | def match_key(self) -> Tuple[bool, bool, int, List[WeightedPart]]:
if self.map is None:
raise RuntimeError(f"{self!r} is not bound to a Map")
complex_rule = any(weight.converter for weight in self._weights)
return (not bool(self.defaults), complex_rule, -len(self._weights), self._weights) | [
"def",
"match_key",
"(",
"self",
")",
"->",
"Tuple",
"[",
"bool",
",",
"bool",
",",
"int",
",",
"List",
"[",
"WeightedPart",
"]",
"]",
":",
"if",
"self",
".",
"map",
"is",
"None",
":",
"raise",
"RuntimeError",
"(",
"f\"{self!r} is not bound to a Map\"",
... | A Key to sort the rules by weight for matching.
The key leads to ordering:
- By first order by defaults as they are simple rules without
conversions.
- Then on the complexity of the rule, i.e. does it have any
converted parts. This is as simple rules are quick to match
or reject.
- Then by the number of parts, with more complex (more parts)
first.
- Finally by the weights themselves. Note that weights are also
sub keyed by converter first then weight second. | [
"A",
"Key",
"to",
"sort",
"the",
"rules",
"by",
"weight",
"for",
"matching",
"."
] | 7cb2d3bd98e8746025764f2b933abc12041fa175 | https://github.com/pgjones/quart/blob/7cb2d3bd98e8746025764f2b933abc12041fa175/quart/routing.py#L430-L448 |
245,605 | pgjones/quart | quart/routing.py | Rule.build_key | def build_key(self) -> Tuple[bool, int]:
"""A Key to sort the rules by weight for building.
The key leads to ordering:
- By routes with defaults first, as these must be evaulated
for building before ones without.
- Then the more complex routes (most converted parts).
"""
if self.map is None:
raise RuntimeError(f"{self!r} is not bound to a Map")
return (not bool(self.defaults), -sum(1 for weight in self._weights if weight.converter)) | python | def build_key(self) -> Tuple[bool, int]:
if self.map is None:
raise RuntimeError(f"{self!r} is not bound to a Map")
return (not bool(self.defaults), -sum(1 for weight in self._weights if weight.converter)) | [
"def",
"build_key",
"(",
"self",
")",
"->",
"Tuple",
"[",
"bool",
",",
"int",
"]",
":",
"if",
"self",
".",
"map",
"is",
"None",
":",
"raise",
"RuntimeError",
"(",
"f\"{self!r} is not bound to a Map\"",
")",
"return",
"(",
"not",
"bool",
"(",
"self",
".",... | A Key to sort the rules by weight for building.
The key leads to ordering:
- By routes with defaults first, as these must be evaulated
for building before ones without.
- Then the more complex routes (most converted parts). | [
"A",
"Key",
"to",
"sort",
"the",
"rules",
"by",
"weight",
"for",
"building",
"."
] | 7cb2d3bd98e8746025764f2b933abc12041fa175 | https://github.com/pgjones/quart/blob/7cb2d3bd98e8746025764f2b933abc12041fa175/quart/routing.py#L451-L462 |
245,606 | pgjones/quart | examples/http2_push/http2_push.py | get_tile | def get_tile(tile_number):
"""
Returns a crop of `img` based on a sequence number `tile_number`.
:param int tile_number: Number of the tile between 0 and `max_tiles`^2.
:raises TileOutOfBoundsError: When `tile_number` exceeds `max_tiles`^2
:rtype PIL.Image:
"""
tile_number = int(tile_number)
max_tiles = app.max_tiles
if tile_number > max_tiles * max_tiles:
raise TileOutOfBoundsError('Requested an out of bounds tile')
tile_size = Point(
app.img.size[0] // max_tiles, app.img.size[1] // max_tiles)
tile_coords = Point(
tile_number % max_tiles, tile_number // max_tiles)
crop_box = (
tile_coords.x * tile_size.x,
tile_coords.y * tile_size.y,
tile_coords.x * tile_size.x + tile_size.x,
tile_coords.y * tile_size.y + tile_size.y,
)
return app.img.crop(crop_box) | python | def get_tile(tile_number):
tile_number = int(tile_number)
max_tiles = app.max_tiles
if tile_number > max_tiles * max_tiles:
raise TileOutOfBoundsError('Requested an out of bounds tile')
tile_size = Point(
app.img.size[0] // max_tiles, app.img.size[1] // max_tiles)
tile_coords = Point(
tile_number % max_tiles, tile_number // max_tiles)
crop_box = (
tile_coords.x * tile_size.x,
tile_coords.y * tile_size.y,
tile_coords.x * tile_size.x + tile_size.x,
tile_coords.y * tile_size.y + tile_size.y,
)
return app.img.crop(crop_box) | [
"def",
"get_tile",
"(",
"tile_number",
")",
":",
"tile_number",
"=",
"int",
"(",
"tile_number",
")",
"max_tiles",
"=",
"app",
".",
"max_tiles",
"if",
"tile_number",
">",
"max_tiles",
"*",
"max_tiles",
":",
"raise",
"TileOutOfBoundsError",
"(",
"'Requested an out... | Returns a crop of `img` based on a sequence number `tile_number`.
:param int tile_number: Number of the tile between 0 and `max_tiles`^2.
:raises TileOutOfBoundsError: When `tile_number` exceeds `max_tiles`^2
:rtype PIL.Image: | [
"Returns",
"a",
"crop",
"of",
"img",
"based",
"on",
"a",
"sequence",
"number",
"tile_number",
"."
] | 7cb2d3bd98e8746025764f2b933abc12041fa175 | https://github.com/pgjones/quart/blob/7cb2d3bd98e8746025764f2b933abc12041fa175/examples/http2_push/http2_push.py#L21-L44 |
245,607 | pgjones/quart | examples/http2_push/http2_push.py | tile | async def tile(tile_number):
"""
Handles GET requests for a tile number.
:param int tile_number: Number of the tile between 0 and `max_tiles`^2.
:raises HTTPError: 404 if tile exceeds `max_tiles`^2.
"""
try:
tile = get_tile(tile_number)
except TileOutOfBoundsError:
abort(404)
buf = BytesIO(tile.tobytes())
tile.save(buf, 'JPEG')
content = buf.getvalue()
response = await make_response(content)
response.headers['Content-Type'] = 'image/jpg'
response.headers['Accept-Ranges'] = 'bytes'
response.headers['Content-Length'] = str(len(content))
return response | python | async def tile(tile_number):
try:
tile = get_tile(tile_number)
except TileOutOfBoundsError:
abort(404)
buf = BytesIO(tile.tobytes())
tile.save(buf, 'JPEG')
content = buf.getvalue()
response = await make_response(content)
response.headers['Content-Type'] = 'image/jpg'
response.headers['Accept-Ranges'] = 'bytes'
response.headers['Content-Length'] = str(len(content))
return response | [
"async",
"def",
"tile",
"(",
"tile_number",
")",
":",
"try",
":",
"tile",
"=",
"get_tile",
"(",
"tile_number",
")",
"except",
"TileOutOfBoundsError",
":",
"abort",
"(",
"404",
")",
"buf",
"=",
"BytesIO",
"(",
"tile",
".",
"tobytes",
"(",
")",
")",
"til... | Handles GET requests for a tile number.
:param int tile_number: Number of the tile between 0 and `max_tiles`^2.
:raises HTTPError: 404 if tile exceeds `max_tiles`^2. | [
"Handles",
"GET",
"requests",
"for",
"a",
"tile",
"number",
"."
] | 7cb2d3bd98e8746025764f2b933abc12041fa175 | https://github.com/pgjones/quart/blob/7cb2d3bd98e8746025764f2b933abc12041fa175/examples/http2_push/http2_push.py#L66-L86 |
245,608 | pgjones/quart | quart/wrappers/_base.py | JSONMixin.is_json | def is_json(self) -> bool:
"""Returns True if the content_type is json like."""
content_type = self.mimetype
if content_type == 'application/json' or (
content_type.startswith('application/') and content_type.endswith('+json')
):
return True
else:
return False | python | def is_json(self) -> bool:
content_type = self.mimetype
if content_type == 'application/json' or (
content_type.startswith('application/') and content_type.endswith('+json')
):
return True
else:
return False | [
"def",
"is_json",
"(",
"self",
")",
"->",
"bool",
":",
"content_type",
"=",
"self",
".",
"mimetype",
"if",
"content_type",
"==",
"'application/json'",
"or",
"(",
"content_type",
".",
"startswith",
"(",
"'application/'",
")",
"and",
"content_type",
".",
"endswi... | Returns True if the content_type is json like. | [
"Returns",
"True",
"if",
"the",
"content_type",
"is",
"json",
"like",
"."
] | 7cb2d3bd98e8746025764f2b933abc12041fa175 | https://github.com/pgjones/quart/blob/7cb2d3bd98e8746025764f2b933abc12041fa175/quart/wrappers/_base.py#L40-L48 |
245,609 | pgjones/quart | quart/wrappers/_base.py | JSONMixin.get_json | async def get_json(
self, force: bool=False, silent: bool=False, cache: bool=True,
) -> Any:
"""Parses the body data as JSON and returns it.
Arguments:
force: Force JSON parsing even if the mimetype is not JSON.
silent: Do not trigger error handling if parsing fails, without
this the :meth:`on_json_loading_failed` will be called on
error.
cache: Cache the parsed JSON on this request object.
"""
if cache and self._cached_json is not sentinel:
return self._cached_json
if not (force or self.is_json):
return None
data = await self._load_json_data()
try:
result = loads(data)
except ValueError as error:
if silent:
result = None
else:
self.on_json_loading_failed(error)
if cache:
self._cached_json = result
return result | python | async def get_json(
self, force: bool=False, silent: bool=False, cache: bool=True,
) -> Any:
if cache and self._cached_json is not sentinel:
return self._cached_json
if not (force or self.is_json):
return None
data = await self._load_json_data()
try:
result = loads(data)
except ValueError as error:
if silent:
result = None
else:
self.on_json_loading_failed(error)
if cache:
self._cached_json = result
return result | [
"async",
"def",
"get_json",
"(",
"self",
",",
"force",
":",
"bool",
"=",
"False",
",",
"silent",
":",
"bool",
"=",
"False",
",",
"cache",
":",
"bool",
"=",
"True",
",",
")",
"->",
"Any",
":",
"if",
"cache",
"and",
"self",
".",
"_cached_json",
"is",... | Parses the body data as JSON and returns it.
Arguments:
force: Force JSON parsing even if the mimetype is not JSON.
silent: Do not trigger error handling if parsing fails, without
this the :meth:`on_json_loading_failed` will be called on
error.
cache: Cache the parsed JSON on this request object. | [
"Parses",
"the",
"body",
"data",
"as",
"JSON",
"and",
"returns",
"it",
"."
] | 7cb2d3bd98e8746025764f2b933abc12041fa175 | https://github.com/pgjones/quart/blob/7cb2d3bd98e8746025764f2b933abc12041fa175/quart/wrappers/_base.py#L54-L82 |
245,610 | pgjones/quart | quart/wrappers/_base.py | _BaseRequestResponse.mimetype | def mimetype(self, value: str) -> None:
"""Set the mimetype to the value."""
if (
value.startswith('text/') or value == 'application/xml' or
(value.startswith('application/') and value.endswith('+xml'))
):
mimetype = f"{value}; charset={self.charset}"
else:
mimetype = value
self.headers['Content-Type'] = mimetype | python | def mimetype(self, value: str) -> None:
if (
value.startswith('text/') or value == 'application/xml' or
(value.startswith('application/') and value.endswith('+xml'))
):
mimetype = f"{value}; charset={self.charset}"
else:
mimetype = value
self.headers['Content-Type'] = mimetype | [
"def",
"mimetype",
"(",
"self",
",",
"value",
":",
"str",
")",
"->",
"None",
":",
"if",
"(",
"value",
".",
"startswith",
"(",
"'text/'",
")",
"or",
"value",
"==",
"'application/xml'",
"or",
"(",
"value",
".",
"startswith",
"(",
"'application/'",
")",
"... | Set the mimetype to the value. | [
"Set",
"the",
"mimetype",
"to",
"the",
"value",
"."
] | 7cb2d3bd98e8746025764f2b933abc12041fa175 | https://github.com/pgjones/quart/blob/7cb2d3bd98e8746025764f2b933abc12041fa175/quart/wrappers/_base.py#L117-L126 |
245,611 | pgjones/quart | quart/wrappers/_base.py | BaseRequestWebsocket.blueprint | def blueprint(self) -> Optional[str]:
"""Returns the blueprint the matched endpoint belongs to.
This can be None if the request has not been matched or the
endpoint is not in a blueprint.
"""
if self.endpoint is not None and '.' in self.endpoint:
return self.endpoint.rsplit('.', 1)[0]
else:
return None | python | def blueprint(self) -> Optional[str]:
if self.endpoint is not None and '.' in self.endpoint:
return self.endpoint.rsplit('.', 1)[0]
else:
return None | [
"def",
"blueprint",
"(",
"self",
")",
"->",
"Optional",
"[",
"str",
"]",
":",
"if",
"self",
".",
"endpoint",
"is",
"not",
"None",
"and",
"'.'",
"in",
"self",
".",
"endpoint",
":",
"return",
"self",
".",
"endpoint",
".",
"rsplit",
"(",
"'.'",
",",
"... | Returns the blueprint the matched endpoint belongs to.
This can be None if the request has not been matched or the
endpoint is not in a blueprint. | [
"Returns",
"the",
"blueprint",
"the",
"matched",
"endpoint",
"belongs",
"to",
"."
] | 7cb2d3bd98e8746025764f2b933abc12041fa175 | https://github.com/pgjones/quart/blob/7cb2d3bd98e8746025764f2b933abc12041fa175/quart/wrappers/_base.py#L195-L204 |
245,612 | pgjones/quart | quart/wrappers/_base.py | BaseRequestWebsocket.base_url | def base_url(self) -> str:
"""Returns the base url without query string or fragments."""
return urlunparse(ParseResult(self.scheme, self.host, self.path, '', '', '')) | python | def base_url(self) -> str:
return urlunparse(ParseResult(self.scheme, self.host, self.path, '', '', '')) | [
"def",
"base_url",
"(",
"self",
")",
"->",
"str",
":",
"return",
"urlunparse",
"(",
"ParseResult",
"(",
"self",
".",
"scheme",
",",
"self",
".",
"host",
",",
"self",
".",
"path",
",",
"''",
",",
"''",
",",
"''",
")",
")"
] | Returns the base url without query string or fragments. | [
"Returns",
"the",
"base",
"url",
"without",
"query",
"string",
"or",
"fragments",
"."
] | 7cb2d3bd98e8746025764f2b933abc12041fa175 | https://github.com/pgjones/quart/blob/7cb2d3bd98e8746025764f2b933abc12041fa175/quart/wrappers/_base.py#L266-L268 |
245,613 | pgjones/quart | quart/wrappers/_base.py | BaseRequestWebsocket.url | def url(self) -> str:
"""Returns the full url requested."""
return urlunparse(
ParseResult(
self.scheme, self.host, self.path, '', self.query_string.decode('ascii'), '',
),
) | python | def url(self) -> str:
return urlunparse(
ParseResult(
self.scheme, self.host, self.path, '', self.query_string.decode('ascii'), '',
),
) | [
"def",
"url",
"(",
"self",
")",
"->",
"str",
":",
"return",
"urlunparse",
"(",
"ParseResult",
"(",
"self",
".",
"scheme",
",",
"self",
".",
"host",
",",
"self",
".",
"path",
",",
"''",
",",
"self",
".",
"query_string",
".",
"decode",
"(",
"'ascii'",
... | Returns the full url requested. | [
"Returns",
"the",
"full",
"url",
"requested",
"."
] | 7cb2d3bd98e8746025764f2b933abc12041fa175 | https://github.com/pgjones/quart/blob/7cb2d3bd98e8746025764f2b933abc12041fa175/quart/wrappers/_base.py#L286-L292 |
245,614 | pgjones/quart | quart/wrappers/_base.py | BaseRequestWebsocket.cookies | def cookies(self) -> Dict[str, str]:
"""The parsed cookies attached to this request."""
cookies = SimpleCookie()
cookies.load(self.headers.get('Cookie', ''))
return {key: cookie.value for key, cookie in cookies.items()} | python | def cookies(self) -> Dict[str, str]:
cookies = SimpleCookie()
cookies.load(self.headers.get('Cookie', ''))
return {key: cookie.value for key, cookie in cookies.items()} | [
"def",
"cookies",
"(",
"self",
")",
"->",
"Dict",
"[",
"str",
",",
"str",
"]",
":",
"cookies",
"=",
"SimpleCookie",
"(",
")",
"cookies",
".",
"load",
"(",
"self",
".",
"headers",
".",
"get",
"(",
"'Cookie'",
",",
"''",
")",
")",
"return",
"{",
"k... | The parsed cookies attached to this request. | [
"The",
"parsed",
"cookies",
"attached",
"to",
"this",
"request",
"."
] | 7cb2d3bd98e8746025764f2b933abc12041fa175 | https://github.com/pgjones/quart/blob/7cb2d3bd98e8746025764f2b933abc12041fa175/quart/wrappers/_base.py#L307-L311 |
245,615 | pgjones/quart | quart/config.py | Config.from_envvar | def from_envvar(self, variable_name: str, silent: bool=False) -> None:
"""Load the configuration from a location specified in the environment.
This will load a cfg file using :meth:`from_pyfile` from the
location specified in the environment, for example the two blocks
below are equivalent.
.. code-block:: python
app.config.from_envvar('CONFIG')
.. code-block:: python
filename = os.environ['CONFIG']
app.config.from_pyfile(filename)
"""
value = os.environ.get(variable_name)
if value is None and not silent:
raise RuntimeError(
f"Environment variable {variable_name} is not present, cannot load config",
)
return self.from_pyfile(value) | python | def from_envvar(self, variable_name: str, silent: bool=False) -> None:
value = os.environ.get(variable_name)
if value is None and not silent:
raise RuntimeError(
f"Environment variable {variable_name} is not present, cannot load config",
)
return self.from_pyfile(value) | [
"def",
"from_envvar",
"(",
"self",
",",
"variable_name",
":",
"str",
",",
"silent",
":",
"bool",
"=",
"False",
")",
"->",
"None",
":",
"value",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"variable_name",
")",
"if",
"value",
"is",
"None",
"and",
"not... | Load the configuration from a location specified in the environment.
This will load a cfg file using :meth:`from_pyfile` from the
location specified in the environment, for example the two blocks
below are equivalent.
.. code-block:: python
app.config.from_envvar('CONFIG')
.. code-block:: python
filename = os.environ['CONFIG']
app.config.from_pyfile(filename) | [
"Load",
"the",
"configuration",
"from",
"a",
"location",
"specified",
"in",
"the",
"environment",
"."
] | 7cb2d3bd98e8746025764f2b933abc12041fa175 | https://github.com/pgjones/quart/blob/7cb2d3bd98e8746025764f2b933abc12041fa175/quart/config.py#L88-L109 |
245,616 | pgjones/quart | quart/config.py | Config.from_pyfile | def from_pyfile(self, filename: str, silent: bool=False) -> None:
"""Load the configuration from a Python cfg or py file.
See Python's ConfigParser docs for details on the cfg format.
It is a common practice to load the defaults from the source
using the :meth:`from_object` and then override with a cfg or
py file, for example
.. code-block:: python
app.config.from_object('config_module')
app.config.from_pyfile('production.cfg')
Arguments:
filename: The filename which when appended to
:attr:`root_path` gives the path to the file
"""
file_path = self.root_path / filename
try:
spec = importlib.util.spec_from_file_location("module.name", file_path) # type: ignore
if spec is None: # Likely passed a cfg file
parser = ConfigParser()
parser.optionxform = str # type: ignore # Prevents lowercasing of keys
with open(file_path) as file_:
config_str = '[section]\n' + file_.read()
parser.read_string(config_str)
self.from_mapping(parser['section'])
else:
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module) # type: ignore
self.from_object(module)
except (FileNotFoundError, IsADirectoryError):
if not silent:
raise | python | def from_pyfile(self, filename: str, silent: bool=False) -> None:
file_path = self.root_path / filename
try:
spec = importlib.util.spec_from_file_location("module.name", file_path) # type: ignore
if spec is None: # Likely passed a cfg file
parser = ConfigParser()
parser.optionxform = str # type: ignore # Prevents lowercasing of keys
with open(file_path) as file_:
config_str = '[section]\n' + file_.read()
parser.read_string(config_str)
self.from_mapping(parser['section'])
else:
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module) # type: ignore
self.from_object(module)
except (FileNotFoundError, IsADirectoryError):
if not silent:
raise | [
"def",
"from_pyfile",
"(",
"self",
",",
"filename",
":",
"str",
",",
"silent",
":",
"bool",
"=",
"False",
")",
"->",
"None",
":",
"file_path",
"=",
"self",
".",
"root_path",
"/",
"filename",
"try",
":",
"spec",
"=",
"importlib",
".",
"util",
".",
"sp... | Load the configuration from a Python cfg or py file.
See Python's ConfigParser docs for details on the cfg format.
It is a common practice to load the defaults from the source
using the :meth:`from_object` and then override with a cfg or
py file, for example
.. code-block:: python
app.config.from_object('config_module')
app.config.from_pyfile('production.cfg')
Arguments:
filename: The filename which when appended to
:attr:`root_path` gives the path to the file | [
"Load",
"the",
"configuration",
"from",
"a",
"Python",
"cfg",
"or",
"py",
"file",
"."
] | 7cb2d3bd98e8746025764f2b933abc12041fa175 | https://github.com/pgjones/quart/blob/7cb2d3bd98e8746025764f2b933abc12041fa175/quart/config.py#L111-L145 |
245,617 | pgjones/quart | quart/config.py | Config.from_object | def from_object(self, instance: Union[object, str]) -> None:
"""Load the configuration from a Python object.
This can be used to reference modules or objects within
modules for example,
.. code-block:: python
app.config.from_object('module')
app.config.from_object('module.instance')
from module import instance
app.config.from_object(instance)
are valid.
Arguments:
instance: Either a str referencing a python object or the
object itself.
"""
if isinstance(instance, str):
try:
path, config = instance.rsplit('.', 1)
except ValueError:
path = instance
instance = importlib.import_module(path)
else:
module = importlib.import_module(path)
instance = getattr(module, config)
for key in dir(instance):
if key.isupper():
self[key] = getattr(instance, key) | python | def from_object(self, instance: Union[object, str]) -> None:
if isinstance(instance, str):
try:
path, config = instance.rsplit('.', 1)
except ValueError:
path = instance
instance = importlib.import_module(path)
else:
module = importlib.import_module(path)
instance = getattr(module, config)
for key in dir(instance):
if key.isupper():
self[key] = getattr(instance, key) | [
"def",
"from_object",
"(",
"self",
",",
"instance",
":",
"Union",
"[",
"object",
",",
"str",
"]",
")",
"->",
"None",
":",
"if",
"isinstance",
"(",
"instance",
",",
"str",
")",
":",
"try",
":",
"path",
",",
"config",
"=",
"instance",
".",
"rsplit",
... | Load the configuration from a Python object.
This can be used to reference modules or objects within
modules for example,
.. code-block:: python
app.config.from_object('module')
app.config.from_object('module.instance')
from module import instance
app.config.from_object(instance)
are valid.
Arguments:
instance: Either a str referencing a python object or the
object itself. | [
"Load",
"the",
"configuration",
"from",
"a",
"Python",
"object",
"."
] | 7cb2d3bd98e8746025764f2b933abc12041fa175 | https://github.com/pgjones/quart/blob/7cb2d3bd98e8746025764f2b933abc12041fa175/quart/config.py#L147-L179 |
245,618 | pgjones/quart | quart/config.py | Config.from_json | def from_json(self, filename: str, silent: bool=False) -> None:
"""Load the configuration values from a JSON formatted file.
This allows configuration to be loaded as so
.. code-block:: python
app.config.from_json('config.json')
Arguments:
filename: The filename which when appended to
:attr:`root_path` gives the path to the file.
silent: If True any errors will fail silently.
"""
file_path = self.root_path / filename
try:
with open(file_path) as file_:
data = json.loads(file_.read())
except (FileNotFoundError, IsADirectoryError):
if not silent:
raise
else:
self.from_mapping(data) | python | def from_json(self, filename: str, silent: bool=False) -> None:
file_path = self.root_path / filename
try:
with open(file_path) as file_:
data = json.loads(file_.read())
except (FileNotFoundError, IsADirectoryError):
if not silent:
raise
else:
self.from_mapping(data) | [
"def",
"from_json",
"(",
"self",
",",
"filename",
":",
"str",
",",
"silent",
":",
"bool",
"=",
"False",
")",
"->",
"None",
":",
"file_path",
"=",
"self",
".",
"root_path",
"/",
"filename",
"try",
":",
"with",
"open",
"(",
"file_path",
")",
"as",
"fil... | Load the configuration values from a JSON formatted file.
This allows configuration to be loaded as so
.. code-block:: python
app.config.from_json('config.json')
Arguments:
filename: The filename which when appended to
:attr:`root_path` gives the path to the file.
silent: If True any errors will fail silently. | [
"Load",
"the",
"configuration",
"values",
"from",
"a",
"JSON",
"formatted",
"file",
"."
] | 7cb2d3bd98e8746025764f2b933abc12041fa175 | https://github.com/pgjones/quart/blob/7cb2d3bd98e8746025764f2b933abc12041fa175/quart/config.py#L181-L203 |
245,619 | pgjones/quart | quart/config.py | Config.from_mapping | def from_mapping(self, mapping: Optional[Mapping[str, Any]]=None, **kwargs: Any) -> None:
"""Load the configuration values from a mapping.
This allows either a mapping to be directly passed or as
keyword arguments, for example,
.. code-block:: python
config = {'FOO': 'bar'}
app.config.from_mapping(config)
app.config.form_mapping(FOO='bar')
Arguments:
mapping: Optionally a mapping object.
kwargs: Optionally a collection of keyword arguments to
form a mapping.
"""
mappings: Dict[str, Any] = {}
if mapping is not None:
mappings.update(mapping)
mappings.update(kwargs)
for key, value in mappings.items():
if key.isupper():
self[key] = value | python | def from_mapping(self, mapping: Optional[Mapping[str, Any]]=None, **kwargs: Any) -> None:
mappings: Dict[str, Any] = {}
if mapping is not None:
mappings.update(mapping)
mappings.update(kwargs)
for key, value in mappings.items():
if key.isupper():
self[key] = value | [
"def",
"from_mapping",
"(",
"self",
",",
"mapping",
":",
"Optional",
"[",
"Mapping",
"[",
"str",
",",
"Any",
"]",
"]",
"=",
"None",
",",
"*",
"*",
"kwargs",
":",
"Any",
")",
"->",
"None",
":",
"mappings",
":",
"Dict",
"[",
"str",
",",
"Any",
"]",... | Load the configuration values from a mapping.
This allows either a mapping to be directly passed or as
keyword arguments, for example,
.. code-block:: python
config = {'FOO': 'bar'}
app.config.from_mapping(config)
app.config.form_mapping(FOO='bar')
Arguments:
mapping: Optionally a mapping object.
kwargs: Optionally a collection of keyword arguments to
form a mapping. | [
"Load",
"the",
"configuration",
"values",
"from",
"a",
"mapping",
"."
] | 7cb2d3bd98e8746025764f2b933abc12041fa175 | https://github.com/pgjones/quart/blob/7cb2d3bd98e8746025764f2b933abc12041fa175/quart/config.py#L205-L228 |
245,620 | pgjones/quart | quart/config.py | Config.get_namespace | def get_namespace(
self,
namespace: str,
lowercase: bool=True,
trim_namespace: bool=True,
) -> Dict[str, Any]:
"""Return a dictionary of keys within a namespace.
A namespace is considered to be a key prefix, for example the
keys ``FOO_A, FOO_BAR, FOO_B`` are all within the ``FOO``
namespace. This method would return a dictionary with these
keys and values present.
.. code-block:: python
config = {'FOO_A': 'a', 'FOO_BAR': 'bar', 'BAR': False}
app.config.from_mapping(config)
assert app.config.get_namespace('FOO_') == {'a': 'a', 'bar': 'bar'}
Arguments:
namespace: The namespace itself (should be uppercase).
lowercase: Lowercase the keys in the returned dictionary.
trim_namespace: Remove the namespace from the returned
keys.
"""
config = {}
for key, value in self.items():
if key.startswith(namespace):
if trim_namespace:
new_key = key[len(namespace):]
else:
new_key = key
if lowercase:
new_key = new_key.lower()
config[new_key] = value
return config | python | def get_namespace(
self,
namespace: str,
lowercase: bool=True,
trim_namespace: bool=True,
) -> Dict[str, Any]:
config = {}
for key, value in self.items():
if key.startswith(namespace):
if trim_namespace:
new_key = key[len(namespace):]
else:
new_key = key
if lowercase:
new_key = new_key.lower()
config[new_key] = value
return config | [
"def",
"get_namespace",
"(",
"self",
",",
"namespace",
":",
"str",
",",
"lowercase",
":",
"bool",
"=",
"True",
",",
"trim_namespace",
":",
"bool",
"=",
"True",
",",
")",
"->",
"Dict",
"[",
"str",
",",
"Any",
"]",
":",
"config",
"=",
"{",
"}",
"for"... | Return a dictionary of keys within a namespace.
A namespace is considered to be a key prefix, for example the
keys ``FOO_A, FOO_BAR, FOO_B`` are all within the ``FOO``
namespace. This method would return a dictionary with these
keys and values present.
.. code-block:: python
config = {'FOO_A': 'a', 'FOO_BAR': 'bar', 'BAR': False}
app.config.from_mapping(config)
assert app.config.get_namespace('FOO_') == {'a': 'a', 'bar': 'bar'}
Arguments:
namespace: The namespace itself (should be uppercase).
lowercase: Lowercase the keys in the returned dictionary.
trim_namespace: Remove the namespace from the returned
keys. | [
"Return",
"a",
"dictionary",
"of",
"keys",
"within",
"a",
"namespace",
"."
] | 7cb2d3bd98e8746025764f2b933abc12041fa175 | https://github.com/pgjones/quart/blob/7cb2d3bd98e8746025764f2b933abc12041fa175/quart/config.py#L230-L265 |
245,621 | pgjones/quart | quart/helpers.py | make_response | async def make_response(*args: Any) -> Response:
"""Create a response, a simple wrapper function.
This is most useful when you want to alter a Response before
returning it, for example
.. code-block:: python
response = make_response(render_template('index.html'))
response.headers['X-Header'] = 'Something'
"""
if not args:
return current_app.response_class()
if len(args) == 1:
args = args[0]
return await current_app.make_response(args) | python | async def make_response(*args: Any) -> Response:
if not args:
return current_app.response_class()
if len(args) == 1:
args = args[0]
return await current_app.make_response(args) | [
"async",
"def",
"make_response",
"(",
"*",
"args",
":",
"Any",
")",
"->",
"Response",
":",
"if",
"not",
"args",
":",
"return",
"current_app",
".",
"response_class",
"(",
")",
"if",
"len",
"(",
"args",
")",
"==",
"1",
":",
"args",
"=",
"args",
"[",
... | Create a response, a simple wrapper function.
This is most useful when you want to alter a Response before
returning it, for example
.. code-block:: python
response = make_response(render_template('index.html'))
response.headers['X-Header'] = 'Something' | [
"Create",
"a",
"response",
"a",
"simple",
"wrapper",
"function",
"."
] | 7cb2d3bd98e8746025764f2b933abc12041fa175 | https://github.com/pgjones/quart/blob/7cb2d3bd98e8746025764f2b933abc12041fa175/quart/helpers.py#L38-L55 |
245,622 | pgjones/quart | quart/helpers.py | get_flashed_messages | def get_flashed_messages(
with_categories: bool=False,
category_filter: List[str]=[],
) -> Union[List[str], List[Tuple[str, str]]]:
"""Retrieve the flashed messages stored in the session.
This is mostly useful in templates where it is exposed as a global
function, for example
.. code-block:: html+jinja
<ul>
{% for message in get_flashed_messages() %}
<li>{{ message }}</li>
{% endfor %}
</ul>
Note that caution is required for usage of ``category_filter`` as
all messages will be popped, but only those matching the filter
returned. See :func:`~quart.helpers.flash` for message creation.
"""
flashes = session.pop('_flashes') if '_flashes' in session else []
if category_filter:
flashes = [flash for flash in flashes if flash[0] in category_filter]
if not with_categories:
flashes = [flash[1] for flash in flashes]
return flashes | python | def get_flashed_messages(
with_categories: bool=False,
category_filter: List[str]=[],
) -> Union[List[str], List[Tuple[str, str]]]:
flashes = session.pop('_flashes') if '_flashes' in session else []
if category_filter:
flashes = [flash for flash in flashes if flash[0] in category_filter]
if not with_categories:
flashes = [flash[1] for flash in flashes]
return flashes | [
"def",
"get_flashed_messages",
"(",
"with_categories",
":",
"bool",
"=",
"False",
",",
"category_filter",
":",
"List",
"[",
"str",
"]",
"=",
"[",
"]",
",",
")",
"->",
"Union",
"[",
"List",
"[",
"str",
"]",
",",
"List",
"[",
"Tuple",
"[",
"str",
",",
... | Retrieve the flashed messages stored in the session.
This is mostly useful in templates where it is exposed as a global
function, for example
.. code-block:: html+jinja
<ul>
{% for message in get_flashed_messages() %}
<li>{{ message }}</li>
{% endfor %}
</ul>
Note that caution is required for usage of ``category_filter`` as
all messages will be popped, but only those matching the filter
returned. See :func:`~quart.helpers.flash` for message creation. | [
"Retrieve",
"the",
"flashed",
"messages",
"stored",
"in",
"the",
"session",
"."
] | 7cb2d3bd98e8746025764f2b933abc12041fa175 | https://github.com/pgjones/quart/blob/7cb2d3bd98e8746025764f2b933abc12041fa175/quart/helpers.py#L95-L121 |
245,623 | pgjones/quart | quart/helpers.py | url_for | def url_for(
endpoint: str,
*,
_anchor: Optional[str]=None,
_external: Optional[bool]=None,
_method: Optional[str]=None,
_scheme: Optional[str]=None,
**values: Any,
) -> str:
"""Return the url for a specific endpoint.
This is most useful in templates and redirects to create a URL
that can be used in the browser.
Arguments:
endpoint: The endpoint to build a url for, if prefixed with
``.`` it targets endpoint's in the current blueprint.
_anchor: Additional anchor text to append (i.e. #text).
_external: Return an absolute url for external (to app) usage.
_method: The method to consider alongside the endpoint.
_scheme: A specific scheme to use.
values: The values to build into the URL, as specified in
the endpoint rule.
"""
app_context = _app_ctx_stack.top
request_context = _request_ctx_stack.top
if request_context is not None:
url_adapter = request_context.url_adapter
if endpoint.startswith('.'):
if request.blueprint is not None:
endpoint = request.blueprint + endpoint
else:
endpoint = endpoint[1:]
if _external is None:
_external = False
elif app_context is not None:
url_adapter = app_context.url_adapter
if _external is None:
_external = True
else:
raise RuntimeError('Cannot create a url outside of an application context')
if url_adapter is None:
raise RuntimeError(
'Unable to create a url adapter, try setting the the SERVER_NAME config variable.'
)
if _scheme is not None and not _external:
raise ValueError('External must be True for scheme usage')
app_context.app.inject_url_defaults(endpoint, values)
try:
url = url_adapter.build(
endpoint, values, method=_method, scheme=_scheme, external=_external,
)
except BuildError as error:
return app_context.app.handle_url_build_error(error, endpoint, values)
if _anchor is not None:
quoted_anchor = quote(_anchor)
url = f"{url}#{quoted_anchor}"
return url | python | def url_for(
endpoint: str,
*,
_anchor: Optional[str]=None,
_external: Optional[bool]=None,
_method: Optional[str]=None,
_scheme: Optional[str]=None,
**values: Any,
) -> str:
app_context = _app_ctx_stack.top
request_context = _request_ctx_stack.top
if request_context is not None:
url_adapter = request_context.url_adapter
if endpoint.startswith('.'):
if request.blueprint is not None:
endpoint = request.blueprint + endpoint
else:
endpoint = endpoint[1:]
if _external is None:
_external = False
elif app_context is not None:
url_adapter = app_context.url_adapter
if _external is None:
_external = True
else:
raise RuntimeError('Cannot create a url outside of an application context')
if url_adapter is None:
raise RuntimeError(
'Unable to create a url adapter, try setting the the SERVER_NAME config variable.'
)
if _scheme is not None and not _external:
raise ValueError('External must be True for scheme usage')
app_context.app.inject_url_defaults(endpoint, values)
try:
url = url_adapter.build(
endpoint, values, method=_method, scheme=_scheme, external=_external,
)
except BuildError as error:
return app_context.app.handle_url_build_error(error, endpoint, values)
if _anchor is not None:
quoted_anchor = quote(_anchor)
url = f"{url}#{quoted_anchor}"
return url | [
"def",
"url_for",
"(",
"endpoint",
":",
"str",
",",
"*",
",",
"_anchor",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
",",
"_external",
":",
"Optional",
"[",
"bool",
"]",
"=",
"None",
",",
"_method",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",... | Return the url for a specific endpoint.
This is most useful in templates and redirects to create a URL
that can be used in the browser.
Arguments:
endpoint: The endpoint to build a url for, if prefixed with
``.`` it targets endpoint's in the current blueprint.
_anchor: Additional anchor text to append (i.e. #text).
_external: Return an absolute url for external (to app) usage.
_method: The method to consider alongside the endpoint.
_scheme: A specific scheme to use.
values: The values to build into the URL, as specified in
the endpoint rule. | [
"Return",
"the",
"url",
"for",
"a",
"specific",
"endpoint",
"."
] | 7cb2d3bd98e8746025764f2b933abc12041fa175 | https://github.com/pgjones/quart/blob/7cb2d3bd98e8746025764f2b933abc12041fa175/quart/helpers.py#L137-L198 |
245,624 | pgjones/quart | quart/helpers.py | stream_with_context | def stream_with_context(func: Callable) -> Callable:
"""Share the current request context with a generator.
This allows the request context to be accessed within a streaming
generator, for example,
.. code-block:: python
@app.route('/')
def index() -> AsyncGenerator[bytes, None]:
@stream_with_context
async def generator() -> bytes:
yield request.method.encode()
yield b' '
yield request.path.encode()
return generator()
"""
request_context = _request_ctx_stack.top.copy()
@wraps(func)
async def generator(*args: Any, **kwargs: Any) -> Any:
async with request_context:
async for data in func(*args, **kwargs):
yield data
return generator | python | def stream_with_context(func: Callable) -> Callable:
request_context = _request_ctx_stack.top.copy()
@wraps(func)
async def generator(*args: Any, **kwargs: Any) -> Any:
async with request_context:
async for data in func(*args, **kwargs):
yield data
return generator | [
"def",
"stream_with_context",
"(",
"func",
":",
"Callable",
")",
"->",
"Callable",
":",
"request_context",
"=",
"_request_ctx_stack",
".",
"top",
".",
"copy",
"(",
")",
"@",
"wraps",
"(",
"func",
")",
"async",
"def",
"generator",
"(",
"*",
"args",
":",
"... | Share the current request context with a generator.
This allows the request context to be accessed within a streaming
generator, for example,
.. code-block:: python
@app.route('/')
def index() -> AsyncGenerator[bytes, None]:
@stream_with_context
async def generator() -> bytes:
yield request.method.encode()
yield b' '
yield request.path.encode()
return generator() | [
"Share",
"the",
"current",
"request",
"context",
"with",
"a",
"generator",
"."
] | 7cb2d3bd98e8746025764f2b933abc12041fa175 | https://github.com/pgjones/quart/blob/7cb2d3bd98e8746025764f2b933abc12041fa175/quart/helpers.py#L201-L227 |
245,625 | pgjones/quart | quart/static.py | safe_join | def safe_join(directory: FilePath, *paths: FilePath) -> Path:
"""Safely join the paths to the known directory to return a full path.
Raises:
NotFound: if the full path does not share a commonprefix with
the directory.
"""
try:
safe_path = file_path_to_path(directory).resolve(strict=True)
full_path = file_path_to_path(directory, *paths).resolve(strict=True)
except FileNotFoundError:
raise NotFound()
try:
full_path.relative_to(safe_path)
except ValueError:
raise NotFound()
return full_path | python | def safe_join(directory: FilePath, *paths: FilePath) -> Path:
try:
safe_path = file_path_to_path(directory).resolve(strict=True)
full_path = file_path_to_path(directory, *paths).resolve(strict=True)
except FileNotFoundError:
raise NotFound()
try:
full_path.relative_to(safe_path)
except ValueError:
raise NotFound()
return full_path | [
"def",
"safe_join",
"(",
"directory",
":",
"FilePath",
",",
"*",
"paths",
":",
"FilePath",
")",
"->",
"Path",
":",
"try",
":",
"safe_path",
"=",
"file_path_to_path",
"(",
"directory",
")",
".",
"resolve",
"(",
"strict",
"=",
"True",
")",
"full_path",
"="... | Safely join the paths to the known directory to return a full path.
Raises:
NotFound: if the full path does not share a commonprefix with
the directory. | [
"Safely",
"join",
"the",
"paths",
"to",
"the",
"known",
"directory",
"to",
"return",
"a",
"full",
"path",
"."
] | 7cb2d3bd98e8746025764f2b933abc12041fa175 | https://github.com/pgjones/quart/blob/7cb2d3bd98e8746025764f2b933abc12041fa175/quart/static.py#L117-L133 |
245,626 | pgjones/quart | quart/static.py | send_from_directory | async def send_from_directory(
directory: FilePath,
file_name: str,
*,
mimetype: Optional[str]=None,
as_attachment: bool=False,
attachment_filename: Optional[str]=None,
add_etags: bool=True,
cache_timeout: Optional[int]=None,
conditional: bool=True,
last_modified: Optional[datetime]=None,
) -> Response:
"""Send a file from a given directory.
Arguments:
directory: Directory that when combined with file_name gives
the file path.
file_name: File name that when combined with directory gives
the file path.
See :func:`send_file` for the other arguments.
"""
file_path = safe_join(directory, file_name)
if not file_path.is_file():
raise NotFound()
return await send_file(
file_path,
mimetype=mimetype,
as_attachment=as_attachment,
attachment_filename=attachment_filename,
add_etags=add_etags,
cache_timeout=cache_timeout,
conditional=conditional,
last_modified=last_modified,
) | python | async def send_from_directory(
directory: FilePath,
file_name: str,
*,
mimetype: Optional[str]=None,
as_attachment: bool=False,
attachment_filename: Optional[str]=None,
add_etags: bool=True,
cache_timeout: Optional[int]=None,
conditional: bool=True,
last_modified: Optional[datetime]=None,
) -> Response:
file_path = safe_join(directory, file_name)
if not file_path.is_file():
raise NotFound()
return await send_file(
file_path,
mimetype=mimetype,
as_attachment=as_attachment,
attachment_filename=attachment_filename,
add_etags=add_etags,
cache_timeout=cache_timeout,
conditional=conditional,
last_modified=last_modified,
) | [
"async",
"def",
"send_from_directory",
"(",
"directory",
":",
"FilePath",
",",
"file_name",
":",
"str",
",",
"*",
",",
"mimetype",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
",",
"as_attachment",
":",
"bool",
"=",
"False",
",",
"attachment_filename",
"... | Send a file from a given directory.
Arguments:
directory: Directory that when combined with file_name gives
the file path.
file_name: File name that when combined with directory gives
the file path.
See :func:`send_file` for the other arguments. | [
"Send",
"a",
"file",
"from",
"a",
"given",
"directory",
"."
] | 7cb2d3bd98e8746025764f2b933abc12041fa175 | https://github.com/pgjones/quart/blob/7cb2d3bd98e8746025764f2b933abc12041fa175/quart/static.py#L136-L169 |
245,627 | pgjones/quart | quart/static.py | send_file | async def send_file(
filename: FilePath,
mimetype: Optional[str]=None,
as_attachment: bool=False,
attachment_filename: Optional[str]=None,
add_etags: bool=True,
cache_timeout: Optional[int]=None,
conditional: bool=False,
last_modified: Optional[datetime]=None,
) -> Response:
"""Return a Reponse to send the filename given.
Arguments:
filename: The filename (path) to send, remember to use
:func:`safe_join`.
mimetype: Mimetype to use, by default it will be guessed or
revert to the DEFAULT_MIMETYPE.
as_attachment: If true use the attachment filename in a
Content-Disposition attachment header.
attachment_filename: Name for the filename, if it differs
add_etags: Set etags based on the filename, size and
modification time.
last_modified: Used to override the last modified value.
cache_timeout: Time in seconds for the response to be cached.
"""
file_path = file_path_to_path(filename)
if attachment_filename is None:
attachment_filename = file_path.name
if mimetype is None:
mimetype = mimetypes.guess_type(attachment_filename)[0] or DEFAULT_MIMETYPE
file_body = current_app.response_class.file_body_class(file_path)
response = current_app.response_class(file_body, mimetype=mimetype)
if as_attachment:
response.headers.add('Content-Disposition', 'attachment', filename=attachment_filename)
if last_modified is not None:
response.last_modified = last_modified
else:
response.last_modified = datetime.fromtimestamp(file_path.stat().st_mtime)
response.cache_control.public = True
cache_timeout = cache_timeout or current_app.get_send_file_max_age(file_path)
if cache_timeout is not None:
response.cache_control.max_age = cache_timeout
response.expires = datetime.utcnow() + timedelta(seconds=cache_timeout)
if add_etags:
response.set_etag(
'{}-{}-{}'.format(
file_path.stat().st_mtime, file_path.stat().st_size,
adler32(bytes(file_path)),
),
)
if conditional:
await response.make_conditional(request.range)
return response | python | async def send_file(
filename: FilePath,
mimetype: Optional[str]=None,
as_attachment: bool=False,
attachment_filename: Optional[str]=None,
add_etags: bool=True,
cache_timeout: Optional[int]=None,
conditional: bool=False,
last_modified: Optional[datetime]=None,
) -> Response:
file_path = file_path_to_path(filename)
if attachment_filename is None:
attachment_filename = file_path.name
if mimetype is None:
mimetype = mimetypes.guess_type(attachment_filename)[0] or DEFAULT_MIMETYPE
file_body = current_app.response_class.file_body_class(file_path)
response = current_app.response_class(file_body, mimetype=mimetype)
if as_attachment:
response.headers.add('Content-Disposition', 'attachment', filename=attachment_filename)
if last_modified is not None:
response.last_modified = last_modified
else:
response.last_modified = datetime.fromtimestamp(file_path.stat().st_mtime)
response.cache_control.public = True
cache_timeout = cache_timeout or current_app.get_send_file_max_age(file_path)
if cache_timeout is not None:
response.cache_control.max_age = cache_timeout
response.expires = datetime.utcnow() + timedelta(seconds=cache_timeout)
if add_etags:
response.set_etag(
'{}-{}-{}'.format(
file_path.stat().st_mtime, file_path.stat().st_size,
adler32(bytes(file_path)),
),
)
if conditional:
await response.make_conditional(request.range)
return response | [
"async",
"def",
"send_file",
"(",
"filename",
":",
"FilePath",
",",
"mimetype",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
",",
"as_attachment",
":",
"bool",
"=",
"False",
",",
"attachment_filename",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
","... | Return a Reponse to send the filename given.
Arguments:
filename: The filename (path) to send, remember to use
:func:`safe_join`.
mimetype: Mimetype to use, by default it will be guessed or
revert to the DEFAULT_MIMETYPE.
as_attachment: If true use the attachment filename in a
Content-Disposition attachment header.
attachment_filename: Name for the filename, if it differs
add_etags: Set etags based on the filename, size and
modification time.
last_modified: Used to override the last modified value.
cache_timeout: Time in seconds for the response to be cached. | [
"Return",
"a",
"Reponse",
"to",
"send",
"the",
"filename",
"given",
"."
] | 7cb2d3bd98e8746025764f2b933abc12041fa175 | https://github.com/pgjones/quart/blob/7cb2d3bd98e8746025764f2b933abc12041fa175/quart/static.py#L172-L230 |
245,628 | manrajgrover/halo | halo/halo.py | Halo._render_frame | def _render_frame(self):
"""Renders the frame on the line after clearing it.
"""
frame = self.frame()
output = '\r{0}'.format(frame)
self.clear()
try:
self._stream.write(output)
except UnicodeEncodeError:
self._stream.write(encode_utf_8_text(output)) | python | def _render_frame(self):
frame = self.frame()
output = '\r{0}'.format(frame)
self.clear()
try:
self._stream.write(output)
except UnicodeEncodeError:
self._stream.write(encode_utf_8_text(output)) | [
"def",
"_render_frame",
"(",
"self",
")",
":",
"frame",
"=",
"self",
".",
"frame",
"(",
")",
"output",
"=",
"'\\r{0}'",
".",
"format",
"(",
"frame",
")",
"self",
".",
"clear",
"(",
")",
"try",
":",
"self",
".",
"_stream",
".",
"write",
"(",
"output... | Renders the frame on the line after clearing it. | [
"Renders",
"the",
"frame",
"on",
"the",
"line",
"after",
"clearing",
"it",
"."
] | 0ac5149dea965b27b09f0776df9095ebf013fb4d | https://github.com/manrajgrover/halo/blob/0ac5149dea965b27b09f0776df9095ebf013fb4d/halo/halo.py#L336-L345 |
245,629 | manrajgrover/halo | halo/_utils.py | get_environment | def get_environment():
"""Get the environment in which halo is running
Returns
-------
str
Environment name
"""
try:
from IPython import get_ipython
except ImportError:
return 'terminal'
try:
shell = get_ipython().__class__.__name__
if shell == 'ZMQInteractiveShell': # Jupyter notebook or qtconsole
return 'jupyter'
elif shell == 'TerminalInteractiveShell': # Terminal running IPython
return 'ipython'
else:
return 'terminal' # Other type (?)
except NameError:
return 'terminal' | python | def get_environment():
try:
from IPython import get_ipython
except ImportError:
return 'terminal'
try:
shell = get_ipython().__class__.__name__
if shell == 'ZMQInteractiveShell': # Jupyter notebook or qtconsole
return 'jupyter'
elif shell == 'TerminalInteractiveShell': # Terminal running IPython
return 'ipython'
else:
return 'terminal' # Other type (?)
except NameError:
return 'terminal' | [
"def",
"get_environment",
"(",
")",
":",
"try",
":",
"from",
"IPython",
"import",
"get_ipython",
"except",
"ImportError",
":",
"return",
"'terminal'",
"try",
":",
"shell",
"=",
"get_ipython",
"(",
")",
".",
"__class__",
".",
"__name__",
"if",
"shell",
"==",
... | Get the environment in which halo is running
Returns
-------
str
Environment name | [
"Get",
"the",
"environment",
"in",
"which",
"halo",
"is",
"running"
] | 0ac5149dea965b27b09f0776df9095ebf013fb4d | https://github.com/manrajgrover/halo/blob/0ac5149dea965b27b09f0776df9095ebf013fb4d/halo/_utils.py#L35-L59 |
245,630 | manrajgrover/halo | halo/_utils.py | is_text_type | def is_text_type(text):
"""Check if given parameter is a string or not
Parameters
----------
text : *
Parameter to be checked for text type
Returns
-------
bool
Whether parameter is a string or not
"""
if isinstance(text, six.text_type) or isinstance(text, six.string_types):
return True
return False | python | def is_text_type(text):
if isinstance(text, six.text_type) or isinstance(text, six.string_types):
return True
return False | [
"def",
"is_text_type",
"(",
"text",
")",
":",
"if",
"isinstance",
"(",
"text",
",",
"six",
".",
"text_type",
")",
"or",
"isinstance",
"(",
"text",
",",
"six",
".",
"string_types",
")",
":",
"return",
"True",
"return",
"False"
] | Check if given parameter is a string or not
Parameters
----------
text : *
Parameter to be checked for text type
Returns
-------
bool
Whether parameter is a string or not | [
"Check",
"if",
"given",
"parameter",
"is",
"a",
"string",
"or",
"not"
] | 0ac5149dea965b27b09f0776df9095ebf013fb4d | https://github.com/manrajgrover/halo/blob/0ac5149dea965b27b09f0776df9095ebf013fb4d/halo/_utils.py#L80-L96 |
245,631 | GibbsConsulting/django-plotly-dash | django_plotly_dash/models.py | find_stateless_by_name | def find_stateless_by_name(name):
'''
Find stateless app given its name
First search the Django ORM, and if not found then look the app up in a local registry.
If the app does not have an ORM entry then a StatelessApp model instance is created.
'''
try:
dsa_app = StatelessApp.objects.get(app_name=name) # pylint: disable=no-member
return dsa_app.as_dash_app()
except: # pylint: disable=bare-except
pass
dash_app = get_stateless_by_name(name)
dsa_app = StatelessApp(app_name=name)
dsa_app.save()
return dash_app | python | def find_stateless_by_name(name):
'''
Find stateless app given its name
First search the Django ORM, and if not found then look the app up in a local registry.
If the app does not have an ORM entry then a StatelessApp model instance is created.
'''
try:
dsa_app = StatelessApp.objects.get(app_name=name) # pylint: disable=no-member
return dsa_app.as_dash_app()
except: # pylint: disable=bare-except
pass
dash_app = get_stateless_by_name(name)
dsa_app = StatelessApp(app_name=name)
dsa_app.save()
return dash_app | [
"def",
"find_stateless_by_name",
"(",
"name",
")",
":",
"try",
":",
"dsa_app",
"=",
"StatelessApp",
".",
"objects",
".",
"get",
"(",
"app_name",
"=",
"name",
")",
"# pylint: disable=no-member",
"return",
"dsa_app",
".",
"as_dash_app",
"(",
")",
"except",
":",
... | Find stateless app given its name
First search the Django ORM, and if not found then look the app up in a local registry.
If the app does not have an ORM entry then a StatelessApp model instance is created. | [
"Find",
"stateless",
"app",
"given",
"its",
"name"
] | 773ed081fc2ea3cc7607590322a14686a7a79bc5 | https://github.com/GibbsConsulting/django-plotly-dash/blob/773ed081fc2ea3cc7607590322a14686a7a79bc5/django_plotly_dash/models.py#L63-L79 |
245,632 | GibbsConsulting/django-plotly-dash | django_plotly_dash/models.py | StatelessApp.as_dash_app | def as_dash_app(self):
'''
Return a DjangoDash instance of the dash application
'''
dateless_dash_app = getattr(self, '_stateless_dash_app_instance', None)
if not dateless_dash_app:
dateless_dash_app = get_stateless_by_name(self.app_name)
setattr(self, '_stateless_dash_app_instance', dateless_dash_app)
return dateless_dash_app | python | def as_dash_app(self):
'''
Return a DjangoDash instance of the dash application
'''
dateless_dash_app = getattr(self, '_stateless_dash_app_instance', None)
if not dateless_dash_app:
dateless_dash_app = get_stateless_by_name(self.app_name)
setattr(self, '_stateless_dash_app_instance', dateless_dash_app)
return dateless_dash_app | [
"def",
"as_dash_app",
"(",
"self",
")",
":",
"dateless_dash_app",
"=",
"getattr",
"(",
"self",
",",
"'_stateless_dash_app_instance'",
",",
"None",
")",
"if",
"not",
"dateless_dash_app",
":",
"dateless_dash_app",
"=",
"get_stateless_by_name",
"(",
"self",
".",
"app... | Return a DjangoDash instance of the dash application | [
"Return",
"a",
"DjangoDash",
"instance",
"of",
"the",
"dash",
"application"
] | 773ed081fc2ea3cc7607590322a14686a7a79bc5 | https://github.com/GibbsConsulting/django-plotly-dash/blob/773ed081fc2ea3cc7607590322a14686a7a79bc5/django_plotly_dash/models.py#L53-L61 |
245,633 | GibbsConsulting/django-plotly-dash | django_plotly_dash/models.py | DashApp.handle_current_state | def handle_current_state(self):
'''
Check to see if the current hydrated state and the saved state are different.
If they are, then persist the current state in the database by saving the model instance.
'''
if getattr(self, '_current_state_hydrated_changed', False) and self.save_on_change:
new_base_state = json.dumps(getattr(self, '_current_state_hydrated', {}))
if new_base_state != self.base_state:
self.base_state = new_base_state
self.save() | python | def handle_current_state(self):
'''
Check to see if the current hydrated state and the saved state are different.
If they are, then persist the current state in the database by saving the model instance.
'''
if getattr(self, '_current_state_hydrated_changed', False) and self.save_on_change:
new_base_state = json.dumps(getattr(self, '_current_state_hydrated', {}))
if new_base_state != self.base_state:
self.base_state = new_base_state
self.save() | [
"def",
"handle_current_state",
"(",
"self",
")",
":",
"if",
"getattr",
"(",
"self",
",",
"'_current_state_hydrated_changed'",
",",
"False",
")",
"and",
"self",
".",
"save_on_change",
":",
"new_base_state",
"=",
"json",
".",
"dumps",
"(",
"getattr",
"(",
"self"... | Check to see if the current hydrated state and the saved state are different.
If they are, then persist the current state in the database by saving the model instance. | [
"Check",
"to",
"see",
"if",
"the",
"current",
"hydrated",
"state",
"and",
"the",
"saved",
"state",
"are",
"different",
"."
] | 773ed081fc2ea3cc7607590322a14686a7a79bc5 | https://github.com/GibbsConsulting/django-plotly-dash/blob/773ed081fc2ea3cc7607590322a14686a7a79bc5/django_plotly_dash/models.py#L114-L124 |
245,634 | GibbsConsulting/django-plotly-dash | django_plotly_dash/models.py | DashApp.have_current_state_entry | def have_current_state_entry(self, wid, key):
'Return True if there is a cached current state for this app'
cscoll = self.current_state()
c_state = cscoll.get(wid, {})
return key in c_state | python | def have_current_state_entry(self, wid, key):
'Return True if there is a cached current state for this app'
cscoll = self.current_state()
c_state = cscoll.get(wid, {})
return key in c_state | [
"def",
"have_current_state_entry",
"(",
"self",
",",
"wid",
",",
"key",
")",
":",
"cscoll",
"=",
"self",
".",
"current_state",
"(",
")",
"c_state",
"=",
"cscoll",
".",
"get",
"(",
"wid",
",",
"{",
"}",
")",
"return",
"key",
"in",
"c_state"
] | Return True if there is a cached current state for this app | [
"Return",
"True",
"if",
"there",
"is",
"a",
"cached",
"current",
"state",
"for",
"this",
"app"
] | 773ed081fc2ea3cc7607590322a14686a7a79bc5 | https://github.com/GibbsConsulting/django-plotly-dash/blob/773ed081fc2ea3cc7607590322a14686a7a79bc5/django_plotly_dash/models.py#L126-L130 |
245,635 | GibbsConsulting/django-plotly-dash | django_plotly_dash/models.py | DashApp.current_state | def current_state(self):
'''
Return the current internal state of the model instance.
This is not necessarily the same as the persisted state
stored in the self.base_state variable.
'''
c_state = getattr(self, '_current_state_hydrated', None)
if not c_state:
c_state = json.loads(self.base_state)
setattr(self, '_current_state_hydrated', c_state)
setattr(self, '_current_state_hydrated_changed', False)
return c_state | python | def current_state(self):
'''
Return the current internal state of the model instance.
This is not necessarily the same as the persisted state
stored in the self.base_state variable.
'''
c_state = getattr(self, '_current_state_hydrated', None)
if not c_state:
c_state = json.loads(self.base_state)
setattr(self, '_current_state_hydrated', c_state)
setattr(self, '_current_state_hydrated_changed', False)
return c_state | [
"def",
"current_state",
"(",
"self",
")",
":",
"c_state",
"=",
"getattr",
"(",
"self",
",",
"'_current_state_hydrated'",
",",
"None",
")",
"if",
"not",
"c_state",
":",
"c_state",
"=",
"json",
".",
"loads",
"(",
"self",
".",
"base_state",
")",
"setattr",
... | Return the current internal state of the model instance.
This is not necessarily the same as the persisted state
stored in the self.base_state variable. | [
"Return",
"the",
"current",
"internal",
"state",
"of",
"the",
"model",
"instance",
"."
] | 773ed081fc2ea3cc7607590322a14686a7a79bc5 | https://github.com/GibbsConsulting/django-plotly-dash/blob/773ed081fc2ea3cc7607590322a14686a7a79bc5/django_plotly_dash/models.py#L146-L158 |
245,636 | GibbsConsulting/django-plotly-dash | django_plotly_dash/models.py | DashApp.as_dash_instance | def as_dash_instance(self, cache_id=None):
'Return a dash application instance for this model instance'
dash_app = self.stateless_app.as_dash_app() # pylint: disable=no-member
base = self.current_state()
return dash_app.do_form_dash_instance(replacements=base,
specific_identifier=self.slug,
cache_id=cache_id) | python | def as_dash_instance(self, cache_id=None):
'Return a dash application instance for this model instance'
dash_app = self.stateless_app.as_dash_app() # pylint: disable=no-member
base = self.current_state()
return dash_app.do_form_dash_instance(replacements=base,
specific_identifier=self.slug,
cache_id=cache_id) | [
"def",
"as_dash_instance",
"(",
"self",
",",
"cache_id",
"=",
"None",
")",
":",
"dash_app",
"=",
"self",
".",
"stateless_app",
".",
"as_dash_app",
"(",
")",
"# pylint: disable=no-member",
"base",
"=",
"self",
".",
"current_state",
"(",
")",
"return",
"dash_app... | Return a dash application instance for this model instance | [
"Return",
"a",
"dash",
"application",
"instance",
"for",
"this",
"model",
"instance"
] | 773ed081fc2ea3cc7607590322a14686a7a79bc5 | https://github.com/GibbsConsulting/django-plotly-dash/blob/773ed081fc2ea3cc7607590322a14686a7a79bc5/django_plotly_dash/models.py#L160-L166 |
245,637 | GibbsConsulting/django-plotly-dash | django_plotly_dash/models.py | DashApp._get_base_state | def _get_base_state(self):
'''
Get the base state of the object, as defined by the app.layout code, as a python dict
'''
base_app_inst = self.stateless_app.as_dash_app().as_dash_instance() # pylint: disable=no-member
# Get base layout response, from a base object
base_resp = base_app_inst.locate_endpoint_function('dash-layout')()
base_obj = json.loads(base_resp.data.decode('utf-8'))
# Walk the base layout and find all values; insert into base state map
obj = {}
base_app_inst.walk_tree_and_extract(base_obj, obj)
return obj | python | def _get_base_state(self):
'''
Get the base state of the object, as defined by the app.layout code, as a python dict
'''
base_app_inst = self.stateless_app.as_dash_app().as_dash_instance() # pylint: disable=no-member
# Get base layout response, from a base object
base_resp = base_app_inst.locate_endpoint_function('dash-layout')()
base_obj = json.loads(base_resp.data.decode('utf-8'))
# Walk the base layout and find all values; insert into base state map
obj = {}
base_app_inst.walk_tree_and_extract(base_obj, obj)
return obj | [
"def",
"_get_base_state",
"(",
"self",
")",
":",
"base_app_inst",
"=",
"self",
".",
"stateless_app",
".",
"as_dash_app",
"(",
")",
".",
"as_dash_instance",
"(",
")",
"# pylint: disable=no-member",
"# Get base layout response, from a base object",
"base_resp",
"=",
"base... | Get the base state of the object, as defined by the app.layout code, as a python dict | [
"Get",
"the",
"base",
"state",
"of",
"the",
"object",
"as",
"defined",
"by",
"the",
"app",
".",
"layout",
"code",
"as",
"a",
"python",
"dict"
] | 773ed081fc2ea3cc7607590322a14686a7a79bc5 | https://github.com/GibbsConsulting/django-plotly-dash/blob/773ed081fc2ea3cc7607590322a14686a7a79bc5/django_plotly_dash/models.py#L168-L182 |
245,638 | GibbsConsulting/django-plotly-dash | django_plotly_dash/models.py | DashApp.populate_values | def populate_values(self):
'''
Add values from the underlying dash layout configuration
'''
obj = self._get_base_state()
self.base_state = json.dumps(obj) | python | def populate_values(self):
'''
Add values from the underlying dash layout configuration
'''
obj = self._get_base_state()
self.base_state = json.dumps(obj) | [
"def",
"populate_values",
"(",
"self",
")",
":",
"obj",
"=",
"self",
".",
"_get_base_state",
"(",
")",
"self",
".",
"base_state",
"=",
"json",
".",
"dumps",
"(",
"obj",
")"
] | Add values from the underlying dash layout configuration | [
"Add",
"values",
"from",
"the",
"underlying",
"dash",
"layout",
"configuration"
] | 773ed081fc2ea3cc7607590322a14686a7a79bc5 | https://github.com/GibbsConsulting/django-plotly-dash/blob/773ed081fc2ea3cc7607590322a14686a7a79bc5/django_plotly_dash/models.py#L184-L189 |
245,639 | GibbsConsulting/django-plotly-dash | django_plotly_dash/models.py | DashApp.locate_item | def locate_item(ident, stateless=False, cache_id=None):
'''Locate a dash application, given either the
slug of an instance or the name for a stateless app'''
if stateless:
dash_app = find_stateless_by_name(ident)
else:
dash_app = get_object_or_404(DashApp, slug=ident)
app = dash_app.as_dash_instance(cache_id=cache_id)
return dash_app, app | python | def locate_item(ident, stateless=False, cache_id=None):
'''Locate a dash application, given either the
slug of an instance or the name for a stateless app'''
if stateless:
dash_app = find_stateless_by_name(ident)
else:
dash_app = get_object_or_404(DashApp, slug=ident)
app = dash_app.as_dash_instance(cache_id=cache_id)
return dash_app, app | [
"def",
"locate_item",
"(",
"ident",
",",
"stateless",
"=",
"False",
",",
"cache_id",
"=",
"None",
")",
":",
"if",
"stateless",
":",
"dash_app",
"=",
"find_stateless_by_name",
"(",
"ident",
")",
"else",
":",
"dash_app",
"=",
"get_object_or_404",
"(",
"DashApp... | Locate a dash application, given either the
slug of an instance or the name for a stateless app | [
"Locate",
"a",
"dash",
"application",
"given",
"either",
"the",
"slug",
"of",
"an",
"instance",
"or",
"the",
"name",
"for",
"a",
"stateless",
"app"
] | 773ed081fc2ea3cc7607590322a14686a7a79bc5 | https://github.com/GibbsConsulting/django-plotly-dash/blob/773ed081fc2ea3cc7607590322a14686a7a79bc5/django_plotly_dash/models.py#L192-L201 |
245,640 | GibbsConsulting/django-plotly-dash | django_plotly_dash/consumers.py | send_to_pipe_channel | def send_to_pipe_channel(channel_name,
label,
value):
'Send message through pipe to client component'
async_to_sync(async_send_to_pipe_channel)(channel_name=channel_name,
label=label,
value=value) | python | def send_to_pipe_channel(channel_name,
label,
value):
'Send message through pipe to client component'
async_to_sync(async_send_to_pipe_channel)(channel_name=channel_name,
label=label,
value=value) | [
"def",
"send_to_pipe_channel",
"(",
"channel_name",
",",
"label",
",",
"value",
")",
":",
"async_to_sync",
"(",
"async_send_to_pipe_channel",
")",
"(",
"channel_name",
"=",
"channel_name",
",",
"label",
"=",
"label",
",",
"value",
"=",
"value",
")"
] | Send message through pipe to client component | [
"Send",
"message",
"through",
"pipe",
"to",
"client",
"component"
] | 773ed081fc2ea3cc7607590322a14686a7a79bc5 | https://github.com/GibbsConsulting/django-plotly-dash/blob/773ed081fc2ea3cc7607590322a14686a7a79bc5/django_plotly_dash/consumers.py#L35-L41 |
245,641 | GibbsConsulting/django-plotly-dash | django_plotly_dash/consumers.py | async_send_to_pipe_channel | async def async_send_to_pipe_channel(channel_name,
label,
value):
'Send message asynchronously through pipe to client component'
pcn = _form_pipe_channel_name(channel_name)
channel_layer = get_channel_layer()
await channel_layer.group_send(pcn,
{"type":"pipe.value",
"label":label,
"value":value}) | python | async def async_send_to_pipe_channel(channel_name,
label,
value):
'Send message asynchronously through pipe to client component'
pcn = _form_pipe_channel_name(channel_name)
channel_layer = get_channel_layer()
await channel_layer.group_send(pcn,
{"type":"pipe.value",
"label":label,
"value":value}) | [
"async",
"def",
"async_send_to_pipe_channel",
"(",
"channel_name",
",",
"label",
",",
"value",
")",
":",
"pcn",
"=",
"_form_pipe_channel_name",
"(",
"channel_name",
")",
"channel_layer",
"=",
"get_channel_layer",
"(",
")",
"await",
"channel_layer",
".",
"group_send"... | Send message asynchronously through pipe to client component | [
"Send",
"message",
"asynchronously",
"through",
"pipe",
"to",
"client",
"component"
] | 773ed081fc2ea3cc7607590322a14686a7a79bc5 | https://github.com/GibbsConsulting/django-plotly-dash/blob/773ed081fc2ea3cc7607590322a14686a7a79bc5/django_plotly_dash/consumers.py#L43-L53 |
245,642 | GibbsConsulting/django-plotly-dash | django_plotly_dash/consumers.py | MessageConsumer.pipe_value | def pipe_value(self, message):
'Send a new value into the ws pipe'
jmsg = json.dumps(message)
self.send(jmsg) | python | def pipe_value(self, message):
'Send a new value into the ws pipe'
jmsg = json.dumps(message)
self.send(jmsg) | [
"def",
"pipe_value",
"(",
"self",
",",
"message",
")",
":",
"jmsg",
"=",
"json",
".",
"dumps",
"(",
"message",
")",
"self",
".",
"send",
"(",
"jmsg",
")"
] | Send a new value into the ws pipe | [
"Send",
"a",
"new",
"value",
"into",
"the",
"ws",
"pipe"
] | 773ed081fc2ea3cc7607590322a14686a7a79bc5 | https://github.com/GibbsConsulting/django-plotly-dash/blob/773ed081fc2ea3cc7607590322a14686a7a79bc5/django_plotly_dash/consumers.py#L72-L75 |
245,643 | GibbsConsulting/django-plotly-dash | django_plotly_dash/consumers.py | MessageConsumer.update_pipe_channel | def update_pipe_channel(self, uid, channel_name, label): # pylint: disable=unused-argument
'''
Update this consumer to listen on channel_name for the js widget associated with uid
'''
pipe_group_name = _form_pipe_channel_name(channel_name)
if self.channel_layer:
current = self.channel_maps.get(uid, None)
if current != pipe_group_name:
if current:
async_to_sync(self.channel_layer.group_discard)(current, self.channel_name)
self.channel_maps[uid] = pipe_group_name
async_to_sync(self.channel_layer.group_add)(pipe_group_name, self.channel_name) | python | def update_pipe_channel(self, uid, channel_name, label): # pylint: disable=unused-argument
'''
Update this consumer to listen on channel_name for the js widget associated with uid
'''
pipe_group_name = _form_pipe_channel_name(channel_name)
if self.channel_layer:
current = self.channel_maps.get(uid, None)
if current != pipe_group_name:
if current:
async_to_sync(self.channel_layer.group_discard)(current, self.channel_name)
self.channel_maps[uid] = pipe_group_name
async_to_sync(self.channel_layer.group_add)(pipe_group_name, self.channel_name) | [
"def",
"update_pipe_channel",
"(",
"self",
",",
"uid",
",",
"channel_name",
",",
"label",
")",
":",
"# pylint: disable=unused-argument",
"pipe_group_name",
"=",
"_form_pipe_channel_name",
"(",
"channel_name",
")",
"if",
"self",
".",
"channel_layer",
":",
"current",
... | Update this consumer to listen on channel_name for the js widget associated with uid | [
"Update",
"this",
"consumer",
"to",
"listen",
"on",
"channel_name",
"for",
"the",
"js",
"widget",
"associated",
"with",
"uid"
] | 773ed081fc2ea3cc7607590322a14686a7a79bc5 | https://github.com/GibbsConsulting/django-plotly-dash/blob/773ed081fc2ea3cc7607590322a14686a7a79bc5/django_plotly_dash/consumers.py#L77-L90 |
245,644 | GibbsConsulting/django-plotly-dash | django_plotly_dash/util.py | store_initial_arguments | def store_initial_arguments(request, initial_arguments=None):
'Store initial arguments, if any, and return a cache identifier'
if initial_arguments is None:
return None
# Generate a cache id
cache_id = "dpd-initial-args-%s" % str(uuid.uuid4()).replace('-', '')
# Store args in json form in cache
if initial_argument_location():
cache.set(cache_id, initial_arguments, cache_timeout_initial_arguments())
else:
request.session[cache_id] = initial_arguments
return cache_id | python | def store_initial_arguments(request, initial_arguments=None):
'Store initial arguments, if any, and return a cache identifier'
if initial_arguments is None:
return None
# Generate a cache id
cache_id = "dpd-initial-args-%s" % str(uuid.uuid4()).replace('-', '')
# Store args in json form in cache
if initial_argument_location():
cache.set(cache_id, initial_arguments, cache_timeout_initial_arguments())
else:
request.session[cache_id] = initial_arguments
return cache_id | [
"def",
"store_initial_arguments",
"(",
"request",
",",
"initial_arguments",
"=",
"None",
")",
":",
"if",
"initial_arguments",
"is",
"None",
":",
"return",
"None",
"# Generate a cache id",
"cache_id",
"=",
"\"dpd-initial-args-%s\"",
"%",
"str",
"(",
"uuid",
".",
"u... | Store initial arguments, if any, and return a cache identifier | [
"Store",
"initial",
"arguments",
"if",
"any",
"and",
"return",
"a",
"cache",
"identifier"
] | 773ed081fc2ea3cc7607590322a14686a7a79bc5 | https://github.com/GibbsConsulting/django-plotly-dash/blob/773ed081fc2ea3cc7607590322a14686a7a79bc5/django_plotly_dash/util.py#L72-L87 |
245,645 | GibbsConsulting/django-plotly-dash | django_plotly_dash/util.py | get_initial_arguments | def get_initial_arguments(request, cache_id=None):
'Extract initial arguments for the dash app'
if cache_id is None:
return None
if initial_argument_location():
return cache.get(cache_id)
return request.session[cache_id] | python | def get_initial_arguments(request, cache_id=None):
'Extract initial arguments for the dash app'
if cache_id is None:
return None
if initial_argument_location():
return cache.get(cache_id)
return request.session[cache_id] | [
"def",
"get_initial_arguments",
"(",
"request",
",",
"cache_id",
"=",
"None",
")",
":",
"if",
"cache_id",
"is",
"None",
":",
"return",
"None",
"if",
"initial_argument_location",
"(",
")",
":",
"return",
"cache",
".",
"get",
"(",
"cache_id",
")",
"return",
... | Extract initial arguments for the dash app | [
"Extract",
"initial",
"arguments",
"for",
"the",
"dash",
"app"
] | 773ed081fc2ea3cc7607590322a14686a7a79bc5 | https://github.com/GibbsConsulting/django-plotly-dash/blob/773ed081fc2ea3cc7607590322a14686a7a79bc5/django_plotly_dash/util.py#L89-L98 |
245,646 | GibbsConsulting/django-plotly-dash | django_plotly_dash/views.py | dependencies | def dependencies(request, ident, stateless=False, **kwargs):
'Return the dependencies'
_, app = DashApp.locate_item(ident, stateless)
with app.app_context():
view_func = app.locate_endpoint_function('dash-dependencies')
resp = view_func()
return HttpResponse(resp.data,
content_type=resp.mimetype) | python | def dependencies(request, ident, stateless=False, **kwargs):
'Return the dependencies'
_, app = DashApp.locate_item(ident, stateless)
with app.app_context():
view_func = app.locate_endpoint_function('dash-dependencies')
resp = view_func()
return HttpResponse(resp.data,
content_type=resp.mimetype) | [
"def",
"dependencies",
"(",
"request",
",",
"ident",
",",
"stateless",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"_",
",",
"app",
"=",
"DashApp",
".",
"locate_item",
"(",
"ident",
",",
"stateless",
")",
"with",
"app",
".",
"app_context",
"(",
... | Return the dependencies | [
"Return",
"the",
"dependencies"
] | 773ed081fc2ea3cc7607590322a14686a7a79bc5 | https://github.com/GibbsConsulting/django-plotly-dash/blob/773ed081fc2ea3cc7607590322a14686a7a79bc5/django_plotly_dash/views.py#L39-L47 |
245,647 | GibbsConsulting/django-plotly-dash | django_plotly_dash/views.py | layout | def layout(request, ident, stateless=False, cache_id=None, **kwargs):
'Return the layout of the dash application'
_, app = DashApp.locate_item(ident, stateless)
view_func = app.locate_endpoint_function('dash-layout')
resp = view_func()
initial_arguments = get_initial_arguments(request, cache_id)
response_data, mimetype = app.augment_initial_layout(resp, initial_arguments)
return HttpResponse(response_data,
content_type=mimetype) | python | def layout(request, ident, stateless=False, cache_id=None, **kwargs):
'Return the layout of the dash application'
_, app = DashApp.locate_item(ident, stateless)
view_func = app.locate_endpoint_function('dash-layout')
resp = view_func()
initial_arguments = get_initial_arguments(request, cache_id)
response_data, mimetype = app.augment_initial_layout(resp, initial_arguments)
return HttpResponse(response_data,
content_type=mimetype) | [
"def",
"layout",
"(",
"request",
",",
"ident",
",",
"stateless",
"=",
"False",
",",
"cache_id",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"_",
",",
"app",
"=",
"DashApp",
".",
"locate_item",
"(",
"ident",
",",
"stateless",
")",
"view_func",
"="... | Return the layout of the dash application | [
"Return",
"the",
"layout",
"of",
"the",
"dash",
"application"
] | 773ed081fc2ea3cc7607590322a14686a7a79bc5 | https://github.com/GibbsConsulting/django-plotly-dash/blob/773ed081fc2ea3cc7607590322a14686a7a79bc5/django_plotly_dash/views.py#L49-L60 |
245,648 | GibbsConsulting/django-plotly-dash | django_plotly_dash/views.py | update | def update(request, ident, stateless=False, **kwargs):
'Generate update json response'
dash_app, app = DashApp.locate_item(ident, stateless)
request_body = json.loads(request.body.decode('utf-8'))
if app.use_dash_dispatch():
# Force call through dash
view_func = app.locate_endpoint_function('dash-update-component')
import flask
with app.test_request_context():
# Fudge request object
# pylint: disable=protected-access
flask.request._cached_json = (request_body, flask.request._cached_json[True])
resp = view_func()
else:
# Use direct dispatch with extra arguments in the argMap
app_state = request.session.get("django_plotly_dash", dict())
arg_map = {'dash_app_id': ident,
'dash_app': dash_app,
'user': request.user,
'session_state': app_state}
resp = app.dispatch_with_args(request_body, arg_map)
request.session['django_plotly_dash'] = app_state
dash_app.handle_current_state()
# Special for ws-driven edge case
if str(resp) == 'EDGECASEEXIT':
return HttpResponse("")
# Change in returned value type
try:
rdata = resp.data
rtype = resp.mimetype
except:
rdata = resp
rtype = "application/json"
return HttpResponse(rdata,
content_type=rtype) | python | def update(request, ident, stateless=False, **kwargs):
'Generate update json response'
dash_app, app = DashApp.locate_item(ident, stateless)
request_body = json.loads(request.body.decode('utf-8'))
if app.use_dash_dispatch():
# Force call through dash
view_func = app.locate_endpoint_function('dash-update-component')
import flask
with app.test_request_context():
# Fudge request object
# pylint: disable=protected-access
flask.request._cached_json = (request_body, flask.request._cached_json[True])
resp = view_func()
else:
# Use direct dispatch with extra arguments in the argMap
app_state = request.session.get("django_plotly_dash", dict())
arg_map = {'dash_app_id': ident,
'dash_app': dash_app,
'user': request.user,
'session_state': app_state}
resp = app.dispatch_with_args(request_body, arg_map)
request.session['django_plotly_dash'] = app_state
dash_app.handle_current_state()
# Special for ws-driven edge case
if str(resp) == 'EDGECASEEXIT':
return HttpResponse("")
# Change in returned value type
try:
rdata = resp.data
rtype = resp.mimetype
except:
rdata = resp
rtype = "application/json"
return HttpResponse(rdata,
content_type=rtype) | [
"def",
"update",
"(",
"request",
",",
"ident",
",",
"stateless",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"dash_app",
",",
"app",
"=",
"DashApp",
".",
"locate_item",
"(",
"ident",
",",
"stateless",
")",
"request_body",
"=",
"json",
".",
"loads"... | Generate update json response | [
"Generate",
"update",
"json",
"response"
] | 773ed081fc2ea3cc7607590322a14686a7a79bc5 | https://github.com/GibbsConsulting/django-plotly-dash/blob/773ed081fc2ea3cc7607590322a14686a7a79bc5/django_plotly_dash/views.py#L62-L102 |
245,649 | GibbsConsulting/django-plotly-dash | django_plotly_dash/views.py | main_view | def main_view(request, ident, stateless=False, cache_id=None, **kwargs):
'Main view for a dash app'
_, app = DashApp.locate_item(ident, stateless, cache_id=cache_id)
view_func = app.locate_endpoint_function()
resp = view_func()
return HttpResponse(resp) | python | def main_view(request, ident, stateless=False, cache_id=None, **kwargs):
'Main view for a dash app'
_, app = DashApp.locate_item(ident, stateless, cache_id=cache_id)
view_func = app.locate_endpoint_function()
resp = view_func()
return HttpResponse(resp) | [
"def",
"main_view",
"(",
"request",
",",
"ident",
",",
"stateless",
"=",
"False",
",",
"cache_id",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"_",
",",
"app",
"=",
"DashApp",
".",
"locate_item",
"(",
"ident",
",",
"stateless",
",",
"cache_id",
"... | Main view for a dash app | [
"Main",
"view",
"for",
"a",
"dash",
"app"
] | 773ed081fc2ea3cc7607590322a14686a7a79bc5 | https://github.com/GibbsConsulting/django-plotly-dash/blob/773ed081fc2ea3cc7607590322a14686a7a79bc5/django_plotly_dash/views.py#L104-L110 |
245,650 | GibbsConsulting/django-plotly-dash | django_plotly_dash/views.py | app_assets | def app_assets(request, **kwargs):
'Return a local dash app asset, served up through the Django static framework'
get_params = request.GET.urlencode()
extra_part = ""
if get_params:
redone_url = "/static/dash/assets/%s?%s" %(extra_part, get_params)
else:
redone_url = "/static/dash/assets/%s" % extra_part
return HttpResponseRedirect(redirect_to=redone_url) | python | def app_assets(request, **kwargs):
'Return a local dash app asset, served up through the Django static framework'
get_params = request.GET.urlencode()
extra_part = ""
if get_params:
redone_url = "/static/dash/assets/%s?%s" %(extra_part, get_params)
else:
redone_url = "/static/dash/assets/%s" % extra_part
return HttpResponseRedirect(redirect_to=redone_url) | [
"def",
"app_assets",
"(",
"request",
",",
"*",
"*",
"kwargs",
")",
":",
"get_params",
"=",
"request",
".",
"GET",
".",
"urlencode",
"(",
")",
"extra_part",
"=",
"\"\"",
"if",
"get_params",
":",
"redone_url",
"=",
"\"/static/dash/assets/%s?%s\"",
"%",
"(",
... | Return a local dash app asset, served up through the Django static framework | [
"Return",
"a",
"local",
"dash",
"app",
"asset",
"served",
"up",
"through",
"the",
"Django",
"static",
"framework"
] | 773ed081fc2ea3cc7607590322a14686a7a79bc5 | https://github.com/GibbsConsulting/django-plotly-dash/blob/773ed081fc2ea3cc7607590322a14686a7a79bc5/django_plotly_dash/views.py#L131-L140 |
245,651 | GibbsConsulting/django-plotly-dash | django_plotly_dash/views.py | add_to_session | def add_to_session(request, template_name="index.html", **kwargs):
'Add some info to a session in a place that django-plotly-dash can pass to a callback'
django_plotly_dash = request.session.get("django_plotly_dash", dict())
session_add_count = django_plotly_dash.get('add_counter', 0)
django_plotly_dash['add_counter'] = session_add_count + 1
request.session['django_plotly_dash'] = django_plotly_dash
return TemplateResponse(request, template_name, {}) | python | def add_to_session(request, template_name="index.html", **kwargs):
'Add some info to a session in a place that django-plotly-dash can pass to a callback'
django_plotly_dash = request.session.get("django_plotly_dash", dict())
session_add_count = django_plotly_dash.get('add_counter', 0)
django_plotly_dash['add_counter'] = session_add_count + 1
request.session['django_plotly_dash'] = django_plotly_dash
return TemplateResponse(request, template_name, {}) | [
"def",
"add_to_session",
"(",
"request",
",",
"template_name",
"=",
"\"index.html\"",
",",
"*",
"*",
"kwargs",
")",
":",
"django_plotly_dash",
"=",
"request",
".",
"session",
".",
"get",
"(",
"\"django_plotly_dash\"",
",",
"dict",
"(",
")",
")",
"session_add_c... | Add some info to a session in a place that django-plotly-dash can pass to a callback | [
"Add",
"some",
"info",
"to",
"a",
"session",
"in",
"a",
"place",
"that",
"django",
"-",
"plotly",
"-",
"dash",
"can",
"pass",
"to",
"a",
"callback"
] | 773ed081fc2ea3cc7607590322a14686a7a79bc5 | https://github.com/GibbsConsulting/django-plotly-dash/blob/773ed081fc2ea3cc7607590322a14686a7a79bc5/django_plotly_dash/views.py#L145-L154 |
245,652 | GibbsConsulting/django-plotly-dash | django_plotly_dash/views.py | asset_redirection | def asset_redirection(request, path, ident=None, stateless=False, **kwargs):
'Redirect static assets for a component'
X, app = DashApp.locate_item(ident, stateless)
# Redirect to a location based on the import path of the module containing the DjangoDash app
static_path = X.get_asset_static_url(path)
return redirect(static_path) | python | def asset_redirection(request, path, ident=None, stateless=False, **kwargs):
'Redirect static assets for a component'
X, app = DashApp.locate_item(ident, stateless)
# Redirect to a location based on the import path of the module containing the DjangoDash app
static_path = X.get_asset_static_url(path)
return redirect(static_path) | [
"def",
"asset_redirection",
"(",
"request",
",",
"path",
",",
"ident",
"=",
"None",
",",
"stateless",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"X",
",",
"app",
"=",
"DashApp",
".",
"locate_item",
"(",
"ident",
",",
"stateless",
")",
"# Redirect... | Redirect static assets for a component | [
"Redirect",
"static",
"assets",
"for",
"a",
"component"
] | 773ed081fc2ea3cc7607590322a14686a7a79bc5 | https://github.com/GibbsConsulting/django-plotly-dash/blob/773ed081fc2ea3cc7607590322a14686a7a79bc5/django_plotly_dash/views.py#L156-L164 |
245,653 | GibbsConsulting/django-plotly-dash | demo/demo/views.py | dash_example_1_view | def dash_example_1_view(request, template_name="demo_six.html", **kwargs):
'Example view that inserts content into the dash context passed to the dash application'
context = {}
# create some context to send over to Dash:
dash_context = request.session.get("django_plotly_dash", dict())
dash_context['django_to_dash_context'] = "I am Dash receiving context from Django"
request.session['django_plotly_dash'] = dash_context
return render(request, template_name=template_name, context=context) | python | def dash_example_1_view(request, template_name="demo_six.html", **kwargs):
'Example view that inserts content into the dash context passed to the dash application'
context = {}
# create some context to send over to Dash:
dash_context = request.session.get("django_plotly_dash", dict())
dash_context['django_to_dash_context'] = "I am Dash receiving context from Django"
request.session['django_plotly_dash'] = dash_context
return render(request, template_name=template_name, context=context) | [
"def",
"dash_example_1_view",
"(",
"request",
",",
"template_name",
"=",
"\"demo_six.html\"",
",",
"*",
"*",
"kwargs",
")",
":",
"context",
"=",
"{",
"}",
"# create some context to send over to Dash:",
"dash_context",
"=",
"request",
".",
"session",
".",
"get",
"(... | Example view that inserts content into the dash context passed to the dash application | [
"Example",
"view",
"that",
"inserts",
"content",
"into",
"the",
"dash",
"context",
"passed",
"to",
"the",
"dash",
"application"
] | 773ed081fc2ea3cc7607590322a14686a7a79bc5 | https://github.com/GibbsConsulting/django-plotly-dash/blob/773ed081fc2ea3cc7607590322a14686a7a79bc5/demo/demo/views.py#L9-L19 |
245,654 | GibbsConsulting/django-plotly-dash | demo/demo/views.py | session_state_view | def session_state_view(request, template_name, **kwargs):
'Example view that exhibits the use of sessions to store state'
session = request.session
demo_count = session.get('django_plotly_dash', {})
ind_use = demo_count.get('ind_use', 0)
ind_use += 1
demo_count['ind_use'] = ind_use
context = {'ind_use' : ind_use}
session['django_plotly_dash'] = demo_count
return render(request, template_name=template_name, context=context) | python | def session_state_view(request, template_name, **kwargs):
'Example view that exhibits the use of sessions to store state'
session = request.session
demo_count = session.get('django_plotly_dash', {})
ind_use = demo_count.get('ind_use', 0)
ind_use += 1
demo_count['ind_use'] = ind_use
context = {'ind_use' : ind_use}
session['django_plotly_dash'] = demo_count
return render(request, template_name=template_name, context=context) | [
"def",
"session_state_view",
"(",
"request",
",",
"template_name",
",",
"*",
"*",
"kwargs",
")",
":",
"session",
"=",
"request",
".",
"session",
"demo_count",
"=",
"session",
".",
"get",
"(",
"'django_plotly_dash'",
",",
"{",
"}",
")",
"ind_use",
"=",
"dem... | Example view that exhibits the use of sessions to store state | [
"Example",
"view",
"that",
"exhibits",
"the",
"use",
"of",
"sessions",
"to",
"store",
"state"
] | 773ed081fc2ea3cc7607590322a14686a7a79bc5 | https://github.com/GibbsConsulting/django-plotly-dash/blob/773ed081fc2ea3cc7607590322a14686a7a79bc5/demo/demo/views.py#L21-L36 |
245,655 | GibbsConsulting/django-plotly-dash | django_plotly_dash/middleware.py | ContentCollector.adjust_response | def adjust_response(self, response):
'Locate placeholder magic strings and replace with content'
try:
c1 = self._replace(response.content,
self.header_placeholder,
self.embedded_holder.css)
response.content = self._replace(c1,
self.footer_placeholder,
"\n".join([self.embedded_holder.config,
self.embedded_holder.scripts]))
except AttributeError:
# Catch the "FileResponse instance has no `content` attribute" error when serving media files in the Django development server.
pass
return response | python | def adjust_response(self, response):
'Locate placeholder magic strings and replace with content'
try:
c1 = self._replace(response.content,
self.header_placeholder,
self.embedded_holder.css)
response.content = self._replace(c1,
self.footer_placeholder,
"\n".join([self.embedded_holder.config,
self.embedded_holder.scripts]))
except AttributeError:
# Catch the "FileResponse instance has no `content` attribute" error when serving media files in the Django development server.
pass
return response | [
"def",
"adjust_response",
"(",
"self",
",",
"response",
")",
":",
"try",
":",
"c1",
"=",
"self",
".",
"_replace",
"(",
"response",
".",
"content",
",",
"self",
".",
"header_placeholder",
",",
"self",
".",
"embedded_holder",
".",
"css",
")",
"response",
"... | Locate placeholder magic strings and replace with content | [
"Locate",
"placeholder",
"magic",
"strings",
"and",
"replace",
"with",
"content"
] | 773ed081fc2ea3cc7607590322a14686a7a79bc5 | https://github.com/GibbsConsulting/django-plotly-dash/blob/773ed081fc2ea3cc7607590322a14686a7a79bc5/django_plotly_dash/middleware.py#L65-L81 |
245,656 | GibbsConsulting/django-plotly-dash | demo/demo/plotly_apps.py | callback_c | def callback_c(*args, **kwargs):
'Update the output following a change of the input selection'
#da = kwargs['dash_app']
session_state = kwargs['session_state']
calls_so_far = session_state.get('calls_so_far', 0)
session_state['calls_so_far'] = calls_so_far + 1
user_counts = session_state.get('user_counts', None)
user_name = str(kwargs['user'])
if user_counts is None:
user_counts = {user_name:1}
session_state['user_counts'] = user_counts
else:
user_counts[user_name] = user_counts.get(user_name, 0) + 1
return "Args are [%s] and kwargs are %s" %(",".join(args), str(kwargs)) | python | def callback_c(*args, **kwargs):
'Update the output following a change of the input selection'
#da = kwargs['dash_app']
session_state = kwargs['session_state']
calls_so_far = session_state.get('calls_so_far', 0)
session_state['calls_so_far'] = calls_so_far + 1
user_counts = session_state.get('user_counts', None)
user_name = str(kwargs['user'])
if user_counts is None:
user_counts = {user_name:1}
session_state['user_counts'] = user_counts
else:
user_counts[user_name] = user_counts.get(user_name, 0) + 1
return "Args are [%s] and kwargs are %s" %(",".join(args), str(kwargs)) | [
"def",
"callback_c",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"#da = kwargs['dash_app']",
"session_state",
"=",
"kwargs",
"[",
"'session_state'",
"]",
"calls_so_far",
"=",
"session_state",
".",
"get",
"(",
"'calls_so_far'",
",",
"0",
")",
"session_... | Update the output following a change of the input selection | [
"Update",
"the",
"output",
"following",
"a",
"change",
"of",
"the",
"input",
"selection"
] | 773ed081fc2ea3cc7607590322a14686a7a79bc5 | https://github.com/GibbsConsulting/django-plotly-dash/blob/773ed081fc2ea3cc7607590322a14686a7a79bc5/demo/demo/plotly_apps.py#L101-L118 |
245,657 | GibbsConsulting/django-plotly-dash | demo/demo/plotly_apps.py | callback_liveIn_button_press | def callback_liveIn_button_press(red_clicks, blue_clicks, green_clicks,
rc_timestamp, bc_timestamp, gc_timestamp, **kwargs): # pylint: disable=unused-argument
'Input app button pressed, so do something interesting'
if not rc_timestamp:
rc_timestamp = 0
if not bc_timestamp:
bc_timestamp = 0
if not gc_timestamp:
gc_timestamp = 0
if (rc_timestamp + bc_timestamp + gc_timestamp) < 1:
change_col = None
timestamp = 0
else:
if rc_timestamp > bc_timestamp:
change_col = "red"
timestamp = rc_timestamp
else:
change_col = "blue"
timestamp = bc_timestamp
if gc_timestamp > timestamp:
timestamp = gc_timestamp
change_col = "green"
value = {'red_clicks':red_clicks,
'blue_clicks':blue_clicks,
'green_clicks':green_clicks,
'click_colour':change_col,
'click_timestamp':timestamp,
'user':str(kwargs.get('user', 'UNKNOWN'))}
send_to_pipe_channel(channel_name="live_button_counter",
label="named_counts",
value=value)
return "Number of local clicks so far is %s red and %s blue; last change is %s at %s" % (red_clicks,
blue_clicks,
change_col,
datetime.fromtimestamp(0.001*timestamp)) | python | def callback_liveIn_button_press(red_clicks, blue_clicks, green_clicks,
rc_timestamp, bc_timestamp, gc_timestamp, **kwargs): # pylint: disable=unused-argument
'Input app button pressed, so do something interesting'
if not rc_timestamp:
rc_timestamp = 0
if not bc_timestamp:
bc_timestamp = 0
if not gc_timestamp:
gc_timestamp = 0
if (rc_timestamp + bc_timestamp + gc_timestamp) < 1:
change_col = None
timestamp = 0
else:
if rc_timestamp > bc_timestamp:
change_col = "red"
timestamp = rc_timestamp
else:
change_col = "blue"
timestamp = bc_timestamp
if gc_timestamp > timestamp:
timestamp = gc_timestamp
change_col = "green"
value = {'red_clicks':red_clicks,
'blue_clicks':blue_clicks,
'green_clicks':green_clicks,
'click_colour':change_col,
'click_timestamp':timestamp,
'user':str(kwargs.get('user', 'UNKNOWN'))}
send_to_pipe_channel(channel_name="live_button_counter",
label="named_counts",
value=value)
return "Number of local clicks so far is %s red and %s blue; last change is %s at %s" % (red_clicks,
blue_clicks,
change_col,
datetime.fromtimestamp(0.001*timestamp)) | [
"def",
"callback_liveIn_button_press",
"(",
"red_clicks",
",",
"blue_clicks",
",",
"green_clicks",
",",
"rc_timestamp",
",",
"bc_timestamp",
",",
"gc_timestamp",
",",
"*",
"*",
"kwargs",
")",
":",
"# pylint: disable=unused-argument",
"if",
"not",
"rc_timestamp",
":",
... | Input app button pressed, so do something interesting | [
"Input",
"app",
"button",
"pressed",
"so",
"do",
"something",
"interesting"
] | 773ed081fc2ea3cc7607590322a14686a7a79bc5 | https://github.com/GibbsConsulting/django-plotly-dash/blob/773ed081fc2ea3cc7607590322a14686a7a79bc5/demo/demo/plotly_apps.py#L149-L188 |
245,658 | GibbsConsulting/django-plotly-dash | demo/demo/plotly_apps.py | generate_liveOut_layout | def generate_liveOut_layout():
'Generate the layout per-app, generating each tine a new uuid for the state_uid argument'
return html.Div([
dpd.Pipe(id="named_count_pipe",
value=None,
label="named_counts",
channel_name="live_button_counter"),
html.Div(id="internal_state",
children="No state has been computed yet",
style={'display':'none'}),
dcc.Graph(id="timeseries_plot"),
dcc.Input(value=str(uuid.uuid4()),
id="state_uid",
style={'display':'none'},
)
]) | python | def generate_liveOut_layout():
'Generate the layout per-app, generating each tine a new uuid for the state_uid argument'
return html.Div([
dpd.Pipe(id="named_count_pipe",
value=None,
label="named_counts",
channel_name="live_button_counter"),
html.Div(id="internal_state",
children="No state has been computed yet",
style={'display':'none'}),
dcc.Graph(id="timeseries_plot"),
dcc.Input(value=str(uuid.uuid4()),
id="state_uid",
style={'display':'none'},
)
]) | [
"def",
"generate_liveOut_layout",
"(",
")",
":",
"return",
"html",
".",
"Div",
"(",
"[",
"dpd",
".",
"Pipe",
"(",
"id",
"=",
"\"named_count_pipe\"",
",",
"value",
"=",
"None",
",",
"label",
"=",
"\"named_counts\"",
",",
"channel_name",
"=",
"\"live_button_co... | Generate the layout per-app, generating each tine a new uuid for the state_uid argument | [
"Generate",
"the",
"layout",
"per",
"-",
"app",
"generating",
"each",
"tine",
"a",
"new",
"uuid",
"for",
"the",
"state_uid",
"argument"
] | 773ed081fc2ea3cc7607590322a14686a7a79bc5 | https://github.com/GibbsConsulting/django-plotly-dash/blob/773ed081fc2ea3cc7607590322a14686a7a79bc5/demo/demo/plotly_apps.py#L195-L210 |
245,659 | GibbsConsulting/django-plotly-dash | demo/demo/plotly_apps.py | callback_liveOut_pipe_in | def callback_liveOut_pipe_in(named_count, state_uid, **kwargs):
'Handle something changing the value of the input pipe or the associated state uid'
cache_key = _get_cache_key(state_uid)
state = cache.get(cache_key)
# If nothing in cache, prepopulate
if not state:
state = {}
# Guard against missing input on startup
if not named_count:
named_count = {}
# extract incoming info from the message and update the internal state
user = named_count.get('user', None)
click_colour = named_count.get('click_colour', None)
click_timestamp = named_count.get('click_timestamp', 0)
if click_colour:
colour_set = state.get(click_colour, None)
if not colour_set:
colour_set = [(None, 0, 100) for i in range(5)]
_, last_ts, prev = colour_set[-1]
# Loop over all existing timestamps and find the latest one
if not click_timestamp or click_timestamp < 1:
click_timestamp = 0
for _, the_colour_set in state.items():
_, lts, _ = the_colour_set[-1]
if lts > click_timestamp:
click_timestamp = lts
click_timestamp = click_timestamp + 1000
if click_timestamp > last_ts:
colour_set.append((user, click_timestamp, prev * random.lognormvariate(0.0, 0.1)),)
colour_set = colour_set[-100:]
state[click_colour] = colour_set
cache.set(cache_key, state, 3600)
return "(%s,%s)" % (cache_key, click_timestamp) | python | def callback_liveOut_pipe_in(named_count, state_uid, **kwargs):
'Handle something changing the value of the input pipe or the associated state uid'
cache_key = _get_cache_key(state_uid)
state = cache.get(cache_key)
# If nothing in cache, prepopulate
if not state:
state = {}
# Guard against missing input on startup
if not named_count:
named_count = {}
# extract incoming info from the message and update the internal state
user = named_count.get('user', None)
click_colour = named_count.get('click_colour', None)
click_timestamp = named_count.get('click_timestamp', 0)
if click_colour:
colour_set = state.get(click_colour, None)
if not colour_set:
colour_set = [(None, 0, 100) for i in range(5)]
_, last_ts, prev = colour_set[-1]
# Loop over all existing timestamps and find the latest one
if not click_timestamp or click_timestamp < 1:
click_timestamp = 0
for _, the_colour_set in state.items():
_, lts, _ = the_colour_set[-1]
if lts > click_timestamp:
click_timestamp = lts
click_timestamp = click_timestamp + 1000
if click_timestamp > last_ts:
colour_set.append((user, click_timestamp, prev * random.lognormvariate(0.0, 0.1)),)
colour_set = colour_set[-100:]
state[click_colour] = colour_set
cache.set(cache_key, state, 3600)
return "(%s,%s)" % (cache_key, click_timestamp) | [
"def",
"callback_liveOut_pipe_in",
"(",
"named_count",
",",
"state_uid",
",",
"*",
"*",
"kwargs",
")",
":",
"cache_key",
"=",
"_get_cache_key",
"(",
"state_uid",
")",
"state",
"=",
"cache",
".",
"get",
"(",
"cache_key",
")",
"# If nothing in cache, prepopulate",
... | Handle something changing the value of the input pipe or the associated state uid | [
"Handle",
"something",
"changing",
"the",
"value",
"of",
"the",
"input",
"pipe",
"or",
"the",
"associated",
"state",
"uid"
] | 773ed081fc2ea3cc7607590322a14686a7a79bc5 | https://github.com/GibbsConsulting/django-plotly-dash/blob/773ed081fc2ea3cc7607590322a14686a7a79bc5/demo/demo/plotly_apps.py#L221-L266 |
245,660 | GibbsConsulting/django-plotly-dash | demo/demo/plotly_apps.py | callback_show_timeseries | def callback_show_timeseries(internal_state_string, state_uid, **kwargs):
'Build a timeseries from the internal state'
cache_key = _get_cache_key(state_uid)
state = cache.get(cache_key)
# If nothing in cache, prepopulate
if not state:
state = {}
colour_series = {}
colors = {'red':'#FF0000',
'blue':'#0000FF',
'green':'#00FF00',
'yellow': '#FFFF00',
'cyan': '#00FFFF',
'magenta': '#FF00FF',
'black' : '#000000',
}
for colour, values in state.items():
timestamps = [datetime.fromtimestamp(int(0.001*ts)) for _, ts, _ in values if ts > 0]
#users = [user for user, ts, _ in values if ts > 0]
levels = [level for _, ts, level in values if ts > 0]
if colour in colors:
colour_series[colour] = pd.Series(levels, index=timestamps).groupby(level=0).first()
df = pd.DataFrame(colour_series).fillna(method="ffill").reset_index()[-25:]
traces = [go.Scatter(y=df[colour],
x=df['index'],
name=colour,
line=dict(color=colors.get(colour, '#000000')),
) for colour in colour_series]
return {'data':traces,
#'layout': go.Layout
} | python | def callback_show_timeseries(internal_state_string, state_uid, **kwargs):
'Build a timeseries from the internal state'
cache_key = _get_cache_key(state_uid)
state = cache.get(cache_key)
# If nothing in cache, prepopulate
if not state:
state = {}
colour_series = {}
colors = {'red':'#FF0000',
'blue':'#0000FF',
'green':'#00FF00',
'yellow': '#FFFF00',
'cyan': '#00FFFF',
'magenta': '#FF00FF',
'black' : '#000000',
}
for colour, values in state.items():
timestamps = [datetime.fromtimestamp(int(0.001*ts)) for _, ts, _ in values if ts > 0]
#users = [user for user, ts, _ in values if ts > 0]
levels = [level for _, ts, level in values if ts > 0]
if colour in colors:
colour_series[colour] = pd.Series(levels, index=timestamps).groupby(level=0).first()
df = pd.DataFrame(colour_series).fillna(method="ffill").reset_index()[-25:]
traces = [go.Scatter(y=df[colour],
x=df['index'],
name=colour,
line=dict(color=colors.get(colour, '#000000')),
) for colour in colour_series]
return {'data':traces,
#'layout': go.Layout
} | [
"def",
"callback_show_timeseries",
"(",
"internal_state_string",
",",
"state_uid",
",",
"*",
"*",
"kwargs",
")",
":",
"cache_key",
"=",
"_get_cache_key",
"(",
"state_uid",
")",
"state",
"=",
"cache",
".",
"get",
"(",
"cache_key",
")",
"# If nothing in cache, prepo... | Build a timeseries from the internal state | [
"Build",
"a",
"timeseries",
"from",
"the",
"internal",
"state"
] | 773ed081fc2ea3cc7607590322a14686a7a79bc5 | https://github.com/GibbsConsulting/django-plotly-dash/blob/773ed081fc2ea3cc7607590322a14686a7a79bc5/demo/demo/plotly_apps.py#L273-L311 |
245,661 | GibbsConsulting/django-plotly-dash | demo/demo/bootstrap_app.py | session_demo_danger_callback | def session_demo_danger_callback(da_children, session_state=None, **kwargs):
'Update output based just on state'
if not session_state:
return "Session state not yet available"
return "Session state contains: " + str(session_state.get('bootstrap_demo_state', "NOTHING")) + " and the page render count is " + str(session_state.get("ind_use", "NOT SET")) | python | def session_demo_danger_callback(da_children, session_state=None, **kwargs):
'Update output based just on state'
if not session_state:
return "Session state not yet available"
return "Session state contains: " + str(session_state.get('bootstrap_demo_state', "NOTHING")) + " and the page render count is " + str(session_state.get("ind_use", "NOT SET")) | [
"def",
"session_demo_danger_callback",
"(",
"da_children",
",",
"session_state",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"session_state",
":",
"return",
"\"Session state not yet available\"",
"return",
"\"Session state contains: \"",
"+",
"str",
"... | Update output based just on state | [
"Update",
"output",
"based",
"just",
"on",
"state"
] | 773ed081fc2ea3cc7607590322a14686a7a79bc5 | https://github.com/GibbsConsulting/django-plotly-dash/blob/773ed081fc2ea3cc7607590322a14686a7a79bc5/demo/demo/bootstrap_app.py#L57-L62 |
245,662 | GibbsConsulting/django-plotly-dash | demo/demo/bootstrap_app.py | session_demo_alert_callback | def session_demo_alert_callback(n_clicks, session_state=None, **kwargs):
'Output text based on both app state and session state'
if session_state is None:
raise NotImplementedError("Cannot handle a missing session state")
csf = session_state.get('bootstrap_demo_state', None)
if not csf:
csf = dict(clicks=0)
session_state['bootstrap_demo_state'] = csf
else:
csf['clicks'] = n_clicks
return "Button has been clicked %s times since the page was rendered" %n_clicks | python | def session_demo_alert_callback(n_clicks, session_state=None, **kwargs):
'Output text based on both app state and session state'
if session_state is None:
raise NotImplementedError("Cannot handle a missing session state")
csf = session_state.get('bootstrap_demo_state', None)
if not csf:
csf = dict(clicks=0)
session_state['bootstrap_demo_state'] = csf
else:
csf['clicks'] = n_clicks
return "Button has been clicked %s times since the page was rendered" %n_clicks | [
"def",
"session_demo_alert_callback",
"(",
"n_clicks",
",",
"session_state",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"session_state",
"is",
"None",
":",
"raise",
"NotImplementedError",
"(",
"\"Cannot handle a missing session state\"",
")",
"csf",
"=",
... | Output text based on both app state and session state | [
"Output",
"text",
"based",
"on",
"both",
"app",
"state",
"and",
"session",
"state"
] | 773ed081fc2ea3cc7607590322a14686a7a79bc5 | https://github.com/GibbsConsulting/django-plotly-dash/blob/773ed081fc2ea3cc7607590322a14686a7a79bc5/demo/demo/bootstrap_app.py#L69-L79 |
245,663 | GibbsConsulting/django-plotly-dash | django_plotly_dash/dash_wrapper.py | add_usable_app | def add_usable_app(name, app):
'Add app to local registry by name'
name = slugify(name)
global usable_apps # pylint: disable=global-statement
usable_apps[name] = app
return name | python | def add_usable_app(name, app):
'Add app to local registry by name'
name = slugify(name)
global usable_apps # pylint: disable=global-statement
usable_apps[name] = app
return name | [
"def",
"add_usable_app",
"(",
"name",
",",
"app",
")",
":",
"name",
"=",
"slugify",
"(",
"name",
")",
"global",
"usable_apps",
"# pylint: disable=global-statement",
"usable_apps",
"[",
"name",
"]",
"=",
"app",
"return",
"name"
] | Add app to local registry by name | [
"Add",
"app",
"to",
"local",
"registry",
"by",
"name"
] | 773ed081fc2ea3cc7607590322a14686a7a79bc5 | https://github.com/GibbsConsulting/django-plotly-dash/blob/773ed081fc2ea3cc7607590322a14686a7a79bc5/django_plotly_dash/dash_wrapper.py#L49-L54 |
245,664 | GibbsConsulting/django-plotly-dash | django_plotly_dash/dash_wrapper.py | DjangoDash.get_base_pathname | def get_base_pathname(self, specific_identifier, cache_id):
'Base path name of this instance, taking into account any state or statelessness'
if not specific_identifier:
app_pathname = "%s:app-%s"% (app_name, main_view_label)
ndid = self._uid
else:
app_pathname = "%s:%s" % (app_name, main_view_label)
ndid = specific_identifier
kwargs = {'ident': ndid}
if cache_id:
kwargs['cache_id'] = cache_id
app_pathname = app_pathname + "--args"
full_url = reverse(app_pathname, kwargs=kwargs)
if full_url[-1] != '/':
full_url = full_url + '/'
return ndid, full_url | python | def get_base_pathname(self, specific_identifier, cache_id):
'Base path name of this instance, taking into account any state or statelessness'
if not specific_identifier:
app_pathname = "%s:app-%s"% (app_name, main_view_label)
ndid = self._uid
else:
app_pathname = "%s:%s" % (app_name, main_view_label)
ndid = specific_identifier
kwargs = {'ident': ndid}
if cache_id:
kwargs['cache_id'] = cache_id
app_pathname = app_pathname + "--args"
full_url = reverse(app_pathname, kwargs=kwargs)
if full_url[-1] != '/':
full_url = full_url + '/'
return ndid, full_url | [
"def",
"get_base_pathname",
"(",
"self",
",",
"specific_identifier",
",",
"cache_id",
")",
":",
"if",
"not",
"specific_identifier",
":",
"app_pathname",
"=",
"\"%s:app-%s\"",
"%",
"(",
"app_name",
",",
"main_view_label",
")",
"ndid",
"=",
"self",
".",
"_uid",
... | Base path name of this instance, taking into account any state or statelessness | [
"Base",
"path",
"name",
"of",
"this",
"instance",
"taking",
"into",
"account",
"any",
"state",
"or",
"statelessness"
] | 773ed081fc2ea3cc7607590322a14686a7a79bc5 | https://github.com/GibbsConsulting/django-plotly-dash/blob/773ed081fc2ea3cc7607590322a14686a7a79bc5/django_plotly_dash/dash_wrapper.py#L161-L179 |
245,665 | GibbsConsulting/django-plotly-dash | django_plotly_dash/dash_wrapper.py | DjangoDash.do_form_dash_instance | def do_form_dash_instance(self, replacements=None, specific_identifier=None, cache_id=None):
'Perform the act of constructing a Dash instance taking into account state'
ndid, base_pathname = self.get_base_pathname(specific_identifier, cache_id)
return self.form_dash_instance(replacements, ndid, base_pathname) | python | def do_form_dash_instance(self, replacements=None, specific_identifier=None, cache_id=None):
'Perform the act of constructing a Dash instance taking into account state'
ndid, base_pathname = self.get_base_pathname(specific_identifier, cache_id)
return self.form_dash_instance(replacements, ndid, base_pathname) | [
"def",
"do_form_dash_instance",
"(",
"self",
",",
"replacements",
"=",
"None",
",",
"specific_identifier",
"=",
"None",
",",
"cache_id",
"=",
"None",
")",
":",
"ndid",
",",
"base_pathname",
"=",
"self",
".",
"get_base_pathname",
"(",
"specific_identifier",
",",
... | Perform the act of constructing a Dash instance taking into account state | [
"Perform",
"the",
"act",
"of",
"constructing",
"a",
"Dash",
"instance",
"taking",
"into",
"account",
"state"
] | 773ed081fc2ea3cc7607590322a14686a7a79bc5 | https://github.com/GibbsConsulting/django-plotly-dash/blob/773ed081fc2ea3cc7607590322a14686a7a79bc5/django_plotly_dash/dash_wrapper.py#L181-L185 |
245,666 | GibbsConsulting/django-plotly-dash | django_plotly_dash/dash_wrapper.py | DjangoDash.form_dash_instance | def form_dash_instance(self, replacements=None, ndid=None, base_pathname=None):
'Construct a Dash instance taking into account state'
if ndid is None:
ndid = self._uid
rd = WrappedDash(base_pathname=base_pathname,
expanded_callbacks=self._expanded_callbacks,
replacements=replacements,
ndid=ndid,
serve_locally=self._serve_locally)
rd.layout = self.layout
rd.config['suppress_callback_exceptions'] = self._suppress_callback_exceptions
for cb, func in self._callback_sets:
rd.callback(**cb)(func)
for s in self.css.items:
rd.css.append_css(s)
for s in self.scripts.items:
rd.scripts.append_script(s)
return rd | python | def form_dash_instance(self, replacements=None, ndid=None, base_pathname=None):
'Construct a Dash instance taking into account state'
if ndid is None:
ndid = self._uid
rd = WrappedDash(base_pathname=base_pathname,
expanded_callbacks=self._expanded_callbacks,
replacements=replacements,
ndid=ndid,
serve_locally=self._serve_locally)
rd.layout = self.layout
rd.config['suppress_callback_exceptions'] = self._suppress_callback_exceptions
for cb, func in self._callback_sets:
rd.callback(**cb)(func)
for s in self.css.items:
rd.css.append_css(s)
for s in self.scripts.items:
rd.scripts.append_script(s)
return rd | [
"def",
"form_dash_instance",
"(",
"self",
",",
"replacements",
"=",
"None",
",",
"ndid",
"=",
"None",
",",
"base_pathname",
"=",
"None",
")",
":",
"if",
"ndid",
"is",
"None",
":",
"ndid",
"=",
"self",
".",
"_uid",
"rd",
"=",
"WrappedDash",
"(",
"base_p... | Construct a Dash instance taking into account state | [
"Construct",
"a",
"Dash",
"instance",
"taking",
"into",
"account",
"state"
] | 773ed081fc2ea3cc7607590322a14686a7a79bc5 | https://github.com/GibbsConsulting/django-plotly-dash/blob/773ed081fc2ea3cc7607590322a14686a7a79bc5/django_plotly_dash/dash_wrapper.py#L187-L209 |
245,667 | GibbsConsulting/django-plotly-dash | django_plotly_dash/dash_wrapper.py | DjangoDash.callback | def callback(self, output, inputs=None, state=None, events=None):
'Form a callback function by wrapping, in the same way as the underlying Dash application would'
callback_set = {'output':output,
'inputs':inputs and inputs or dict(),
'state':state and state or dict(),
'events':events and events or dict()}
def wrap_func(func, callback_set=callback_set, callback_sets=self._callback_sets): # pylint: disable=dangerous-default-value, missing-docstring
callback_sets.append((callback_set, func))
return func
return wrap_func | python | def callback(self, output, inputs=None, state=None, events=None):
'Form a callback function by wrapping, in the same way as the underlying Dash application would'
callback_set = {'output':output,
'inputs':inputs and inputs or dict(),
'state':state and state or dict(),
'events':events and events or dict()}
def wrap_func(func, callback_set=callback_set, callback_sets=self._callback_sets): # pylint: disable=dangerous-default-value, missing-docstring
callback_sets.append((callback_set, func))
return func
return wrap_func | [
"def",
"callback",
"(",
"self",
",",
"output",
",",
"inputs",
"=",
"None",
",",
"state",
"=",
"None",
",",
"events",
"=",
"None",
")",
":",
"callback_set",
"=",
"{",
"'output'",
":",
"output",
",",
"'inputs'",
":",
"inputs",
"and",
"inputs",
"or",
"d... | Form a callback function by wrapping, in the same way as the underlying Dash application would | [
"Form",
"a",
"callback",
"function",
"by",
"wrapping",
"in",
"the",
"same",
"way",
"as",
"the",
"underlying",
"Dash",
"application",
"would"
] | 773ed081fc2ea3cc7607590322a14686a7a79bc5 | https://github.com/GibbsConsulting/django-plotly-dash/blob/773ed081fc2ea3cc7607590322a14686a7a79bc5/django_plotly_dash/dash_wrapper.py#L211-L220 |
245,668 | GibbsConsulting/django-plotly-dash | django_plotly_dash/dash_wrapper.py | DjangoDash.expanded_callback | def expanded_callback(self, output, inputs=[], state=[], events=[]): # pylint: disable=dangerous-default-value
'''
Form an expanded callback.
This function registers the callback function, and sets an internal flag that mandates that all
callbacks are passed the enhanced arguments.
'''
self._expanded_callbacks = True
return self.callback(output, inputs, state, events) | python | def expanded_callback(self, output, inputs=[], state=[], events=[]): # pylint: disable=dangerous-default-value
'''
Form an expanded callback.
This function registers the callback function, and sets an internal flag that mandates that all
callbacks are passed the enhanced arguments.
'''
self._expanded_callbacks = True
return self.callback(output, inputs, state, events) | [
"def",
"expanded_callback",
"(",
"self",
",",
"output",
",",
"inputs",
"=",
"[",
"]",
",",
"state",
"=",
"[",
"]",
",",
"events",
"=",
"[",
"]",
")",
":",
"# pylint: disable=dangerous-default-value",
"self",
".",
"_expanded_callbacks",
"=",
"True",
"return",... | Form an expanded callback.
This function registers the callback function, and sets an internal flag that mandates that all
callbacks are passed the enhanced arguments. | [
"Form",
"an",
"expanded",
"callback",
"."
] | 773ed081fc2ea3cc7607590322a14686a7a79bc5 | https://github.com/GibbsConsulting/django-plotly-dash/blob/773ed081fc2ea3cc7607590322a14686a7a79bc5/django_plotly_dash/dash_wrapper.py#L222-L230 |
245,669 | GibbsConsulting/django-plotly-dash | django_plotly_dash/dash_wrapper.py | WrappedDash.augment_initial_layout | def augment_initial_layout(self, base_response, initial_arguments=None):
'Add application state to initial values'
if self.use_dash_layout() and not initial_arguments and False:
return base_response.data, base_response.mimetype
# Adjust the base layout response
baseDataInBytes = base_response.data
baseData = json.loads(baseDataInBytes.decode('utf-8'))
# Also add in any initial arguments
if initial_arguments:
if isinstance(initial_arguments, str):
initial_arguments = json.loads(initial_arguments)
# Walk tree. If at any point we have an element whose id
# matches, then replace any named values at this level
reworked_data = self.walk_tree_and_replace(baseData, initial_arguments)
response_data = json.dumps(reworked_data,
cls=PlotlyJSONEncoder)
return response_data, base_response.mimetype | python | def augment_initial_layout(self, base_response, initial_arguments=None):
'Add application state to initial values'
if self.use_dash_layout() and not initial_arguments and False:
return base_response.data, base_response.mimetype
# Adjust the base layout response
baseDataInBytes = base_response.data
baseData = json.loads(baseDataInBytes.decode('utf-8'))
# Also add in any initial arguments
if initial_arguments:
if isinstance(initial_arguments, str):
initial_arguments = json.loads(initial_arguments)
# Walk tree. If at any point we have an element whose id
# matches, then replace any named values at this level
reworked_data = self.walk_tree_and_replace(baseData, initial_arguments)
response_data = json.dumps(reworked_data,
cls=PlotlyJSONEncoder)
return response_data, base_response.mimetype | [
"def",
"augment_initial_layout",
"(",
"self",
",",
"base_response",
",",
"initial_arguments",
"=",
"None",
")",
":",
"if",
"self",
".",
"use_dash_layout",
"(",
")",
"and",
"not",
"initial_arguments",
"and",
"False",
":",
"return",
"base_response",
".",
"data",
... | Add application state to initial values | [
"Add",
"application",
"state",
"to",
"initial",
"values"
] | 773ed081fc2ea3cc7607590322a14686a7a79bc5 | https://github.com/GibbsConsulting/django-plotly-dash/blob/773ed081fc2ea3cc7607590322a14686a7a79bc5/django_plotly_dash/dash_wrapper.py#L312-L333 |
245,670 | GibbsConsulting/django-plotly-dash | django_plotly_dash/dash_wrapper.py | WrappedDash.walk_tree_and_extract | def walk_tree_and_extract(self, data, target):
'Walk tree of properties and extract identifiers and associated values'
if isinstance(data, dict):
for key in ['children', 'props',]:
self.walk_tree_and_extract(data.get(key, None), target)
ident = data.get('id', None)
if ident is not None:
idVals = target.get(ident, {})
for key, value in data.items():
if key not in ['props', 'options', 'children', 'id']:
idVals[key] = value
if idVals:
target[ident] = idVals
if isinstance(data, list):
for element in data:
self.walk_tree_and_extract(element, target) | python | def walk_tree_and_extract(self, data, target):
'Walk tree of properties and extract identifiers and associated values'
if isinstance(data, dict):
for key in ['children', 'props',]:
self.walk_tree_and_extract(data.get(key, None), target)
ident = data.get('id', None)
if ident is not None:
idVals = target.get(ident, {})
for key, value in data.items():
if key not in ['props', 'options', 'children', 'id']:
idVals[key] = value
if idVals:
target[ident] = idVals
if isinstance(data, list):
for element in data:
self.walk_tree_and_extract(element, target) | [
"def",
"walk_tree_and_extract",
"(",
"self",
",",
"data",
",",
"target",
")",
":",
"if",
"isinstance",
"(",
"data",
",",
"dict",
")",
":",
"for",
"key",
"in",
"[",
"'children'",
",",
"'props'",
",",
"]",
":",
"self",
".",
"walk_tree_and_extract",
"(",
... | Walk tree of properties and extract identifiers and associated values | [
"Walk",
"tree",
"of",
"properties",
"and",
"extract",
"identifiers",
"and",
"associated",
"values"
] | 773ed081fc2ea3cc7607590322a14686a7a79bc5 | https://github.com/GibbsConsulting/django-plotly-dash/blob/773ed081fc2ea3cc7607590322a14686a7a79bc5/django_plotly_dash/dash_wrapper.py#L335-L350 |
245,671 | GibbsConsulting/django-plotly-dash | django_plotly_dash/dash_wrapper.py | WrappedDash.walk_tree_and_replace | def walk_tree_and_replace(self, data, overrides):
'''
Walk the tree. Rely on json decoding to insert instances of dict and list
ie we use a dna test for anatine, rather than our eyes and ears...
'''
if isinstance(data, dict):
response = {}
replacements = {}
# look for id entry
thisID = data.get('id', None)
if thisID is not None:
replacements = overrides.get(thisID, None) if overrides else None
if not replacements:
replacements = self._replacements.get(thisID, {})
# walk all keys and replace if needed
for k, v in data.items():
r = replacements.get(k, None)
if r is None:
r = self.walk_tree_and_replace(v, overrides)
response[k] = r
return response
if isinstance(data, list):
# process each entry in turn and return
return [self.walk_tree_and_replace(x, overrides) for x in data]
return data | python | def walk_tree_and_replace(self, data, overrides):
'''
Walk the tree. Rely on json decoding to insert instances of dict and list
ie we use a dna test for anatine, rather than our eyes and ears...
'''
if isinstance(data, dict):
response = {}
replacements = {}
# look for id entry
thisID = data.get('id', None)
if thisID is not None:
replacements = overrides.get(thisID, None) if overrides else None
if not replacements:
replacements = self._replacements.get(thisID, {})
# walk all keys and replace if needed
for k, v in data.items():
r = replacements.get(k, None)
if r is None:
r = self.walk_tree_and_replace(v, overrides)
response[k] = r
return response
if isinstance(data, list):
# process each entry in turn and return
return [self.walk_tree_and_replace(x, overrides) for x in data]
return data | [
"def",
"walk_tree_and_replace",
"(",
"self",
",",
"data",
",",
"overrides",
")",
":",
"if",
"isinstance",
"(",
"data",
",",
"dict",
")",
":",
"response",
"=",
"{",
"}",
"replacements",
"=",
"{",
"}",
"# look for id entry",
"thisID",
"=",
"data",
".",
"ge... | Walk the tree. Rely on json decoding to insert instances of dict and list
ie we use a dna test for anatine, rather than our eyes and ears... | [
"Walk",
"the",
"tree",
".",
"Rely",
"on",
"json",
"decoding",
"to",
"insert",
"instances",
"of",
"dict",
"and",
"list",
"ie",
"we",
"use",
"a",
"dna",
"test",
"for",
"anatine",
"rather",
"than",
"our",
"eyes",
"and",
"ears",
"..."
] | 773ed081fc2ea3cc7607590322a14686a7a79bc5 | https://github.com/GibbsConsulting/django-plotly-dash/blob/773ed081fc2ea3cc7607590322a14686a7a79bc5/django_plotly_dash/dash_wrapper.py#L352-L376 |
245,672 | GibbsConsulting/django-plotly-dash | django_plotly_dash/dash_wrapper.py | WrappedDash.locate_endpoint_function | def locate_endpoint_function(self, name=None):
'Locate endpoint function given name of view'
if name is not None:
ep = "%s_%s" %(self._base_pathname,
name)
else:
ep = self._base_pathname
return self._notflask.endpoints[ep]['view_func'] | python | def locate_endpoint_function(self, name=None):
'Locate endpoint function given name of view'
if name is not None:
ep = "%s_%s" %(self._base_pathname,
name)
else:
ep = self._base_pathname
return self._notflask.endpoints[ep]['view_func'] | [
"def",
"locate_endpoint_function",
"(",
"self",
",",
"name",
"=",
"None",
")",
":",
"if",
"name",
"is",
"not",
"None",
":",
"ep",
"=",
"\"%s_%s\"",
"%",
"(",
"self",
".",
"_base_pathname",
",",
"name",
")",
"else",
":",
"ep",
"=",
"self",
".",
"_base... | Locate endpoint function given name of view | [
"Locate",
"endpoint",
"function",
"given",
"name",
"of",
"view"
] | 773ed081fc2ea3cc7607590322a14686a7a79bc5 | https://github.com/GibbsConsulting/django-plotly-dash/blob/773ed081fc2ea3cc7607590322a14686a7a79bc5/django_plotly_dash/dash_wrapper.py#L396-L403 |
245,673 | GibbsConsulting/django-plotly-dash | django_plotly_dash/dash_wrapper.py | WrappedDash.layout | def layout(self, value):
'Overloaded layout function to fix component names as needed'
if self._adjust_id:
self._fix_component_id(value)
return Dash.layout.fset(self, value) | python | def layout(self, value):
'Overloaded layout function to fix component names as needed'
if self._adjust_id:
self._fix_component_id(value)
return Dash.layout.fset(self, value) | [
"def",
"layout",
"(",
"self",
",",
"value",
")",
":",
"if",
"self",
".",
"_adjust_id",
":",
"self",
".",
"_fix_component_id",
"(",
"value",
")",
"return",
"Dash",
".",
"layout",
".",
"fset",
"(",
"self",
",",
"value",
")"
] | Overloaded layout function to fix component names as needed | [
"Overloaded",
"layout",
"function",
"to",
"fix",
"component",
"names",
"as",
"needed"
] | 773ed081fc2ea3cc7607590322a14686a7a79bc5 | https://github.com/GibbsConsulting/django-plotly-dash/blob/773ed081fc2ea3cc7607590322a14686a7a79bc5/django_plotly_dash/dash_wrapper.py#L407-L412 |
245,674 | GibbsConsulting/django-plotly-dash | django_plotly_dash/dash_wrapper.py | WrappedDash._fix_component_id | def _fix_component_id(self, component):
'Fix name of component ad all of its children'
theID = getattr(component, "id", None)
if theID is not None:
setattr(component, "id", self._fix_id(theID))
try:
for c in component.children:
self._fix_component_id(c)
except: #pylint: disable=bare-except
pass | python | def _fix_component_id(self, component):
'Fix name of component ad all of its children'
theID = getattr(component, "id", None)
if theID is not None:
setattr(component, "id", self._fix_id(theID))
try:
for c in component.children:
self._fix_component_id(c)
except: #pylint: disable=bare-except
pass | [
"def",
"_fix_component_id",
"(",
"self",
",",
"component",
")",
":",
"theID",
"=",
"getattr",
"(",
"component",
",",
"\"id\"",
",",
"None",
")",
"if",
"theID",
"is",
"not",
"None",
":",
"setattr",
"(",
"component",
",",
"\"id\"",
",",
"self",
".",
"_fi... | Fix name of component ad all of its children | [
"Fix",
"name",
"of",
"component",
"ad",
"all",
"of",
"its",
"children"
] | 773ed081fc2ea3cc7607590322a14686a7a79bc5 | https://github.com/GibbsConsulting/django-plotly-dash/blob/773ed081fc2ea3cc7607590322a14686a7a79bc5/django_plotly_dash/dash_wrapper.py#L414-L424 |
245,675 | GibbsConsulting/django-plotly-dash | django_plotly_dash/dash_wrapper.py | WrappedDash._fix_callback_item | def _fix_callback_item(self, item):
'Update component identifier'
item.component_id = self._fix_id(item.component_id)
return item | python | def _fix_callback_item(self, item):
'Update component identifier'
item.component_id = self._fix_id(item.component_id)
return item | [
"def",
"_fix_callback_item",
"(",
"self",
",",
"item",
")",
":",
"item",
".",
"component_id",
"=",
"self",
".",
"_fix_id",
"(",
"item",
".",
"component_id",
")",
"return",
"item"
] | Update component identifier | [
"Update",
"component",
"identifier"
] | 773ed081fc2ea3cc7607590322a14686a7a79bc5 | https://github.com/GibbsConsulting/django-plotly-dash/blob/773ed081fc2ea3cc7607590322a14686a7a79bc5/django_plotly_dash/dash_wrapper.py#L433-L436 |
245,676 | GibbsConsulting/django-plotly-dash | django_plotly_dash/dash_wrapper.py | WrappedDash.callback | def callback(self, output, inputs=[], state=[], events=[]): # pylint: disable=dangerous-default-value
'Invoke callback, adjusting variable names as needed'
if isinstance(output, (list, tuple)):
fixed_outputs = [self._fix_callback_item(x) for x in output]
# Temporary check; can be removed once the library has been extended
raise NotImplementedError("django-plotly-dash cannot handle multiple callback outputs at present")
else:
fixed_outputs = self._fix_callback_item(output)
return super(WrappedDash, self).callback(fixed_outputs,
[self._fix_callback_item(x) for x in inputs],
[self._fix_callback_item(x) for x in state]) | python | def callback(self, output, inputs=[], state=[], events=[]): # pylint: disable=dangerous-default-value
'Invoke callback, adjusting variable names as needed'
if isinstance(output, (list, tuple)):
fixed_outputs = [self._fix_callback_item(x) for x in output]
# Temporary check; can be removed once the library has been extended
raise NotImplementedError("django-plotly-dash cannot handle multiple callback outputs at present")
else:
fixed_outputs = self._fix_callback_item(output)
return super(WrappedDash, self).callback(fixed_outputs,
[self._fix_callback_item(x) for x in inputs],
[self._fix_callback_item(x) for x in state]) | [
"def",
"callback",
"(",
"self",
",",
"output",
",",
"inputs",
"=",
"[",
"]",
",",
"state",
"=",
"[",
"]",
",",
"events",
"=",
"[",
"]",
")",
":",
"# pylint: disable=dangerous-default-value",
"if",
"isinstance",
"(",
"output",
",",
"(",
"list",
",",
"tu... | Invoke callback, adjusting variable names as needed | [
"Invoke",
"callback",
"adjusting",
"variable",
"names",
"as",
"needed"
] | 773ed081fc2ea3cc7607590322a14686a7a79bc5 | https://github.com/GibbsConsulting/django-plotly-dash/blob/773ed081fc2ea3cc7607590322a14686a7a79bc5/django_plotly_dash/dash_wrapper.py#L438-L450 |
245,677 | GibbsConsulting/django-plotly-dash | django_plotly_dash/dash_wrapper.py | WrappedDash.dispatch | def dispatch(self):
'Perform dispatch, using request embedded within flask global state'
import flask
body = flask.request.get_json()
return self. dispatch_with_args(body, argMap=dict()) | python | def dispatch(self):
'Perform dispatch, using request embedded within flask global state'
import flask
body = flask.request.get_json()
return self. dispatch_with_args(body, argMap=dict()) | [
"def",
"dispatch",
"(",
"self",
")",
":",
"import",
"flask",
"body",
"=",
"flask",
".",
"request",
".",
"get_json",
"(",
")",
"return",
"self",
".",
"dispatch_with_args",
"(",
"body",
",",
"argMap",
"=",
"dict",
"(",
")",
")"
] | Perform dispatch, using request embedded within flask global state | [
"Perform",
"dispatch",
"using",
"request",
"embedded",
"within",
"flask",
"global",
"state"
] | 773ed081fc2ea3cc7607590322a14686a7a79bc5 | https://github.com/GibbsConsulting/django-plotly-dash/blob/773ed081fc2ea3cc7607590322a14686a7a79bc5/django_plotly_dash/dash_wrapper.py#L452-L456 |
245,678 | GibbsConsulting/django-plotly-dash | django_plotly_dash/dash_wrapper.py | WrappedDash.dispatch_with_args | def dispatch_with_args(self, body, argMap):
'Perform callback dispatching, with enhanced arguments and recording of response'
inputs = body.get('inputs', [])
state = body.get('state', [])
output = body['output']
try:
output_id = output['id']
output_property = output['property']
target_id = "%s.%s" %(output_id, output_property)
except:
target_id = output
output_id, output_property = output.split(".")
args = []
da = argMap.get('dash_app', None)
for component_registration in self.callback_map[target_id]['inputs']:
for c in inputs:
if c['property'] == component_registration['property'] and c['id'] == component_registration['id']:
v = c.get('value', None)
args.append(v)
if da:
da.update_current_state(c['id'], c['property'], v)
for component_registration in self.callback_map[target_id]['state']:
for c in state:
if c['property'] == component_registration['property'] and c['id'] == component_registration['id']:
v = c.get('value', None)
args.append(v)
if da:
da.update_current_state(c['id'], c['property'], v)
# Special: intercept case of insufficient arguments
# This happens when a propery has been updated with a pipe component
# TODO see if this can be attacked from the client end
if len(args) < len(self.callback_map[target_id]['inputs']):
return 'EDGECASEEXIT'
res = self.callback_map[target_id]['callback'](*args, **argMap)
if da and da.have_current_state_entry(output_id, output_property):
response = json.loads(res.data.decode('utf-8'))
value = response.get('response', {}).get('props', {}).get(output_property, None)
da.update_current_state(output_id, output_property, value)
return res | python | def dispatch_with_args(self, body, argMap):
'Perform callback dispatching, with enhanced arguments and recording of response'
inputs = body.get('inputs', [])
state = body.get('state', [])
output = body['output']
try:
output_id = output['id']
output_property = output['property']
target_id = "%s.%s" %(output_id, output_property)
except:
target_id = output
output_id, output_property = output.split(".")
args = []
da = argMap.get('dash_app', None)
for component_registration in self.callback_map[target_id]['inputs']:
for c in inputs:
if c['property'] == component_registration['property'] and c['id'] == component_registration['id']:
v = c.get('value', None)
args.append(v)
if da:
da.update_current_state(c['id'], c['property'], v)
for component_registration in self.callback_map[target_id]['state']:
for c in state:
if c['property'] == component_registration['property'] and c['id'] == component_registration['id']:
v = c.get('value', None)
args.append(v)
if da:
da.update_current_state(c['id'], c['property'], v)
# Special: intercept case of insufficient arguments
# This happens when a propery has been updated with a pipe component
# TODO see if this can be attacked from the client end
if len(args) < len(self.callback_map[target_id]['inputs']):
return 'EDGECASEEXIT'
res = self.callback_map[target_id]['callback'](*args, **argMap)
if da and da.have_current_state_entry(output_id, output_property):
response = json.loads(res.data.decode('utf-8'))
value = response.get('response', {}).get('props', {}).get(output_property, None)
da.update_current_state(output_id, output_property, value)
return res | [
"def",
"dispatch_with_args",
"(",
"self",
",",
"body",
",",
"argMap",
")",
":",
"inputs",
"=",
"body",
".",
"get",
"(",
"'inputs'",
",",
"[",
"]",
")",
"state",
"=",
"body",
".",
"get",
"(",
"'state'",
",",
"[",
"]",
")",
"output",
"=",
"body",
"... | Perform callback dispatching, with enhanced arguments and recording of response | [
"Perform",
"callback",
"dispatching",
"with",
"enhanced",
"arguments",
"and",
"recording",
"of",
"response"
] | 773ed081fc2ea3cc7607590322a14686a7a79bc5 | https://github.com/GibbsConsulting/django-plotly-dash/blob/773ed081fc2ea3cc7607590322a14686a7a79bc5/django_plotly_dash/dash_wrapper.py#L459-L506 |
245,679 | GibbsConsulting/django-plotly-dash | django_plotly_dash/dash_wrapper.py | WrappedDash.extra_html_properties | def extra_html_properties(self, prefix=None, postfix=None, template_type=None):
'''
Return extra html properties to allow individual apps to be styled separately.
The content returned from this function is injected unescaped into templates.
'''
prefix = prefix if prefix else "django-plotly-dash"
post_part = "-%s" % postfix if postfix else ""
template_type = template_type if template_type else "iframe"
slugified_id = self.slugified_id()
return "%(prefix)s %(prefix)s-%(template_type)s %(prefix)s-app-%(slugified_id)s%(post_part)s" % {'slugified_id':slugified_id,
'post_part':post_part,
'template_type':template_type,
'prefix':prefix,
} | python | def extra_html_properties(self, prefix=None, postfix=None, template_type=None):
'''
Return extra html properties to allow individual apps to be styled separately.
The content returned from this function is injected unescaped into templates.
'''
prefix = prefix if prefix else "django-plotly-dash"
post_part = "-%s" % postfix if postfix else ""
template_type = template_type if template_type else "iframe"
slugified_id = self.slugified_id()
return "%(prefix)s %(prefix)s-%(template_type)s %(prefix)s-app-%(slugified_id)s%(post_part)s" % {'slugified_id':slugified_id,
'post_part':post_part,
'template_type':template_type,
'prefix':prefix,
} | [
"def",
"extra_html_properties",
"(",
"self",
",",
"prefix",
"=",
"None",
",",
"postfix",
"=",
"None",
",",
"template_type",
"=",
"None",
")",
":",
"prefix",
"=",
"prefix",
"if",
"prefix",
"else",
"\"django-plotly-dash\"",
"post_part",
"=",
"\"-%s\"",
"%",
"p... | Return extra html properties to allow individual apps to be styled separately.
The content returned from this function is injected unescaped into templates. | [
"Return",
"extra",
"html",
"properties",
"to",
"allow",
"individual",
"apps",
"to",
"be",
"styled",
"separately",
"."
] | 773ed081fc2ea3cc7607590322a14686a7a79bc5 | https://github.com/GibbsConsulting/django-plotly-dash/blob/773ed081fc2ea3cc7607590322a14686a7a79bc5/django_plotly_dash/dash_wrapper.py#L513-L531 |
245,680 | GibbsConsulting/django-plotly-dash | django_plotly_dash/templatetags/plotly_dash.py | plotly_direct | def plotly_direct(context, name=None, slug=None, da=None):
'Direct insertion of a Dash app'
da, app = _locate_daapp(name, slug, da)
view_func = app.locate_endpoint_function()
# Load embedded holder inserted by middleware
eh = context.request.dpd_content_handler.embedded_holder
app.set_embedded(eh)
try:
resp = view_func()
finally:
app.exit_embedded()
return locals() | python | def plotly_direct(context, name=None, slug=None, da=None):
'Direct insertion of a Dash app'
da, app = _locate_daapp(name, slug, da)
view_func = app.locate_endpoint_function()
# Load embedded holder inserted by middleware
eh = context.request.dpd_content_handler.embedded_holder
app.set_embedded(eh)
try:
resp = view_func()
finally:
app.exit_embedded()
return locals() | [
"def",
"plotly_direct",
"(",
"context",
",",
"name",
"=",
"None",
",",
"slug",
"=",
"None",
",",
"da",
"=",
"None",
")",
":",
"da",
",",
"app",
"=",
"_locate_daapp",
"(",
"name",
",",
"slug",
",",
"da",
")",
"view_func",
"=",
"app",
".",
"locate_en... | Direct insertion of a Dash app | [
"Direct",
"insertion",
"of",
"a",
"Dash",
"app"
] | 773ed081fc2ea3cc7607590322a14686a7a79bc5 | https://github.com/GibbsConsulting/django-plotly-dash/blob/773ed081fc2ea3cc7607590322a14686a7a79bc5/django_plotly_dash/templatetags/plotly_dash.py#L91-L106 |
245,681 | GibbsConsulting/django-plotly-dash | django_plotly_dash/templatetags/plotly_dash.py | plotly_app_identifier | def plotly_app_identifier(name=None, slug=None, da=None, postfix=None):
'Return a slug-friendly identifier'
da, app = _locate_daapp(name, slug, da)
slugified_id = app.slugified_id()
if postfix:
return "%s-%s" %(slugified_id, postfix)
return slugified_id | python | def plotly_app_identifier(name=None, slug=None, da=None, postfix=None):
'Return a slug-friendly identifier'
da, app = _locate_daapp(name, slug, da)
slugified_id = app.slugified_id()
if postfix:
return "%s-%s" %(slugified_id, postfix)
return slugified_id | [
"def",
"plotly_app_identifier",
"(",
"name",
"=",
"None",
",",
"slug",
"=",
"None",
",",
"da",
"=",
"None",
",",
"postfix",
"=",
"None",
")",
":",
"da",
",",
"app",
"=",
"_locate_daapp",
"(",
"name",
",",
"slug",
",",
"da",
")",
"slugified_id",
"=",
... | Return a slug-friendly identifier | [
"Return",
"a",
"slug",
"-",
"friendly",
"identifier"
] | 773ed081fc2ea3cc7607590322a14686a7a79bc5 | https://github.com/GibbsConsulting/django-plotly-dash/blob/773ed081fc2ea3cc7607590322a14686a7a79bc5/django_plotly_dash/templatetags/plotly_dash.py#L115-L124 |
245,682 | GibbsConsulting/django-plotly-dash | django_plotly_dash/templatetags/plotly_dash.py | plotly_class | def plotly_class(name=None, slug=None, da=None, prefix=None, postfix=None, template_type=None):
'Return a string of space-separated class names'
da, app = _locate_daapp(name, slug, da)
return app.extra_html_properties(prefix=prefix,
postfix=postfix,
template_type=template_type) | python | def plotly_class(name=None, slug=None, da=None, prefix=None, postfix=None, template_type=None):
'Return a string of space-separated class names'
da, app = _locate_daapp(name, slug, da)
return app.extra_html_properties(prefix=prefix,
postfix=postfix,
template_type=template_type) | [
"def",
"plotly_class",
"(",
"name",
"=",
"None",
",",
"slug",
"=",
"None",
",",
"da",
"=",
"None",
",",
"prefix",
"=",
"None",
",",
"postfix",
"=",
"None",
",",
"template_type",
"=",
"None",
")",
":",
"da",
",",
"app",
"=",
"_locate_daapp",
"(",
"n... | Return a string of space-separated class names | [
"Return",
"a",
"string",
"of",
"space",
"-",
"separated",
"class",
"names"
] | 773ed081fc2ea3cc7607590322a14686a7a79bc5 | https://github.com/GibbsConsulting/django-plotly-dash/blob/773ed081fc2ea3cc7607590322a14686a7a79bc5/django_plotly_dash/templatetags/plotly_dash.py#L127-L134 |
245,683 | atztogo/spglib | database/make_Wyckoff_db.py | parse_wyckoff_csv | def parse_wyckoff_csv(wyckoff_file):
"""Parse Wyckoff.csv
There are 530 data sets. For one example:
9:C 1 2 1:::::::
::4:c:1:(x,y,z):(-x,y,-z)::
::2:b:2:(0,y,1/2):::
::2:a:2:(0,y,0):::
"""
rowdata = []
points = []
hP_nums = [433, 436, 444, 450, 452, 458, 460]
for i, line in enumerate(wyckoff_file):
if line.strip() == 'end of data':
break
rowdata.append(line.strip().split(':'))
# 2:P -1 ::::::: <-- store line number if first element is number
if rowdata[-1][0].isdigit():
points.append(i)
points.append(i)
wyckoff = []
for i in range(len(points) - 1): # 0 to 529
symbol = rowdata[points[i]][1] # e.g. "C 1 2 1"
if i + 1 in hP_nums:
symbol = symbol.replace('R', 'H', 1)
wyckoff.append({'symbol': symbol.strip()})
# When the number of positions is larger than 4,
# the positions are written in the next line.
# So those positions are connected.
for i in range(len(points) - 1):
count = 0
wyckoff[i]['wyckoff'] = []
for j in range(points[i] + 1, points[i + 1]):
# Hook if the third element is a number (multiplicity), e.g.,
#
# 232:P 2/b 2/m 2/b::::::: <- ignored
# ::8:r:1:(x,y,z):(-x,y,-z):(x,-y+1/2,-z):(-x,-y+1/2,z)
# :::::(-x,-y,-z):(x,-y,z):(-x,y+1/2,z):(x,y+1/2,-z) <- ignored
# ::4:q:..m:(x,0,z):(-x,0,-z):(x,1/2,-z):(-x,1/2,z)
# ::4:p:..2:(0,y,1/2):(0,-y+1/2,1/2):(0,-y,1/2):(0,y+1/2,1/2)
# ::4:o:..2:(1/2,y,0):(1/2,-y+1/2,0):(1/2,-y,0):(1/2,y+1/2,0)
# ...
if rowdata[j][2].isdigit():
pos = []
w = {'letter': rowdata[j][3].strip(),
'multiplicity': int(rowdata[j][2]),
'site_symmetry': rowdata[j][4].strip(),
'positions': pos}
wyckoff[i]['wyckoff'].append(w)
for k in range(4):
if rowdata[j][k + 5]: # check if '(x,y,z)' or ''
count += 1
pos.append(rowdata[j][k + 5])
else:
for k in range(4):
if rowdata[j][k + 5]:
count += 1
pos.append(rowdata[j][k + 5])
# assertion
for w in wyckoff[i]['wyckoff']:
n_pos = len(w['positions'])
n_pos *= len(lattice_symbols[wyckoff[i]['symbol'][0]])
assert n_pos == w['multiplicity']
return wyckoff | python | def parse_wyckoff_csv(wyckoff_file):
rowdata = []
points = []
hP_nums = [433, 436, 444, 450, 452, 458, 460]
for i, line in enumerate(wyckoff_file):
if line.strip() == 'end of data':
break
rowdata.append(line.strip().split(':'))
# 2:P -1 ::::::: <-- store line number if first element is number
if rowdata[-1][0].isdigit():
points.append(i)
points.append(i)
wyckoff = []
for i in range(len(points) - 1): # 0 to 529
symbol = rowdata[points[i]][1] # e.g. "C 1 2 1"
if i + 1 in hP_nums:
symbol = symbol.replace('R', 'H', 1)
wyckoff.append({'symbol': symbol.strip()})
# When the number of positions is larger than 4,
# the positions are written in the next line.
# So those positions are connected.
for i in range(len(points) - 1):
count = 0
wyckoff[i]['wyckoff'] = []
for j in range(points[i] + 1, points[i + 1]):
# Hook if the third element is a number (multiplicity), e.g.,
#
# 232:P 2/b 2/m 2/b::::::: <- ignored
# ::8:r:1:(x,y,z):(-x,y,-z):(x,-y+1/2,-z):(-x,-y+1/2,z)
# :::::(-x,-y,-z):(x,-y,z):(-x,y+1/2,z):(x,y+1/2,-z) <- ignored
# ::4:q:..m:(x,0,z):(-x,0,-z):(x,1/2,-z):(-x,1/2,z)
# ::4:p:..2:(0,y,1/2):(0,-y+1/2,1/2):(0,-y,1/2):(0,y+1/2,1/2)
# ::4:o:..2:(1/2,y,0):(1/2,-y+1/2,0):(1/2,-y,0):(1/2,y+1/2,0)
# ...
if rowdata[j][2].isdigit():
pos = []
w = {'letter': rowdata[j][3].strip(),
'multiplicity': int(rowdata[j][2]),
'site_symmetry': rowdata[j][4].strip(),
'positions': pos}
wyckoff[i]['wyckoff'].append(w)
for k in range(4):
if rowdata[j][k + 5]: # check if '(x,y,z)' or ''
count += 1
pos.append(rowdata[j][k + 5])
else:
for k in range(4):
if rowdata[j][k + 5]:
count += 1
pos.append(rowdata[j][k + 5])
# assertion
for w in wyckoff[i]['wyckoff']:
n_pos = len(w['positions'])
n_pos *= len(lattice_symbols[wyckoff[i]['symbol'][0]])
assert n_pos == w['multiplicity']
return wyckoff | [
"def",
"parse_wyckoff_csv",
"(",
"wyckoff_file",
")",
":",
"rowdata",
"=",
"[",
"]",
"points",
"=",
"[",
"]",
"hP_nums",
"=",
"[",
"433",
",",
"436",
",",
"444",
",",
"450",
",",
"452",
",",
"458",
",",
"460",
"]",
"for",
"i",
",",
"line",
"in",
... | Parse Wyckoff.csv
There are 530 data sets. For one example:
9:C 1 2 1:::::::
::4:c:1:(x,y,z):(-x,y,-z)::
::2:b:2:(0,y,1/2):::
::2:a:2:(0,y,0)::: | [
"Parse",
"Wyckoff",
".",
"csv"
] | e10a8f24e6e3bc1adfd8c511073442c0e7fc67b6 | https://github.com/atztogo/spglib/blob/e10a8f24e6e3bc1adfd8c511073442c0e7fc67b6/database/make_Wyckoff_db.py#L179-L251 |
245,684 | atztogo/spglib | database/make_Wyckoff_db.py | get_site_symmetries | def get_site_symmetries(wyckoff):
"""List up site symmetries
The data structure is as follows:
wyckoff[0]['wyckoff'][0]['site_symmetry']
Note
----
Maximum length of string is 6.
"""
ssyms = []
for w in wyckoff:
ssyms += ["\"%-6s\"" % w_s['site_symmetry'] for w_s in w['wyckoff']]
damp_array_site_symmetries(ssyms) | python | def get_site_symmetries(wyckoff):
ssyms = []
for w in wyckoff:
ssyms += ["\"%-6s\"" % w_s['site_symmetry'] for w_s in w['wyckoff']]
damp_array_site_symmetries(ssyms) | [
"def",
"get_site_symmetries",
"(",
"wyckoff",
")",
":",
"ssyms",
"=",
"[",
"]",
"for",
"w",
"in",
"wyckoff",
":",
"ssyms",
"+=",
"[",
"\"\\\"%-6s\\\"\"",
"%",
"w_s",
"[",
"'site_symmetry'",
"]",
"for",
"w_s",
"in",
"w",
"[",
"'wyckoff'",
"]",
"]",
"dam... | List up site symmetries
The data structure is as follows:
wyckoff[0]['wyckoff'][0]['site_symmetry']
Note
----
Maximum length of string is 6. | [
"List",
"up",
"site",
"symmetries"
] | e10a8f24e6e3bc1adfd8c511073442c0e7fc67b6 | https://github.com/atztogo/spglib/blob/e10a8f24e6e3bc1adfd8c511073442c0e7fc67b6/database/make_Wyckoff_db.py#L280-L297 |
245,685 | tortoise/tortoise-orm | tortoise/contrib/pylint/__init__.py | transform_model | def transform_model(cls) -> None:
"""
Anything that uses the ModelMeta needs _meta and id.
Also keep track of relationships and make them in the related model class.
"""
if cls.name != "Model":
appname = "models"
for mcls in cls.get_children():
if isinstance(mcls, ClassDef):
for attr in mcls.get_children():
if isinstance(attr, Assign):
if attr.targets[0].name == "app":
appname = attr.value.value
mname = "{}.{}".format(appname, cls.name)
MODELS[mname] = cls
for relname, relval in FUTURE_RELATIONS.get(mname, []):
cls.locals[relname] = relval
for attr in cls.get_children():
if isinstance(attr, Assign):
try:
attrname = attr.value.func.attrname
except AttributeError:
pass
else:
if attrname in ["ForeignKeyField", "ManyToManyField"]:
tomodel = attr.value.args[0].value
relname = ""
if attr.value.keywords:
for keyword in attr.value.keywords:
if keyword.arg == "related_name":
relname = keyword.value.value
if not relname:
relname = cls.name.lower() + "s"
# Injected model attributes need to also have the relation manager
if attrname == "ManyToManyField":
relval = [
attr.value.func,
MANAGER.ast_from_module_name("tortoise.fields").lookup(
"ManyToManyRelationManager"
)[1][0],
]
else:
relval = [
attr.value.func,
MANAGER.ast_from_module_name("tortoise.fields").lookup(
"RelationQueryContainer"
)[1][0],
]
if tomodel in MODELS:
MODELS[tomodel].locals[relname] = relval
else:
FUTURE_RELATIONS.setdefault(tomodel, []).append((relname, relval))
cls.locals["_meta"] = [
MANAGER.ast_from_module_name("tortoise.models").lookup("MetaInfo")[1][0].instantiate_class()
]
if "id" not in cls.locals:
cls.locals["id"] = [nodes.ClassDef("id", None)] | python | def transform_model(cls) -> None:
if cls.name != "Model":
appname = "models"
for mcls in cls.get_children():
if isinstance(mcls, ClassDef):
for attr in mcls.get_children():
if isinstance(attr, Assign):
if attr.targets[0].name == "app":
appname = attr.value.value
mname = "{}.{}".format(appname, cls.name)
MODELS[mname] = cls
for relname, relval in FUTURE_RELATIONS.get(mname, []):
cls.locals[relname] = relval
for attr in cls.get_children():
if isinstance(attr, Assign):
try:
attrname = attr.value.func.attrname
except AttributeError:
pass
else:
if attrname in ["ForeignKeyField", "ManyToManyField"]:
tomodel = attr.value.args[0].value
relname = ""
if attr.value.keywords:
for keyword in attr.value.keywords:
if keyword.arg == "related_name":
relname = keyword.value.value
if not relname:
relname = cls.name.lower() + "s"
# Injected model attributes need to also have the relation manager
if attrname == "ManyToManyField":
relval = [
attr.value.func,
MANAGER.ast_from_module_name("tortoise.fields").lookup(
"ManyToManyRelationManager"
)[1][0],
]
else:
relval = [
attr.value.func,
MANAGER.ast_from_module_name("tortoise.fields").lookup(
"RelationQueryContainer"
)[1][0],
]
if tomodel in MODELS:
MODELS[tomodel].locals[relname] = relval
else:
FUTURE_RELATIONS.setdefault(tomodel, []).append((relname, relval))
cls.locals["_meta"] = [
MANAGER.ast_from_module_name("tortoise.models").lookup("MetaInfo")[1][0].instantiate_class()
]
if "id" not in cls.locals:
cls.locals["id"] = [nodes.ClassDef("id", None)] | [
"def",
"transform_model",
"(",
"cls",
")",
"->",
"None",
":",
"if",
"cls",
".",
"name",
"!=",
"\"Model\"",
":",
"appname",
"=",
"\"models\"",
"for",
"mcls",
"in",
"cls",
".",
"get_children",
"(",
")",
":",
"if",
"isinstance",
"(",
"mcls",
",",
"ClassDe... | Anything that uses the ModelMeta needs _meta and id.
Also keep track of relationships and make them in the related model class. | [
"Anything",
"that",
"uses",
"the",
"ModelMeta",
"needs",
"_meta",
"and",
"id",
".",
"Also",
"keep",
"track",
"of",
"relationships",
"and",
"make",
"them",
"in",
"the",
"related",
"model",
"class",
"."
] | 7d16457731905e19d4d06ccd5b4ea16d4a9447b2 | https://github.com/tortoise/tortoise-orm/blob/7d16457731905e19d4d06ccd5b4ea16d4a9447b2/tortoise/contrib/pylint/__init__.py#L32-L95 |
245,686 | tortoise/tortoise-orm | tortoise/contrib/pylint/__init__.py | apply_type_shim | def apply_type_shim(cls, _context=None) -> Iterator:
"""
Morphs model fields to representative type
"""
if cls.name in ["IntField", "SmallIntField"]:
base_nodes = scoped_nodes.builtin_lookup("int")
elif cls.name in ["CharField", "TextField"]:
base_nodes = scoped_nodes.builtin_lookup("str")
elif cls.name == "BooleanField":
base_nodes = scoped_nodes.builtin_lookup("bool")
elif cls.name == "FloatField":
base_nodes = scoped_nodes.builtin_lookup("float")
elif cls.name == "DecimalField":
base_nodes = MANAGER.ast_from_module_name("decimal").lookup("Decimal")
elif cls.name == "DatetimeField":
base_nodes = MANAGER.ast_from_module_name("datetime").lookup("datetime")
elif cls.name == "DateField":
base_nodes = MANAGER.ast_from_module_name("datetime").lookup("date")
elif cls.name == "ForeignKeyField":
base_nodes = MANAGER.ast_from_module_name("tortoise.fields").lookup("BackwardFKRelation")
elif cls.name == "ManyToManyField":
base_nodes = MANAGER.ast_from_module_name("tortoise.fields").lookup(
"ManyToManyRelationManager"
)
else:
return iter([cls])
return iter([cls] + base_nodes[1]) | python | def apply_type_shim(cls, _context=None) -> Iterator:
if cls.name in ["IntField", "SmallIntField"]:
base_nodes = scoped_nodes.builtin_lookup("int")
elif cls.name in ["CharField", "TextField"]:
base_nodes = scoped_nodes.builtin_lookup("str")
elif cls.name == "BooleanField":
base_nodes = scoped_nodes.builtin_lookup("bool")
elif cls.name == "FloatField":
base_nodes = scoped_nodes.builtin_lookup("float")
elif cls.name == "DecimalField":
base_nodes = MANAGER.ast_from_module_name("decimal").lookup("Decimal")
elif cls.name == "DatetimeField":
base_nodes = MANAGER.ast_from_module_name("datetime").lookup("datetime")
elif cls.name == "DateField":
base_nodes = MANAGER.ast_from_module_name("datetime").lookup("date")
elif cls.name == "ForeignKeyField":
base_nodes = MANAGER.ast_from_module_name("tortoise.fields").lookup("BackwardFKRelation")
elif cls.name == "ManyToManyField":
base_nodes = MANAGER.ast_from_module_name("tortoise.fields").lookup(
"ManyToManyRelationManager"
)
else:
return iter([cls])
return iter([cls] + base_nodes[1]) | [
"def",
"apply_type_shim",
"(",
"cls",
",",
"_context",
"=",
"None",
")",
"->",
"Iterator",
":",
"if",
"cls",
".",
"name",
"in",
"[",
"\"IntField\"",
",",
"\"SmallIntField\"",
"]",
":",
"base_nodes",
"=",
"scoped_nodes",
".",
"builtin_lookup",
"(",
"\"int\"",... | Morphs model fields to representative type | [
"Morphs",
"model",
"fields",
"to",
"representative",
"type"
] | 7d16457731905e19d4d06ccd5b4ea16d4a9447b2 | https://github.com/tortoise/tortoise-orm/blob/7d16457731905e19d4d06ccd5b4ea16d4a9447b2/tortoise/contrib/pylint/__init__.py#L105-L132 |
245,687 | tortoise/tortoise-orm | tortoise/filters.py | list_encoder | def list_encoder(values, instance, field: Field):
"""Encodes an iterable of a given field into a database-compatible format."""
return [field.to_db_value(element, instance) for element in values] | python | def list_encoder(values, instance, field: Field):
return [field.to_db_value(element, instance) for element in values] | [
"def",
"list_encoder",
"(",
"values",
",",
"instance",
",",
"field",
":",
"Field",
")",
":",
"return",
"[",
"field",
".",
"to_db_value",
"(",
"element",
",",
"instance",
")",
"for",
"element",
"in",
"values",
"]"
] | Encodes an iterable of a given field into a database-compatible format. | [
"Encodes",
"an",
"iterable",
"of",
"a",
"given",
"field",
"into",
"a",
"database",
"-",
"compatible",
"format",
"."
] | 7d16457731905e19d4d06ccd5b4ea16d4a9447b2 | https://github.com/tortoise/tortoise-orm/blob/7d16457731905e19d4d06ccd5b4ea16d4a9447b2/tortoise/filters.py#L11-L13 |
245,688 | tortoise/tortoise-orm | tortoise/fields.py | ManyToManyRelationManager.add | async def add(self, *instances, using_db=None) -> None:
"""
Adds one or more of ``instances`` to the relation.
If it is already added, it will be silently ignored.
"""
if not instances:
return
if self.instance.id is None:
raise OperationalError(
"You should first call .save() on {model}".format(model=self.instance)
)
db = using_db if using_db else self.model._meta.db
through_table = Table(self.field.through)
select_query = (
db.query_class.from_(through_table)
.where(getattr(through_table, self.field.backward_key) == self.instance.id)
.select(self.field.backward_key, self.field.forward_key)
)
query = db.query_class.into(through_table).columns(
getattr(through_table, self.field.forward_key),
getattr(through_table, self.field.backward_key),
)
if len(instances) == 1:
criterion = getattr(through_table, self.field.forward_key) == instances[0].id
else:
criterion = getattr(through_table, self.field.forward_key).isin(
[i.id for i in instances]
)
select_query = select_query.where(criterion)
already_existing_relations_raw = await db.execute_query(str(select_query))
already_existing_relations = {
(r[self.field.backward_key], r[self.field.forward_key])
for r in already_existing_relations_raw
}
insert_is_required = False
for instance_to_add in instances:
if instance_to_add.id is None:
raise OperationalError(
"You should first call .save() on {model}".format(model=instance_to_add)
)
if (self.instance.id, instance_to_add.id) in already_existing_relations:
continue
query = query.insert(instance_to_add.id, self.instance.id)
insert_is_required = True
if insert_is_required:
await db.execute_query(str(query)) | python | async def add(self, *instances, using_db=None) -> None:
if not instances:
return
if self.instance.id is None:
raise OperationalError(
"You should first call .save() on {model}".format(model=self.instance)
)
db = using_db if using_db else self.model._meta.db
through_table = Table(self.field.through)
select_query = (
db.query_class.from_(through_table)
.where(getattr(through_table, self.field.backward_key) == self.instance.id)
.select(self.field.backward_key, self.field.forward_key)
)
query = db.query_class.into(through_table).columns(
getattr(through_table, self.field.forward_key),
getattr(through_table, self.field.backward_key),
)
if len(instances) == 1:
criterion = getattr(through_table, self.field.forward_key) == instances[0].id
else:
criterion = getattr(through_table, self.field.forward_key).isin(
[i.id for i in instances]
)
select_query = select_query.where(criterion)
already_existing_relations_raw = await db.execute_query(str(select_query))
already_existing_relations = {
(r[self.field.backward_key], r[self.field.forward_key])
for r in already_existing_relations_raw
}
insert_is_required = False
for instance_to_add in instances:
if instance_to_add.id is None:
raise OperationalError(
"You should first call .save() on {model}".format(model=instance_to_add)
)
if (self.instance.id, instance_to_add.id) in already_existing_relations:
continue
query = query.insert(instance_to_add.id, self.instance.id)
insert_is_required = True
if insert_is_required:
await db.execute_query(str(query)) | [
"async",
"def",
"add",
"(",
"self",
",",
"*",
"instances",
",",
"using_db",
"=",
"None",
")",
"->",
"None",
":",
"if",
"not",
"instances",
":",
"return",
"if",
"self",
".",
"instance",
".",
"id",
"is",
"None",
":",
"raise",
"OperationalError",
"(",
"... | Adds one or more of ``instances`` to the relation.
If it is already added, it will be silently ignored. | [
"Adds",
"one",
"or",
"more",
"of",
"instances",
"to",
"the",
"relation",
"."
] | 7d16457731905e19d4d06ccd5b4ea16d4a9447b2 | https://github.com/tortoise/tortoise-orm/blob/7d16457731905e19d4d06ccd5b4ea16d4a9447b2/tortoise/fields.py#L539-L589 |
245,689 | tortoise/tortoise-orm | tortoise/fields.py | ManyToManyRelationManager.clear | async def clear(self, using_db=None) -> None:
"""
Clears ALL relations.
"""
db = using_db if using_db else self.model._meta.db
through_table = Table(self.field.through)
query = (
db.query_class.from_(through_table)
.where(getattr(through_table, self.field.backward_key) == self.instance.id)
.delete()
)
await db.execute_query(str(query)) | python | async def clear(self, using_db=None) -> None:
db = using_db if using_db else self.model._meta.db
through_table = Table(self.field.through)
query = (
db.query_class.from_(through_table)
.where(getattr(through_table, self.field.backward_key) == self.instance.id)
.delete()
)
await db.execute_query(str(query)) | [
"async",
"def",
"clear",
"(",
"self",
",",
"using_db",
"=",
"None",
")",
"->",
"None",
":",
"db",
"=",
"using_db",
"if",
"using_db",
"else",
"self",
".",
"model",
".",
"_meta",
".",
"db",
"through_table",
"=",
"Table",
"(",
"self",
".",
"field",
".",... | Clears ALL relations. | [
"Clears",
"ALL",
"relations",
"."
] | 7d16457731905e19d4d06ccd5b4ea16d4a9447b2 | https://github.com/tortoise/tortoise-orm/blob/7d16457731905e19d4d06ccd5b4ea16d4a9447b2/tortoise/fields.py#L591-L602 |
245,690 | tortoise/tortoise-orm | tortoise/fields.py | ManyToManyRelationManager.remove | async def remove(self, *instances, using_db=None) -> None:
"""
Removes one or more of ``instances`` from the relation.
"""
db = using_db if using_db else self.model._meta.db
if not instances:
raise OperationalError("remove() called on no instances")
through_table = Table(self.field.through)
if len(instances) == 1:
condition = (getattr(through_table, self.field.forward_key) == instances[0].id) & (
getattr(through_table, self.field.backward_key) == self.instance.id
)
else:
condition = (getattr(through_table, self.field.backward_key) == self.instance.id) & (
getattr(through_table, self.field.forward_key).isin([i.id for i in instances])
)
query = db.query_class.from_(through_table).where(condition).delete()
await db.execute_query(str(query)) | python | async def remove(self, *instances, using_db=None) -> None:
db = using_db if using_db else self.model._meta.db
if not instances:
raise OperationalError("remove() called on no instances")
through_table = Table(self.field.through)
if len(instances) == 1:
condition = (getattr(through_table, self.field.forward_key) == instances[0].id) & (
getattr(through_table, self.field.backward_key) == self.instance.id
)
else:
condition = (getattr(through_table, self.field.backward_key) == self.instance.id) & (
getattr(through_table, self.field.forward_key).isin([i.id for i in instances])
)
query = db.query_class.from_(through_table).where(condition).delete()
await db.execute_query(str(query)) | [
"async",
"def",
"remove",
"(",
"self",
",",
"*",
"instances",
",",
"using_db",
"=",
"None",
")",
"->",
"None",
":",
"db",
"=",
"using_db",
"if",
"using_db",
"else",
"self",
".",
"model",
".",
"_meta",
".",
"db",
"if",
"not",
"instances",
":",
"raise"... | Removes one or more of ``instances`` from the relation. | [
"Removes",
"one",
"or",
"more",
"of",
"instances",
"from",
"the",
"relation",
"."
] | 7d16457731905e19d4d06ccd5b4ea16d4a9447b2 | https://github.com/tortoise/tortoise-orm/blob/7d16457731905e19d4d06ccd5b4ea16d4a9447b2/tortoise/fields.py#L604-L622 |
245,691 | tortoise/tortoise-orm | tortoise/contrib/quart/__init__.py | register_tortoise | def register_tortoise(
app: Quart,
config: Optional[dict] = None,
config_file: Optional[str] = None,
db_url: Optional[str] = None,
modules: Optional[Dict[str, List[str]]] = None,
generate_schemas: bool = False,
) -> None:
"""
Registers ``before_serving`` and ``after_serving`` hooks to set-up and tear-down Tortoise-ORM
inside a Quart service.
It also registers a CLI command ``generate_schemas`` that will generate the schemas.
You can configure using only one of ``config``, ``config_file``
and ``(db_url, modules)``.
Parameters
----------
app:
Quart app.
config:
Dict containing config:
Example
-------
.. code-block:: python3
{
'connections': {
# Dict format for connection
'default': {
'engine': 'tortoise.backends.asyncpg',
'credentials': {
'host': 'localhost',
'port': '5432',
'user': 'tortoise',
'password': 'qwerty123',
'database': 'test',
}
},
# Using a DB_URL string
'default': 'postgres://postgres:@qwerty123localhost:5432/events'
},
'apps': {
'models': {
'models': ['__main__'],
# If no default_connection specified, defaults to 'default'
'default_connection': 'default',
}
}
}
config_file:
Path to .json or .yml (if PyYAML installed) file containing config with
same format as above.
db_url:
Use a DB_URL string. See :ref:`db_url`
modules:
Dictionary of ``key``: [``list_of_modules``] that defined "apps" and modules that
should be discovered for models.
generate_schemas:
True to generate schema immediately. Only useful for dev environments
or SQLite ``:memory:`` databases
"""
@app.before_serving
async def init_orm():
await Tortoise.init(config=config, config_file=config_file, db_url=db_url, modules=modules)
print("Tortoise-ORM started, {}, {}".format(Tortoise._connections, Tortoise.apps))
if generate_schemas:
print("Tortoise-ORM generating schema")
await Tortoise.generate_schemas()
@app.after_serving
async def close_orm():
await Tortoise.close_connections()
print("Tortoise-ORM shutdown")
@app.cli.command() # type: ignore
def generate_schemas(): # pylint: disable=E0102
"""Populate DB with Tortoise-ORM schemas."""
async def inner():
await Tortoise.init(
config=config, config_file=config_file, db_url=db_url, modules=modules
)
await Tortoise.generate_schemas()
await Tortoise.close_connections()
logging.basicConfig(level=logging.DEBUG)
loop = asyncio.get_event_loop()
loop.run_until_complete(inner()) | python | def register_tortoise(
app: Quart,
config: Optional[dict] = None,
config_file: Optional[str] = None,
db_url: Optional[str] = None,
modules: Optional[Dict[str, List[str]]] = None,
generate_schemas: bool = False,
) -> None:
@app.before_serving
async def init_orm():
await Tortoise.init(config=config, config_file=config_file, db_url=db_url, modules=modules)
print("Tortoise-ORM started, {}, {}".format(Tortoise._connections, Tortoise.apps))
if generate_schemas:
print("Tortoise-ORM generating schema")
await Tortoise.generate_schemas()
@app.after_serving
async def close_orm():
await Tortoise.close_connections()
print("Tortoise-ORM shutdown")
@app.cli.command() # type: ignore
def generate_schemas(): # pylint: disable=E0102
"""Populate DB with Tortoise-ORM schemas."""
async def inner():
await Tortoise.init(
config=config, config_file=config_file, db_url=db_url, modules=modules
)
await Tortoise.generate_schemas()
await Tortoise.close_connections()
logging.basicConfig(level=logging.DEBUG)
loop = asyncio.get_event_loop()
loop.run_until_complete(inner()) | [
"def",
"register_tortoise",
"(",
"app",
":",
"Quart",
",",
"config",
":",
"Optional",
"[",
"dict",
"]",
"=",
"None",
",",
"config_file",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
",",
"db_url",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
",",... | Registers ``before_serving`` and ``after_serving`` hooks to set-up and tear-down Tortoise-ORM
inside a Quart service.
It also registers a CLI command ``generate_schemas`` that will generate the schemas.
You can configure using only one of ``config``, ``config_file``
and ``(db_url, modules)``.
Parameters
----------
app:
Quart app.
config:
Dict containing config:
Example
-------
.. code-block:: python3
{
'connections': {
# Dict format for connection
'default': {
'engine': 'tortoise.backends.asyncpg',
'credentials': {
'host': 'localhost',
'port': '5432',
'user': 'tortoise',
'password': 'qwerty123',
'database': 'test',
}
},
# Using a DB_URL string
'default': 'postgres://postgres:@qwerty123localhost:5432/events'
},
'apps': {
'models': {
'models': ['__main__'],
# If no default_connection specified, defaults to 'default'
'default_connection': 'default',
}
}
}
config_file:
Path to .json or .yml (if PyYAML installed) file containing config with
same format as above.
db_url:
Use a DB_URL string. See :ref:`db_url`
modules:
Dictionary of ``key``: [``list_of_modules``] that defined "apps" and modules that
should be discovered for models.
generate_schemas:
True to generate schema immediately. Only useful for dev environments
or SQLite ``:memory:`` databases | [
"Registers",
"before_serving",
"and",
"after_serving",
"hooks",
"to",
"set",
"-",
"up",
"and",
"tear",
"-",
"down",
"Tortoise",
"-",
"ORM",
"inside",
"a",
"Quart",
"service",
".",
"It",
"also",
"registers",
"a",
"CLI",
"command",
"generate_schemas",
"that",
... | 7d16457731905e19d4d06ccd5b4ea16d4a9447b2 | https://github.com/tortoise/tortoise-orm/blob/7d16457731905e19d4d06ccd5b4ea16d4a9447b2/tortoise/contrib/quart/__init__.py#L13-L105 |
245,692 | tortoise/tortoise-orm | tortoise/__init__.py | run_async | def run_async(coro: Coroutine) -> None:
"""
Simple async runner that cleans up DB connections on exit.
This is meant for simple scripts.
Usage::
from tortoise import Tortoise, run_async
async def do_stuff():
await Tortoise.init(
db_url='sqlite://db.sqlite3',
models={'models': ['app.models']}
)
...
run_async(do_stuff())
"""
loop = asyncio.get_event_loop()
try:
loop.run_until_complete(coro)
finally:
loop.run_until_complete(Tortoise.close_connections()) | python | def run_async(coro: Coroutine) -> None:
loop = asyncio.get_event_loop()
try:
loop.run_until_complete(coro)
finally:
loop.run_until_complete(Tortoise.close_connections()) | [
"def",
"run_async",
"(",
"coro",
":",
"Coroutine",
")",
"->",
"None",
":",
"loop",
"=",
"asyncio",
".",
"get_event_loop",
"(",
")",
"try",
":",
"loop",
".",
"run_until_complete",
"(",
"coro",
")",
"finally",
":",
"loop",
".",
"run_until_complete",
"(",
"... | Simple async runner that cleans up DB connections on exit.
This is meant for simple scripts.
Usage::
from tortoise import Tortoise, run_async
async def do_stuff():
await Tortoise.init(
db_url='sqlite://db.sqlite3',
models={'models': ['app.models']}
)
...
run_async(do_stuff()) | [
"Simple",
"async",
"runner",
"that",
"cleans",
"up",
"DB",
"connections",
"on",
"exit",
".",
"This",
"is",
"meant",
"for",
"simple",
"scripts",
"."
] | 7d16457731905e19d4d06ccd5b4ea16d4a9447b2 | https://github.com/tortoise/tortoise-orm/blob/7d16457731905e19d4d06ccd5b4ea16d4a9447b2/tortoise/__init__.py#L381-L404 |
245,693 | tortoise/tortoise-orm | tortoise/__init__.py | Tortoise.init | async def init(
cls,
config: Optional[dict] = None,
config_file: Optional[str] = None,
_create_db: bool = False,
db_url: Optional[str] = None,
modules: Optional[Dict[str, List[str]]] = None,
) -> None:
"""
Sets up Tortoise-ORM.
You can configure using only one of ``config``, ``config_file``
and ``(db_url, modules)``.
Parameters
----------
config:
Dict containing config:
Example
-------
.. code-block:: python3
{
'connections': {
# Dict format for connection
'default': {
'engine': 'tortoise.backends.asyncpg',
'credentials': {
'host': 'localhost',
'port': '5432',
'user': 'tortoise',
'password': 'qwerty123',
'database': 'test',
}
},
# Using a DB_URL string
'default': 'postgres://postgres:@qwerty123localhost:5432/events'
},
'apps': {
'models': {
'models': ['__main__'],
# If no default_connection specified, defaults to 'default'
'default_connection': 'default',
}
}
}
config_file:
Path to .json or .yml (if PyYAML installed) file containing config with
same format as above.
db_url:
Use a DB_URL string. See :ref:`db_url`
modules:
Dictionary of ``key``: [``list_of_modules``] that defined "apps" and modules that
should be discovered for models.
_create_db:
If ``True`` tries to create database for specified connections,
could be used for testing purposes.
Raises
------
ConfigurationError
For any configuration error
"""
if cls._inited:
await cls.close_connections()
await cls._reset_apps()
if int(bool(config) + bool(config_file) + bool(db_url)) != 1:
raise ConfigurationError(
'You should init either from "config", "config_file" or "db_url"'
)
if config_file:
config = cls._get_config_from_config_file(config_file)
if db_url:
if not modules:
raise ConfigurationError('You must specify "db_url" and "modules" together')
config = generate_config(db_url, modules)
try:
connections_config = config["connections"] # type: ignore
except KeyError:
raise ConfigurationError('Config must define "connections" section')
try:
apps_config = config["apps"] # type: ignore
except KeyError:
raise ConfigurationError('Config must define "apps" section')
logger.info(
"Tortoise-ORM startup\n connections: %s\n apps: %s",
str(connections_config),
str(apps_config),
)
await cls._init_connections(connections_config, _create_db)
cls._init_apps(apps_config)
cls._inited = True | python | async def init(
cls,
config: Optional[dict] = None,
config_file: Optional[str] = None,
_create_db: bool = False,
db_url: Optional[str] = None,
modules: Optional[Dict[str, List[str]]] = None,
) -> None:
if cls._inited:
await cls.close_connections()
await cls._reset_apps()
if int(bool(config) + bool(config_file) + bool(db_url)) != 1:
raise ConfigurationError(
'You should init either from "config", "config_file" or "db_url"'
)
if config_file:
config = cls._get_config_from_config_file(config_file)
if db_url:
if not modules:
raise ConfigurationError('You must specify "db_url" and "modules" together')
config = generate_config(db_url, modules)
try:
connections_config = config["connections"] # type: ignore
except KeyError:
raise ConfigurationError('Config must define "connections" section')
try:
apps_config = config["apps"] # type: ignore
except KeyError:
raise ConfigurationError('Config must define "apps" section')
logger.info(
"Tortoise-ORM startup\n connections: %s\n apps: %s",
str(connections_config),
str(apps_config),
)
await cls._init_connections(connections_config, _create_db)
cls._init_apps(apps_config)
cls._inited = True | [
"async",
"def",
"init",
"(",
"cls",
",",
"config",
":",
"Optional",
"[",
"dict",
"]",
"=",
"None",
",",
"config_file",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
",",
"_create_db",
":",
"bool",
"=",
"False",
",",
"db_url",
":",
"Optional",
"[",
... | Sets up Tortoise-ORM.
You can configure using only one of ``config``, ``config_file``
and ``(db_url, modules)``.
Parameters
----------
config:
Dict containing config:
Example
-------
.. code-block:: python3
{
'connections': {
# Dict format for connection
'default': {
'engine': 'tortoise.backends.asyncpg',
'credentials': {
'host': 'localhost',
'port': '5432',
'user': 'tortoise',
'password': 'qwerty123',
'database': 'test',
}
},
# Using a DB_URL string
'default': 'postgres://postgres:@qwerty123localhost:5432/events'
},
'apps': {
'models': {
'models': ['__main__'],
# If no default_connection specified, defaults to 'default'
'default_connection': 'default',
}
}
}
config_file:
Path to .json or .yml (if PyYAML installed) file containing config with
same format as above.
db_url:
Use a DB_URL string. See :ref:`db_url`
modules:
Dictionary of ``key``: [``list_of_modules``] that defined "apps" and modules that
should be discovered for models.
_create_db:
If ``True`` tries to create database for specified connections,
could be used for testing purposes.
Raises
------
ConfigurationError
For any configuration error | [
"Sets",
"up",
"Tortoise",
"-",
"ORM",
"."
] | 7d16457731905e19d4d06ccd5b4ea16d4a9447b2 | https://github.com/tortoise/tortoise-orm/blob/7d16457731905e19d4d06ccd5b4ea16d4a9447b2/tortoise/__init__.py#L231-L332 |
245,694 | tortoise/tortoise-orm | tortoise/transactions.py | in_transaction | def in_transaction(connection_name: Optional[str] = None) -> BaseTransactionWrapper:
"""
Transaction context manager.
You can run your code inside ``async with in_transaction():`` statement to run it
into one transaction. If error occurs transaction will rollback.
:param connection_name: name of connection to run with, optional if you have only
one db connection
"""
connection = _get_connection(connection_name)
return connection._in_transaction() | python | def in_transaction(connection_name: Optional[str] = None) -> BaseTransactionWrapper:
connection = _get_connection(connection_name)
return connection._in_transaction() | [
"def",
"in_transaction",
"(",
"connection_name",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
")",
"->",
"BaseTransactionWrapper",
":",
"connection",
"=",
"_get_connection",
"(",
"connection_name",
")",
"return",
"connection",
".",
"_in_transaction",
"(",
")"
] | Transaction context manager.
You can run your code inside ``async with in_transaction():`` statement to run it
into one transaction. If error occurs transaction will rollback.
:param connection_name: name of connection to run with, optional if you have only
one db connection | [
"Transaction",
"context",
"manager",
"."
] | 7d16457731905e19d4d06ccd5b4ea16d4a9447b2 | https://github.com/tortoise/tortoise-orm/blob/7d16457731905e19d4d06ccd5b4ea16d4a9447b2/tortoise/transactions.py#L25-L36 |
245,695 | tortoise/tortoise-orm | tortoise/transactions.py | atomic | def atomic(connection_name: Optional[str] = None) -> Callable:
"""
Transaction decorator.
You can wrap your function with this decorator to run it into one transaction.
If error occurs transaction will rollback.
:param connection_name: name of connection to run with, optional if you have only
one db connection
"""
def wrapper(func):
@wraps(func)
async def wrapped(*args, **kwargs):
connection = _get_connection(connection_name)
async with connection._in_transaction():
return await func(*args, **kwargs)
return wrapped
return wrapper | python | def atomic(connection_name: Optional[str] = None) -> Callable:
def wrapper(func):
@wraps(func)
async def wrapped(*args, **kwargs):
connection = _get_connection(connection_name)
async with connection._in_transaction():
return await func(*args, **kwargs)
return wrapped
return wrapper | [
"def",
"atomic",
"(",
"connection_name",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
")",
"->",
"Callable",
":",
"def",
"wrapper",
"(",
"func",
")",
":",
"@",
"wraps",
"(",
"func",
")",
"async",
"def",
"wrapped",
"(",
"*",
"args",
",",
"*",
"*",... | Transaction decorator.
You can wrap your function with this decorator to run it into one transaction.
If error occurs transaction will rollback.
:param connection_name: name of connection to run with, optional if you have only
one db connection | [
"Transaction",
"decorator",
"."
] | 7d16457731905e19d4d06ccd5b4ea16d4a9447b2 | https://github.com/tortoise/tortoise-orm/blob/7d16457731905e19d4d06ccd5b4ea16d4a9447b2/tortoise/transactions.py#L39-L59 |
245,696 | tortoise/tortoise-orm | tortoise/transactions.py | start_transaction | async def start_transaction(connection_name: Optional[str] = None) -> BaseTransactionWrapper:
"""
Function to manually control your transaction.
Returns transaction object with ``.rollback()`` and ``.commit()`` methods.
All db calls in same coroutine context will run into transaction
before ending transaction with above methods.
:param connection_name: name of connection to run with, optional if you have only
one db connection
"""
connection = _get_connection(connection_name)
transaction = connection._in_transaction()
await transaction.start()
return transaction | python | async def start_transaction(connection_name: Optional[str] = None) -> BaseTransactionWrapper:
connection = _get_connection(connection_name)
transaction = connection._in_transaction()
await transaction.start()
return transaction | [
"async",
"def",
"start_transaction",
"(",
"connection_name",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
")",
"->",
"BaseTransactionWrapper",
":",
"connection",
"=",
"_get_connection",
"(",
"connection_name",
")",
"transaction",
"=",
"connection",
".",
"_in_tra... | Function to manually control your transaction.
Returns transaction object with ``.rollback()`` and ``.commit()`` methods.
All db calls in same coroutine context will run into transaction
before ending transaction with above methods.
:param connection_name: name of connection to run with, optional if you have only
one db connection | [
"Function",
"to",
"manually",
"control",
"your",
"transaction",
"."
] | 7d16457731905e19d4d06ccd5b4ea16d4a9447b2 | https://github.com/tortoise/tortoise-orm/blob/7d16457731905e19d4d06ccd5b4ea16d4a9447b2/tortoise/transactions.py#L62-L76 |
245,697 | tortoise/tortoise-orm | tortoise/queryset.py | QuerySet.limit | def limit(self, limit: int) -> "QuerySet":
"""
Limits QuerySet to given length.
"""
queryset = self._clone()
queryset._limit = limit
return queryset | python | def limit(self, limit: int) -> "QuerySet":
queryset = self._clone()
queryset._limit = limit
return queryset | [
"def",
"limit",
"(",
"self",
",",
"limit",
":",
"int",
")",
"->",
"\"QuerySet\"",
":",
"queryset",
"=",
"self",
".",
"_clone",
"(",
")",
"queryset",
".",
"_limit",
"=",
"limit",
"return",
"queryset"
] | Limits QuerySet to given length. | [
"Limits",
"QuerySet",
"to",
"given",
"length",
"."
] | 7d16457731905e19d4d06ccd5b4ea16d4a9447b2 | https://github.com/tortoise/tortoise-orm/blob/7d16457731905e19d4d06ccd5b4ea16d4a9447b2/tortoise/queryset.py#L218-L224 |
245,698 | tortoise/tortoise-orm | tortoise/queryset.py | QuerySet.offset | def offset(self, offset: int) -> "QuerySet":
"""
Query offset for QuerySet.
"""
queryset = self._clone()
queryset._offset = offset
if self.capabilities.requires_limit and queryset._limit is None:
queryset._limit = 1000000
return queryset | python | def offset(self, offset: int) -> "QuerySet":
queryset = self._clone()
queryset._offset = offset
if self.capabilities.requires_limit and queryset._limit is None:
queryset._limit = 1000000
return queryset | [
"def",
"offset",
"(",
"self",
",",
"offset",
":",
"int",
")",
"->",
"\"QuerySet\"",
":",
"queryset",
"=",
"self",
".",
"_clone",
"(",
")",
"queryset",
".",
"_offset",
"=",
"offset",
"if",
"self",
".",
"capabilities",
".",
"requires_limit",
"and",
"querys... | Query offset for QuerySet. | [
"Query",
"offset",
"for",
"QuerySet",
"."
] | 7d16457731905e19d4d06ccd5b4ea16d4a9447b2 | https://github.com/tortoise/tortoise-orm/blob/7d16457731905e19d4d06ccd5b4ea16d4a9447b2/tortoise/queryset.py#L226-L234 |
245,699 | tortoise/tortoise-orm | tortoise/queryset.py | QuerySet.annotate | def annotate(self, **kwargs) -> "QuerySet":
"""
Annotate result with aggregation result.
"""
queryset = self._clone()
for key, aggregation in kwargs.items():
if not isinstance(aggregation, Aggregate):
raise TypeError("value is expected to be Aggregate instance")
queryset._annotations[key] = aggregation
from tortoise.models import get_filters_for_field
queryset._custom_filters.update(get_filters_for_field(key, None, key))
return queryset | python | def annotate(self, **kwargs) -> "QuerySet":
queryset = self._clone()
for key, aggregation in kwargs.items():
if not isinstance(aggregation, Aggregate):
raise TypeError("value is expected to be Aggregate instance")
queryset._annotations[key] = aggregation
from tortoise.models import get_filters_for_field
queryset._custom_filters.update(get_filters_for_field(key, None, key))
return queryset | [
"def",
"annotate",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
"->",
"\"QuerySet\"",
":",
"queryset",
"=",
"self",
".",
"_clone",
"(",
")",
"for",
"key",
",",
"aggregation",
"in",
"kwargs",
".",
"items",
"(",
")",
":",
"if",
"not",
"isinstance",
"(",
... | Annotate result with aggregation result. | [
"Annotate",
"result",
"with",
"aggregation",
"result",
"."
] | 7d16457731905e19d4d06ccd5b4ea16d4a9447b2 | https://github.com/tortoise/tortoise-orm/blob/7d16457731905e19d4d06ccd5b4ea16d4a9447b2/tortoise/queryset.py#L244-L256 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.