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 75 19.8k | code_tokens listlengths 20 707 | docstring stringlengths 3 17.3k | docstring_tokens listlengths 3 222 | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1 value | idx int64 0 252k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
bmuller/kademlia | kademlia/node.py | NodeHeap.push | def push(self, nodes):
"""
Push nodes onto heap.
@param nodes: This can be a single item or a C{list}.
"""
if not isinstance(nodes, list):
nodes = [nodes]
for node in nodes:
if node not in self:
distance = self.node.distance_to(node)
heapq.heappush(self.heap, (distance, node)) | python | def push(self, nodes):
"""
Push nodes onto heap.
@param nodes: This can be a single item or a C{list}.
"""
if not isinstance(nodes, list):
nodes = [nodes]
for node in nodes:
if node not in self:
distance = self.node.distance_to(node)
heapq.heappush(self.heap, (distance, node)) | [
"def",
"push",
"(",
"self",
",",
"nodes",
")",
":",
"if",
"not",
"isinstance",
"(",
"nodes",
",",
"list",
")",
":",
"nodes",
"=",
"[",
"nodes",
"]",
"for",
"node",
"in",
"nodes",
":",
"if",
"node",
"not",
"in",
"self",
":",
"distance",
"=",
"self... | Push nodes onto heap.
@param nodes: This can be a single item or a C{list}. | [
"Push",
"nodes",
"onto",
"heap",
"."
] | 4a8d445c9ee8f3ca10f56107e4445daed4933c8a | https://github.com/bmuller/kademlia/blob/4a8d445c9ee8f3ca10f56107e4445daed4933c8a/kademlia/node.py#L85-L97 | train | 226,500 |
bmuller/kademlia | kademlia/utils.py | shared_prefix | def shared_prefix(args):
"""
Find the shared prefix between the strings.
For instance:
sharedPrefix(['blahblah', 'blahwhat'])
returns 'blah'.
"""
i = 0
while i < min(map(len, args)):
if len(set(map(operator.itemgetter(i), args))) != 1:
break
i += 1
return args[0][:i] | python | def shared_prefix(args):
"""
Find the shared prefix between the strings.
For instance:
sharedPrefix(['blahblah', 'blahwhat'])
returns 'blah'.
"""
i = 0
while i < min(map(len, args)):
if len(set(map(operator.itemgetter(i), args))) != 1:
break
i += 1
return args[0][:i] | [
"def",
"shared_prefix",
"(",
"args",
")",
":",
"i",
"=",
"0",
"while",
"i",
"<",
"min",
"(",
"map",
"(",
"len",
",",
"args",
")",
")",
":",
"if",
"len",
"(",
"set",
"(",
"map",
"(",
"operator",
".",
"itemgetter",
"(",
"i",
")",
",",
"args",
"... | Find the shared prefix between the strings.
For instance:
sharedPrefix(['blahblah', 'blahwhat'])
returns 'blah'. | [
"Find",
"the",
"shared",
"prefix",
"between",
"the",
"strings",
"."
] | 4a8d445c9ee8f3ca10f56107e4445daed4933c8a | https://github.com/bmuller/kademlia/blob/4a8d445c9ee8f3ca10f56107e4445daed4933c8a/kademlia/utils.py#L21-L36 | train | 226,501 |
bmuller/kademlia | kademlia/protocol.py | KademliaProtocol.get_refresh_ids | def get_refresh_ids(self):
"""
Get ids to search for to keep old buckets up to date.
"""
ids = []
for bucket in self.router.lonely_buckets():
rid = random.randint(*bucket.range).to_bytes(20, byteorder='big')
ids.append(rid)
return ids | python | def get_refresh_ids(self):
"""
Get ids to search for to keep old buckets up to date.
"""
ids = []
for bucket in self.router.lonely_buckets():
rid = random.randint(*bucket.range).to_bytes(20, byteorder='big')
ids.append(rid)
return ids | [
"def",
"get_refresh_ids",
"(",
"self",
")",
":",
"ids",
"=",
"[",
"]",
"for",
"bucket",
"in",
"self",
".",
"router",
".",
"lonely_buckets",
"(",
")",
":",
"rid",
"=",
"random",
".",
"randint",
"(",
"*",
"bucket",
".",
"range",
")",
".",
"to_bytes",
... | Get ids to search for to keep old buckets up to date. | [
"Get",
"ids",
"to",
"search",
"for",
"to",
"keep",
"old",
"buckets",
"up",
"to",
"date",
"."
] | 4a8d445c9ee8f3ca10f56107e4445daed4933c8a | https://github.com/bmuller/kademlia/blob/4a8d445c9ee8f3ca10f56107e4445daed4933c8a/kademlia/protocol.py#L21-L29 | train | 226,502 |
bmuller/kademlia | kademlia/protocol.py | KademliaProtocol.handle_call_response | def handle_call_response(self, result, node):
"""
If we get a response, add the node to the routing table. If
we get no response, make sure it's removed from the routing table.
"""
if not result[0]:
log.warning("no response from %s, removing from router", node)
self.router.remove_contact(node)
return result
log.info("got successful response from %s", node)
self.welcome_if_new(node)
return result | python | def handle_call_response(self, result, node):
"""
If we get a response, add the node to the routing table. If
we get no response, make sure it's removed from the routing table.
"""
if not result[0]:
log.warning("no response from %s, removing from router", node)
self.router.remove_contact(node)
return result
log.info("got successful response from %s", node)
self.welcome_if_new(node)
return result | [
"def",
"handle_call_response",
"(",
"self",
",",
"result",
",",
"node",
")",
":",
"if",
"not",
"result",
"[",
"0",
"]",
":",
"log",
".",
"warning",
"(",
"\"no response from %s, removing from router\"",
",",
"node",
")",
"self",
".",
"router",
".",
"remove_co... | If we get a response, add the node to the routing table. If
we get no response, make sure it's removed from the routing table. | [
"If",
"we",
"get",
"a",
"response",
"add",
"the",
"node",
"to",
"the",
"routing",
"table",
".",
"If",
"we",
"get",
"no",
"response",
"make",
"sure",
"it",
"s",
"removed",
"from",
"the",
"routing",
"table",
"."
] | 4a8d445c9ee8f3ca10f56107e4445daed4933c8a | https://github.com/bmuller/kademlia/blob/4a8d445c9ee8f3ca10f56107e4445daed4933c8a/kademlia/protocol.py#L116-L128 | train | 226,503 |
adafruit/Adafruit_CircuitPython_NeoPixel | neopixel.py | NeoPixel.deinit | def deinit(self):
"""Blank out the NeoPixels and release the pin."""
for i in range(len(self.buf)):
self.buf[i] = 0
neopixel_write(self.pin, self.buf)
self.pin.deinit() | python | def deinit(self):
"""Blank out the NeoPixels and release the pin."""
for i in range(len(self.buf)):
self.buf[i] = 0
neopixel_write(self.pin, self.buf)
self.pin.deinit() | [
"def",
"deinit",
"(",
"self",
")",
":",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"self",
".",
"buf",
")",
")",
":",
"self",
".",
"buf",
"[",
"i",
"]",
"=",
"0",
"neopixel_write",
"(",
"self",
".",
"pin",
",",
"self",
".",
"buf",
")",
"self... | Blank out the NeoPixels and release the pin. | [
"Blank",
"out",
"the",
"NeoPixels",
"and",
"release",
"the",
"pin",
"."
] | c0ed34813a608b64ed044826553918ddbad12f0c | https://github.com/adafruit/Adafruit_CircuitPython_NeoPixel/blob/c0ed34813a608b64ed044826553918ddbad12f0c/neopixel.py#L107-L112 | train | 226,504 |
adafruit/Adafruit_CircuitPython_NeoPixel | neopixel.py | NeoPixel.show | def show(self):
"""Shows the new colors on the pixels themselves if they haven't already
been autowritten.
The colors may or may not be showing after this function returns because
it may be done asynchronously."""
if self.brightness > 0.99:
neopixel_write(self.pin, self.buf)
else:
neopixel_write(self.pin, bytearray([int(i * self.brightness) for i in self.buf])) | python | def show(self):
"""Shows the new colors on the pixels themselves if they haven't already
been autowritten.
The colors may or may not be showing after this function returns because
it may be done asynchronously."""
if self.brightness > 0.99:
neopixel_write(self.pin, self.buf)
else:
neopixel_write(self.pin, bytearray([int(i * self.brightness) for i in self.buf])) | [
"def",
"show",
"(",
"self",
")",
":",
"if",
"self",
".",
"brightness",
">",
"0.99",
":",
"neopixel_write",
"(",
"self",
".",
"pin",
",",
"self",
".",
"buf",
")",
"else",
":",
"neopixel_write",
"(",
"self",
".",
"pin",
",",
"bytearray",
"(",
"[",
"i... | Shows the new colors on the pixels themselves if they haven't already
been autowritten.
The colors may or may not be showing after this function returns because
it may be done asynchronously. | [
"Shows",
"the",
"new",
"colors",
"on",
"the",
"pixels",
"themselves",
"if",
"they",
"haven",
"t",
"already",
"been",
"autowritten",
"."
] | c0ed34813a608b64ed044826553918ddbad12f0c | https://github.com/adafruit/Adafruit_CircuitPython_NeoPixel/blob/c0ed34813a608b64ed044826553918ddbad12f0c/neopixel.py#L223-L232 | train | 226,505 |
dask/dask-kubernetes | dask_kubernetes/objects.py | _set_k8s_attribute | def _set_k8s_attribute(obj, attribute, value):
"""
Set a specific value on a kubernetes object's attribute
obj
an object from Kubernetes Python API client
attribute
Should be a Kubernetes API style attribute (with camelCase)
value
Can be anything (string, list, dict, k8s objects) that can be
accepted by the k8s python client
"""
current_value = None
attribute_name = None
# All k8s python client objects have an 'attribute_map' property
# which has as keys python style attribute names (api_client)
# and as values the kubernetes JSON API style attribute names
# (apiClient). We want to allow users to use the JSON API style attribute
# names only.
for python_attribute, json_attribute in obj.attribute_map.items():
if json_attribute == attribute:
attribute_name = python_attribute
break
else:
raise ValueError('Attribute must be one of {}'.format(obj.attribute_map.values()))
if hasattr(obj, attribute_name):
current_value = getattr(obj, attribute_name)
if current_value is not None:
# This will ensure that current_value is something JSONable,
# so a dict, list, or scalar
current_value = SERIALIZATION_API_CLIENT.sanitize_for_serialization(
current_value
)
if isinstance(current_value, dict):
# Deep merge our dictionaries!
setattr(obj, attribute_name, merge_dictionaries(current_value, value))
elif isinstance(current_value, list):
# Just append lists
setattr(obj, attribute_name, current_value + value)
else:
# Replace everything else
setattr(obj, attribute_name, value) | python | def _set_k8s_attribute(obj, attribute, value):
"""
Set a specific value on a kubernetes object's attribute
obj
an object from Kubernetes Python API client
attribute
Should be a Kubernetes API style attribute (with camelCase)
value
Can be anything (string, list, dict, k8s objects) that can be
accepted by the k8s python client
"""
current_value = None
attribute_name = None
# All k8s python client objects have an 'attribute_map' property
# which has as keys python style attribute names (api_client)
# and as values the kubernetes JSON API style attribute names
# (apiClient). We want to allow users to use the JSON API style attribute
# names only.
for python_attribute, json_attribute in obj.attribute_map.items():
if json_attribute == attribute:
attribute_name = python_attribute
break
else:
raise ValueError('Attribute must be one of {}'.format(obj.attribute_map.values()))
if hasattr(obj, attribute_name):
current_value = getattr(obj, attribute_name)
if current_value is not None:
# This will ensure that current_value is something JSONable,
# so a dict, list, or scalar
current_value = SERIALIZATION_API_CLIENT.sanitize_for_serialization(
current_value
)
if isinstance(current_value, dict):
# Deep merge our dictionaries!
setattr(obj, attribute_name, merge_dictionaries(current_value, value))
elif isinstance(current_value, list):
# Just append lists
setattr(obj, attribute_name, current_value + value)
else:
# Replace everything else
setattr(obj, attribute_name, value) | [
"def",
"_set_k8s_attribute",
"(",
"obj",
",",
"attribute",
",",
"value",
")",
":",
"current_value",
"=",
"None",
"attribute_name",
"=",
"None",
"# All k8s python client objects have an 'attribute_map' property",
"# which has as keys python style attribute names (api_client)",
"# ... | Set a specific value on a kubernetes object's attribute
obj
an object from Kubernetes Python API client
attribute
Should be a Kubernetes API style attribute (with camelCase)
value
Can be anything (string, list, dict, k8s objects) that can be
accepted by the k8s python client | [
"Set",
"a",
"specific",
"value",
"on",
"a",
"kubernetes",
"object",
"s",
"attribute"
] | 8a4883ecd902460b446bb1f43ed97efe398a135e | https://github.com/dask/dask-kubernetes/blob/8a4883ecd902460b446bb1f43ed97efe398a135e/dask_kubernetes/objects.py#L20-L64 | train | 226,506 |
dask/dask-kubernetes | dask_kubernetes/objects.py | merge_dictionaries | def merge_dictionaries(a, b, path=None, update=True):
"""
Merge two dictionaries recursively.
From https://stackoverflow.com/a/25270947
"""
if path is None:
path = []
for key in b:
if key in a:
if isinstance(a[key], dict) and isinstance(b[key], dict):
merge_dictionaries(a[key], b[key], path + [str(key)])
elif a[key] == b[key]:
pass # same leaf value
elif isinstance(a[key], list) and isinstance(b[key], list):
for idx, val in enumerate(b[key]):
a[key][idx] = merge_dictionaries(a[key][idx],
b[key][idx],
path + [str(key), str(idx)],
update=update)
elif update:
a[key] = b[key]
else:
raise Exception('Conflict at %s' % '.'.join(path + [str(key)]))
else:
a[key] = b[key]
return a | python | def merge_dictionaries(a, b, path=None, update=True):
"""
Merge two dictionaries recursively.
From https://stackoverflow.com/a/25270947
"""
if path is None:
path = []
for key in b:
if key in a:
if isinstance(a[key], dict) and isinstance(b[key], dict):
merge_dictionaries(a[key], b[key], path + [str(key)])
elif a[key] == b[key]:
pass # same leaf value
elif isinstance(a[key], list) and isinstance(b[key], list):
for idx, val in enumerate(b[key]):
a[key][idx] = merge_dictionaries(a[key][idx],
b[key][idx],
path + [str(key), str(idx)],
update=update)
elif update:
a[key] = b[key]
else:
raise Exception('Conflict at %s' % '.'.join(path + [str(key)]))
else:
a[key] = b[key]
return a | [
"def",
"merge_dictionaries",
"(",
"a",
",",
"b",
",",
"path",
"=",
"None",
",",
"update",
"=",
"True",
")",
":",
"if",
"path",
"is",
"None",
":",
"path",
"=",
"[",
"]",
"for",
"key",
"in",
"b",
":",
"if",
"key",
"in",
"a",
":",
"if",
"isinstanc... | Merge two dictionaries recursively.
From https://stackoverflow.com/a/25270947 | [
"Merge",
"two",
"dictionaries",
"recursively",
"."
] | 8a4883ecd902460b446bb1f43ed97efe398a135e | https://github.com/dask/dask-kubernetes/blob/8a4883ecd902460b446bb1f43ed97efe398a135e/dask_kubernetes/objects.py#L67-L93 | train | 226,507 |
dask/dask-kubernetes | dask_kubernetes/objects.py | make_pod_spec | def make_pod_spec(
image,
labels={},
threads_per_worker=1,
env={},
extra_container_config={},
extra_pod_config={},
memory_limit=None,
memory_request=None,
cpu_limit=None,
cpu_request=None,
):
"""
Create generic pod template from input parameters
Examples
--------
>>> make_pod_spec(image='daskdev/dask:latest', memory_limit='4G', memory_request='4G')
"""
args = [
'dask-worker',
'$(DASK_SCHEDULER_ADDRESS)',
'--nthreads', str(threads_per_worker),
'--death-timeout', '60',
]
if memory_limit:
args.extend(['--memory-limit', str(memory_limit)])
pod = client.V1Pod(
metadata=client.V1ObjectMeta(
labels=labels
),
spec=client.V1PodSpec(
restart_policy='Never',
containers=[
client.V1Container(
name='dask-worker',
image=image,
args=args,
env=[client.V1EnvVar(name=k, value=v)
for k, v in env.items()],
)
],
tolerations=[
client.V1Toleration(
key='k8s.dask.org/dedicated',
operator='Equal',
value='worker',
effect='NoSchedule',
),
# GKE currently does not permit creating taints on a node pool
# with a `/` in the key field
client.V1Toleration(
key='k8s.dask.org_dedicated',
operator='Equal',
value='worker',
effect='NoSchedule',
),
]
)
)
resources = client.V1ResourceRequirements(limits={}, requests={})
if cpu_request:
resources.requests['cpu'] = cpu_request
if memory_request:
resources.requests['memory'] = memory_request
if cpu_limit:
resources.limits['cpu'] = cpu_limit
if memory_limit:
resources.limits['memory'] = memory_limit
pod.spec.containers[0].resources = resources
for key, value in extra_container_config.items():
_set_k8s_attribute(
pod.spec.containers[0],
key,
value
)
for key, value in extra_pod_config.items():
_set_k8s_attribute(
pod.spec,
key,
value
)
return pod | python | def make_pod_spec(
image,
labels={},
threads_per_worker=1,
env={},
extra_container_config={},
extra_pod_config={},
memory_limit=None,
memory_request=None,
cpu_limit=None,
cpu_request=None,
):
"""
Create generic pod template from input parameters
Examples
--------
>>> make_pod_spec(image='daskdev/dask:latest', memory_limit='4G', memory_request='4G')
"""
args = [
'dask-worker',
'$(DASK_SCHEDULER_ADDRESS)',
'--nthreads', str(threads_per_worker),
'--death-timeout', '60',
]
if memory_limit:
args.extend(['--memory-limit', str(memory_limit)])
pod = client.V1Pod(
metadata=client.V1ObjectMeta(
labels=labels
),
spec=client.V1PodSpec(
restart_policy='Never',
containers=[
client.V1Container(
name='dask-worker',
image=image,
args=args,
env=[client.V1EnvVar(name=k, value=v)
for k, v in env.items()],
)
],
tolerations=[
client.V1Toleration(
key='k8s.dask.org/dedicated',
operator='Equal',
value='worker',
effect='NoSchedule',
),
# GKE currently does not permit creating taints on a node pool
# with a `/` in the key field
client.V1Toleration(
key='k8s.dask.org_dedicated',
operator='Equal',
value='worker',
effect='NoSchedule',
),
]
)
)
resources = client.V1ResourceRequirements(limits={}, requests={})
if cpu_request:
resources.requests['cpu'] = cpu_request
if memory_request:
resources.requests['memory'] = memory_request
if cpu_limit:
resources.limits['cpu'] = cpu_limit
if memory_limit:
resources.limits['memory'] = memory_limit
pod.spec.containers[0].resources = resources
for key, value in extra_container_config.items():
_set_k8s_attribute(
pod.spec.containers[0],
key,
value
)
for key, value in extra_pod_config.items():
_set_k8s_attribute(
pod.spec,
key,
value
)
return pod | [
"def",
"make_pod_spec",
"(",
"image",
",",
"labels",
"=",
"{",
"}",
",",
"threads_per_worker",
"=",
"1",
",",
"env",
"=",
"{",
"}",
",",
"extra_container_config",
"=",
"{",
"}",
",",
"extra_pod_config",
"=",
"{",
"}",
",",
"memory_limit",
"=",
"None",
... | Create generic pod template from input parameters
Examples
--------
>>> make_pod_spec(image='daskdev/dask:latest', memory_limit='4G', memory_request='4G') | [
"Create",
"generic",
"pod",
"template",
"from",
"input",
"parameters"
] | 8a4883ecd902460b446bb1f43ed97efe398a135e | https://github.com/dask/dask-kubernetes/blob/8a4883ecd902460b446bb1f43ed97efe398a135e/dask_kubernetes/objects.py#L96-L184 | train | 226,508 |
dask/dask-kubernetes | dask_kubernetes/objects.py | clean_pod_template | def clean_pod_template(pod_template):
""" Normalize pod template and check for type errors """
if isinstance(pod_template, str):
msg = ('Expected a kubernetes.client.V1Pod object, got %s'
'If trying to pass a yaml filename then use '
'KubeCluster.from_yaml')
raise TypeError(msg % pod_template)
if isinstance(pod_template, dict):
msg = ('Expected a kubernetes.client.V1Pod object, got %s'
'If trying to pass a dictionary specification then use '
'KubeCluster.from_dict')
raise TypeError(msg % str(pod_template))
pod_template = copy.deepcopy(pod_template)
# Make sure metadata / labels / env objects exist, so they can be modified
# later without a lot of `is None` checks
if pod_template.metadata is None:
pod_template.metadata = client.V1ObjectMeta()
if pod_template.metadata.labels is None:
pod_template.metadata.labels = {}
if pod_template.spec.containers[0].env is None:
pod_template.spec.containers[0].env = []
return pod_template | python | def clean_pod_template(pod_template):
""" Normalize pod template and check for type errors """
if isinstance(pod_template, str):
msg = ('Expected a kubernetes.client.V1Pod object, got %s'
'If trying to pass a yaml filename then use '
'KubeCluster.from_yaml')
raise TypeError(msg % pod_template)
if isinstance(pod_template, dict):
msg = ('Expected a kubernetes.client.V1Pod object, got %s'
'If trying to pass a dictionary specification then use '
'KubeCluster.from_dict')
raise TypeError(msg % str(pod_template))
pod_template = copy.deepcopy(pod_template)
# Make sure metadata / labels / env objects exist, so they can be modified
# later without a lot of `is None` checks
if pod_template.metadata is None:
pod_template.metadata = client.V1ObjectMeta()
if pod_template.metadata.labels is None:
pod_template.metadata.labels = {}
if pod_template.spec.containers[0].env is None:
pod_template.spec.containers[0].env = []
return pod_template | [
"def",
"clean_pod_template",
"(",
"pod_template",
")",
":",
"if",
"isinstance",
"(",
"pod_template",
",",
"str",
")",
":",
"msg",
"=",
"(",
"'Expected a kubernetes.client.V1Pod object, got %s'",
"'If trying to pass a yaml filename then use '",
"'KubeCluster.from_yaml'",
")",
... | Normalize pod template and check for type errors | [
"Normalize",
"pod",
"template",
"and",
"check",
"for",
"type",
"errors"
] | 8a4883ecd902460b446bb1f43ed97efe398a135e | https://github.com/dask/dask-kubernetes/blob/8a4883ecd902460b446bb1f43ed97efe398a135e/dask_kubernetes/objects.py#L199-L225 | train | 226,509 |
dask/dask-kubernetes | dask_kubernetes/core.py | _cleanup_pods | def _cleanup_pods(namespace, labels):
""" Remove all pods with these labels in this namespace """
api = kubernetes.client.CoreV1Api()
pods = api.list_namespaced_pod(namespace, label_selector=format_labels(labels))
for pod in pods.items:
try:
api.delete_namespaced_pod(pod.metadata.name, namespace)
logger.info('Deleted pod: %s', pod.metadata.name)
except kubernetes.client.rest.ApiException as e:
# ignore error if pod is already removed
if e.status != 404:
raise | python | def _cleanup_pods(namespace, labels):
""" Remove all pods with these labels in this namespace """
api = kubernetes.client.CoreV1Api()
pods = api.list_namespaced_pod(namespace, label_selector=format_labels(labels))
for pod in pods.items:
try:
api.delete_namespaced_pod(pod.metadata.name, namespace)
logger.info('Deleted pod: %s', pod.metadata.name)
except kubernetes.client.rest.ApiException as e:
# ignore error if pod is already removed
if e.status != 404:
raise | [
"def",
"_cleanup_pods",
"(",
"namespace",
",",
"labels",
")",
":",
"api",
"=",
"kubernetes",
".",
"client",
".",
"CoreV1Api",
"(",
")",
"pods",
"=",
"api",
".",
"list_namespaced_pod",
"(",
"namespace",
",",
"label_selector",
"=",
"format_labels",
"(",
"label... | Remove all pods with these labels in this namespace | [
"Remove",
"all",
"pods",
"with",
"these",
"labels",
"in",
"this",
"namespace"
] | 8a4883ecd902460b446bb1f43ed97efe398a135e | https://github.com/dask/dask-kubernetes/blob/8a4883ecd902460b446bb1f43ed97efe398a135e/dask_kubernetes/core.py#L500-L511 | train | 226,510 |
dask/dask-kubernetes | dask_kubernetes/core.py | format_labels | def format_labels(labels):
""" Convert a dictionary of labels into a comma separated string """
if labels:
return ','.join(['{}={}'.format(k, v) for k, v in labels.items()])
else:
return '' | python | def format_labels(labels):
""" Convert a dictionary of labels into a comma separated string """
if labels:
return ','.join(['{}={}'.format(k, v) for k, v in labels.items()])
else:
return '' | [
"def",
"format_labels",
"(",
"labels",
")",
":",
"if",
"labels",
":",
"return",
"','",
".",
"join",
"(",
"[",
"'{}={}'",
".",
"format",
"(",
"k",
",",
"v",
")",
"for",
"k",
",",
"v",
"in",
"labels",
".",
"items",
"(",
")",
"]",
")",
"else",
":"... | Convert a dictionary of labels into a comma separated string | [
"Convert",
"a",
"dictionary",
"of",
"labels",
"into",
"a",
"comma",
"separated",
"string"
] | 8a4883ecd902460b446bb1f43ed97efe398a135e | https://github.com/dask/dask-kubernetes/blob/8a4883ecd902460b446bb1f43ed97efe398a135e/dask_kubernetes/core.py#L514-L519 | train | 226,511 |
dask/dask-kubernetes | dask_kubernetes/core.py | _namespace_default | def _namespace_default():
"""
Get current namespace if running in a k8s cluster
If not in a k8s cluster with service accounts enabled, default to
'default'
Taken from https://github.com/jupyterhub/kubespawner/blob/master/kubespawner/spawner.py#L125
"""
ns_path = '/var/run/secrets/kubernetes.io/serviceaccount/namespace'
if os.path.exists(ns_path):
with open(ns_path) as f:
return f.read().strip()
return 'default' | python | def _namespace_default():
"""
Get current namespace if running in a k8s cluster
If not in a k8s cluster with service accounts enabled, default to
'default'
Taken from https://github.com/jupyterhub/kubespawner/blob/master/kubespawner/spawner.py#L125
"""
ns_path = '/var/run/secrets/kubernetes.io/serviceaccount/namespace'
if os.path.exists(ns_path):
with open(ns_path) as f:
return f.read().strip()
return 'default' | [
"def",
"_namespace_default",
"(",
")",
":",
"ns_path",
"=",
"'/var/run/secrets/kubernetes.io/serviceaccount/namespace'",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"ns_path",
")",
":",
"with",
"open",
"(",
"ns_path",
")",
"as",
"f",
":",
"return",
"f",
".",
... | Get current namespace if running in a k8s cluster
If not in a k8s cluster with service accounts enabled, default to
'default'
Taken from https://github.com/jupyterhub/kubespawner/blob/master/kubespawner/spawner.py#L125 | [
"Get",
"current",
"namespace",
"if",
"running",
"in",
"a",
"k8s",
"cluster"
] | 8a4883ecd902460b446bb1f43ed97efe398a135e | https://github.com/dask/dask-kubernetes/blob/8a4883ecd902460b446bb1f43ed97efe398a135e/dask_kubernetes/core.py#L522-L535 | train | 226,512 |
dask/dask-kubernetes | dask_kubernetes/core.py | select_workers_to_close | def select_workers_to_close(scheduler, n_to_close):
""" Select n workers to close from scheduler """
workers = list(scheduler.workers.values())
assert n_to_close <= len(workers)
key = lambda ws: ws.metrics['memory']
to_close = set(sorted(scheduler.idle, key=key)[:n_to_close])
if len(to_close) < n_to_close:
rest = sorted(workers, key=key, reverse=True)
while len(to_close) < n_to_close:
to_close.add(rest.pop())
return [ws.address for ws in to_close] | python | def select_workers_to_close(scheduler, n_to_close):
""" Select n workers to close from scheduler """
workers = list(scheduler.workers.values())
assert n_to_close <= len(workers)
key = lambda ws: ws.metrics['memory']
to_close = set(sorted(scheduler.idle, key=key)[:n_to_close])
if len(to_close) < n_to_close:
rest = sorted(workers, key=key, reverse=True)
while len(to_close) < n_to_close:
to_close.add(rest.pop())
return [ws.address for ws in to_close] | [
"def",
"select_workers_to_close",
"(",
"scheduler",
",",
"n_to_close",
")",
":",
"workers",
"=",
"list",
"(",
"scheduler",
".",
"workers",
".",
"values",
"(",
")",
")",
"assert",
"n_to_close",
"<=",
"len",
"(",
"workers",
")",
"key",
"=",
"lambda",
"ws",
... | Select n workers to close from scheduler | [
"Select",
"n",
"workers",
"to",
"close",
"from",
"scheduler"
] | 8a4883ecd902460b446bb1f43ed97efe398a135e | https://github.com/dask/dask-kubernetes/blob/8a4883ecd902460b446bb1f43ed97efe398a135e/dask_kubernetes/core.py#L538-L550 | train | 226,513 |
dask/dask-kubernetes | dask_kubernetes/core.py | KubeCluster.from_yaml | def from_yaml(cls, yaml_path, **kwargs):
""" Create cluster with worker pod spec defined by a YAML file
We can start a cluster with pods defined in an accompanying YAML file
like the following:
.. code-block:: yaml
kind: Pod
metadata:
labels:
foo: bar
baz: quux
spec:
containers:
- image: daskdev/dask:latest
name: dask-worker
args: [dask-worker, $(DASK_SCHEDULER_ADDRESS), --nthreads, '2', --memory-limit, 8GB]
restartPolicy: Never
Examples
--------
>>> cluster = KubeCluster.from_yaml('pod.yaml', namespace='my-ns') # doctest: +SKIP
See Also
--------
KubeCluster.from_dict
"""
if not yaml:
raise ImportError("PyYaml is required to use yaml functionality, please install it!")
with open(yaml_path) as f:
d = yaml.safe_load(f)
d = dask.config.expand_environment_variables(d)
return cls.from_dict(d, **kwargs) | python | def from_yaml(cls, yaml_path, **kwargs):
""" Create cluster with worker pod spec defined by a YAML file
We can start a cluster with pods defined in an accompanying YAML file
like the following:
.. code-block:: yaml
kind: Pod
metadata:
labels:
foo: bar
baz: quux
spec:
containers:
- image: daskdev/dask:latest
name: dask-worker
args: [dask-worker, $(DASK_SCHEDULER_ADDRESS), --nthreads, '2', --memory-limit, 8GB]
restartPolicy: Never
Examples
--------
>>> cluster = KubeCluster.from_yaml('pod.yaml', namespace='my-ns') # doctest: +SKIP
See Also
--------
KubeCluster.from_dict
"""
if not yaml:
raise ImportError("PyYaml is required to use yaml functionality, please install it!")
with open(yaml_path) as f:
d = yaml.safe_load(f)
d = dask.config.expand_environment_variables(d)
return cls.from_dict(d, **kwargs) | [
"def",
"from_yaml",
"(",
"cls",
",",
"yaml_path",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"yaml",
":",
"raise",
"ImportError",
"(",
"\"PyYaml is required to use yaml functionality, please install it!\"",
")",
"with",
"open",
"(",
"yaml_path",
")",
"as",
... | Create cluster with worker pod spec defined by a YAML file
We can start a cluster with pods defined in an accompanying YAML file
like the following:
.. code-block:: yaml
kind: Pod
metadata:
labels:
foo: bar
baz: quux
spec:
containers:
- image: daskdev/dask:latest
name: dask-worker
args: [dask-worker, $(DASK_SCHEDULER_ADDRESS), --nthreads, '2', --memory-limit, 8GB]
restartPolicy: Never
Examples
--------
>>> cluster = KubeCluster.from_yaml('pod.yaml', namespace='my-ns') # doctest: +SKIP
See Also
--------
KubeCluster.from_dict | [
"Create",
"cluster",
"with",
"worker",
"pod",
"spec",
"defined",
"by",
"a",
"YAML",
"file"
] | 8a4883ecd902460b446bb1f43ed97efe398a135e | https://github.com/dask/dask-kubernetes/blob/8a4883ecd902460b446bb1f43ed97efe398a135e/dask_kubernetes/core.py#L251-L284 | train | 226,514 |
dask/dask-kubernetes | dask_kubernetes/core.py | KubeCluster.pods | def pods(self):
""" A list of kubernetes pods corresponding to current workers
See Also
--------
KubeCluster.logs
"""
return self.core_api.list_namespaced_pod(
self.namespace,
label_selector=format_labels(self.pod_template.metadata.labels)
).items | python | def pods(self):
""" A list of kubernetes pods corresponding to current workers
See Also
--------
KubeCluster.logs
"""
return self.core_api.list_namespaced_pod(
self.namespace,
label_selector=format_labels(self.pod_template.metadata.labels)
).items | [
"def",
"pods",
"(",
"self",
")",
":",
"return",
"self",
".",
"core_api",
".",
"list_namespaced_pod",
"(",
"self",
".",
"namespace",
",",
"label_selector",
"=",
"format_labels",
"(",
"self",
".",
"pod_template",
".",
"metadata",
".",
"labels",
")",
")",
"."... | A list of kubernetes pods corresponding to current workers
See Also
--------
KubeCluster.logs | [
"A",
"list",
"of",
"kubernetes",
"pods",
"corresponding",
"to",
"current",
"workers"
] | 8a4883ecd902460b446bb1f43ed97efe398a135e | https://github.com/dask/dask-kubernetes/blob/8a4883ecd902460b446bb1f43ed97efe398a135e/dask_kubernetes/core.py#L306-L316 | train | 226,515 |
dask/dask-kubernetes | dask_kubernetes/core.py | KubeCluster.logs | def logs(self, pod=None):
""" Logs from a worker pod
You can get this pod object from the ``pods`` method.
If no pod is specified all pod logs will be returned. On large clusters
this could end up being rather large.
Parameters
----------
pod: kubernetes.client.V1Pod
The pod from which we want to collect logs.
See Also
--------
KubeCluster.pods
Client.get_worker_logs
"""
if pod is None:
return {pod.status.pod_ip: self.logs(pod) for pod in self.pods()}
return self.core_api.read_namespaced_pod_log(pod.metadata.name,
pod.metadata.namespace) | python | def logs(self, pod=None):
""" Logs from a worker pod
You can get this pod object from the ``pods`` method.
If no pod is specified all pod logs will be returned. On large clusters
this could end up being rather large.
Parameters
----------
pod: kubernetes.client.V1Pod
The pod from which we want to collect logs.
See Also
--------
KubeCluster.pods
Client.get_worker_logs
"""
if pod is None:
return {pod.status.pod_ip: self.logs(pod) for pod in self.pods()}
return self.core_api.read_namespaced_pod_log(pod.metadata.name,
pod.metadata.namespace) | [
"def",
"logs",
"(",
"self",
",",
"pod",
"=",
"None",
")",
":",
"if",
"pod",
"is",
"None",
":",
"return",
"{",
"pod",
".",
"status",
".",
"pod_ip",
":",
"self",
".",
"logs",
"(",
"pod",
")",
"for",
"pod",
"in",
"self",
".",
"pods",
"(",
")",
"... | Logs from a worker pod
You can get this pod object from the ``pods`` method.
If no pod is specified all pod logs will be returned. On large clusters
this could end up being rather large.
Parameters
----------
pod: kubernetes.client.V1Pod
The pod from which we want to collect logs.
See Also
--------
KubeCluster.pods
Client.get_worker_logs | [
"Logs",
"from",
"a",
"worker",
"pod"
] | 8a4883ecd902460b446bb1f43ed97efe398a135e | https://github.com/dask/dask-kubernetes/blob/8a4883ecd902460b446bb1f43ed97efe398a135e/dask_kubernetes/core.py#L318-L340 | train | 226,516 |
dask/dask-kubernetes | dask_kubernetes/core.py | KubeCluster.scale | def scale(self, n):
""" Scale cluster to n workers
Parameters
----------
n: int
Target number of workers
Example
-------
>>> cluster.scale(10) # scale cluster to ten workers
See Also
--------
KubeCluster.scale_up
KubeCluster.scale_down
"""
pods = self._cleanup_terminated_pods(self.pods())
if n >= len(pods):
return self.scale_up(n, pods=pods)
else:
n_to_delete = len(pods) - n
# Before trying to close running workers, check if we can cancel
# pending pods (in case the kubernetes cluster was too full to
# provision those pods in the first place).
running_workers = list(self.scheduler.workers.keys())
running_ips = set(urlparse(worker).hostname
for worker in running_workers)
pending_pods = [p for p in pods
if p.status.pod_ip not in running_ips]
if pending_pods:
pending_to_delete = pending_pods[:n_to_delete]
logger.debug("Deleting pending pods: %s", pending_to_delete)
self._delete_pods(pending_to_delete)
n_to_delete = n_to_delete - len(pending_to_delete)
if n_to_delete <= 0:
return
to_close = select_workers_to_close(self.scheduler, n_to_delete)
logger.debug("Closing workers: %s", to_close)
if len(to_close) < len(self.scheduler.workers):
# Close workers cleanly to migrate any temporary results to
# remaining workers.
@gen.coroutine
def f(to_close):
yield self.scheduler.retire_workers(
workers=to_close, remove=True, close_workers=True)
yield offload(self.scale_down, to_close)
self.scheduler.loop.add_callback(f, to_close)
return
# Terminate all pods without waiting for clean worker shutdown
self.scale_down(to_close) | python | def scale(self, n):
""" Scale cluster to n workers
Parameters
----------
n: int
Target number of workers
Example
-------
>>> cluster.scale(10) # scale cluster to ten workers
See Also
--------
KubeCluster.scale_up
KubeCluster.scale_down
"""
pods = self._cleanup_terminated_pods(self.pods())
if n >= len(pods):
return self.scale_up(n, pods=pods)
else:
n_to_delete = len(pods) - n
# Before trying to close running workers, check if we can cancel
# pending pods (in case the kubernetes cluster was too full to
# provision those pods in the first place).
running_workers = list(self.scheduler.workers.keys())
running_ips = set(urlparse(worker).hostname
for worker in running_workers)
pending_pods = [p for p in pods
if p.status.pod_ip not in running_ips]
if pending_pods:
pending_to_delete = pending_pods[:n_to_delete]
logger.debug("Deleting pending pods: %s", pending_to_delete)
self._delete_pods(pending_to_delete)
n_to_delete = n_to_delete - len(pending_to_delete)
if n_to_delete <= 0:
return
to_close = select_workers_to_close(self.scheduler, n_to_delete)
logger.debug("Closing workers: %s", to_close)
if len(to_close) < len(self.scheduler.workers):
# Close workers cleanly to migrate any temporary results to
# remaining workers.
@gen.coroutine
def f(to_close):
yield self.scheduler.retire_workers(
workers=to_close, remove=True, close_workers=True)
yield offload(self.scale_down, to_close)
self.scheduler.loop.add_callback(f, to_close)
return
# Terminate all pods without waiting for clean worker shutdown
self.scale_down(to_close) | [
"def",
"scale",
"(",
"self",
",",
"n",
")",
":",
"pods",
"=",
"self",
".",
"_cleanup_terminated_pods",
"(",
"self",
".",
"pods",
"(",
")",
")",
"if",
"n",
">=",
"len",
"(",
"pods",
")",
":",
"return",
"self",
".",
"scale_up",
"(",
"n",
",",
"pods... | Scale cluster to n workers
Parameters
----------
n: int
Target number of workers
Example
-------
>>> cluster.scale(10) # scale cluster to ten workers
See Also
--------
KubeCluster.scale_up
KubeCluster.scale_down | [
"Scale",
"cluster",
"to",
"n",
"workers"
] | 8a4883ecd902460b446bb1f43ed97efe398a135e | https://github.com/dask/dask-kubernetes/blob/8a4883ecd902460b446bb1f43ed97efe398a135e/dask_kubernetes/core.py#L342-L395 | train | 226,517 |
dask/dask-kubernetes | dask_kubernetes/core.py | KubeCluster.scale_up | def scale_up(self, n, pods=None, **kwargs):
"""
Make sure we have n dask-workers available for this cluster
Examples
--------
>>> cluster.scale_up(20) # ask for twenty workers
"""
maximum = dask.config.get('kubernetes.count.max')
if maximum is not None and maximum < n:
logger.info("Tried to scale beyond maximum number of workers %d > %d",
n, maximum)
n = maximum
pods = pods or self._cleanup_terminated_pods(self.pods())
to_create = n - len(pods)
new_pods = []
for i in range(3):
try:
for _ in range(to_create):
new_pods.append(self.core_api.create_namespaced_pod(
self.namespace, self.pod_template))
to_create -= 1
break
except kubernetes.client.rest.ApiException as e:
if e.status == 500 and 'ServerTimeout' in e.body:
logger.info("Server timeout, retry #%d", i + 1)
time.sleep(1)
last_exception = e
continue
else:
raise
else:
raise last_exception
return new_pods | python | def scale_up(self, n, pods=None, **kwargs):
"""
Make sure we have n dask-workers available for this cluster
Examples
--------
>>> cluster.scale_up(20) # ask for twenty workers
"""
maximum = dask.config.get('kubernetes.count.max')
if maximum is not None and maximum < n:
logger.info("Tried to scale beyond maximum number of workers %d > %d",
n, maximum)
n = maximum
pods = pods or self._cleanup_terminated_pods(self.pods())
to_create = n - len(pods)
new_pods = []
for i in range(3):
try:
for _ in range(to_create):
new_pods.append(self.core_api.create_namespaced_pod(
self.namespace, self.pod_template))
to_create -= 1
break
except kubernetes.client.rest.ApiException as e:
if e.status == 500 and 'ServerTimeout' in e.body:
logger.info("Server timeout, retry #%d", i + 1)
time.sleep(1)
last_exception = e
continue
else:
raise
else:
raise last_exception
return new_pods | [
"def",
"scale_up",
"(",
"self",
",",
"n",
",",
"pods",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"maximum",
"=",
"dask",
".",
"config",
".",
"get",
"(",
"'kubernetes.count.max'",
")",
"if",
"maximum",
"is",
"not",
"None",
"and",
"maximum",
"<",... | Make sure we have n dask-workers available for this cluster
Examples
--------
>>> cluster.scale_up(20) # ask for twenty workers | [
"Make",
"sure",
"we",
"have",
"n",
"dask",
"-",
"workers",
"available",
"for",
"this",
"cluster"
] | 8a4883ecd902460b446bb1f43ed97efe398a135e | https://github.com/dask/dask-kubernetes/blob/8a4883ecd902460b446bb1f43ed97efe398a135e/dask_kubernetes/core.py#L421-L455 | train | 226,518 |
dask/dask-kubernetes | dask_kubernetes/core.py | KubeCluster.scale_down | def scale_down(self, workers, pods=None):
""" Remove the pods for the requested list of workers
When scale_down is called by the _adapt async loop, the workers are
assumed to have been cleanly closed first and in-memory data has been
migrated to the remaining workers.
Note that when the worker process exits, Kubernetes leaves the pods in
a 'Succeeded' state that we collect here.
If some workers have not been closed, we just delete the pods with
matching ip addresses.
Parameters
----------
workers: List[str] List of addresses of workers to close
"""
# Get the existing worker pods
pods = pods or self._cleanup_terminated_pods(self.pods())
# Work out the list of pods that we are going to delete
# Each worker to delete is given in the form "tcp://<worker ip>:<port>"
# Convert this to a set of IPs
ips = set(urlparse(worker).hostname for worker in workers)
to_delete = [p for p in pods if p.status.pod_ip in ips]
if not to_delete:
return
self._delete_pods(to_delete) | python | def scale_down(self, workers, pods=None):
""" Remove the pods for the requested list of workers
When scale_down is called by the _adapt async loop, the workers are
assumed to have been cleanly closed first and in-memory data has been
migrated to the remaining workers.
Note that when the worker process exits, Kubernetes leaves the pods in
a 'Succeeded' state that we collect here.
If some workers have not been closed, we just delete the pods with
matching ip addresses.
Parameters
----------
workers: List[str] List of addresses of workers to close
"""
# Get the existing worker pods
pods = pods or self._cleanup_terminated_pods(self.pods())
# Work out the list of pods that we are going to delete
# Each worker to delete is given in the form "tcp://<worker ip>:<port>"
# Convert this to a set of IPs
ips = set(urlparse(worker).hostname for worker in workers)
to_delete = [p for p in pods if p.status.pod_ip in ips]
if not to_delete:
return
self._delete_pods(to_delete) | [
"def",
"scale_down",
"(",
"self",
",",
"workers",
",",
"pods",
"=",
"None",
")",
":",
"# Get the existing worker pods",
"pods",
"=",
"pods",
"or",
"self",
".",
"_cleanup_terminated_pods",
"(",
"self",
".",
"pods",
"(",
")",
")",
"# Work out the list of pods that... | Remove the pods for the requested list of workers
When scale_down is called by the _adapt async loop, the workers are
assumed to have been cleanly closed first and in-memory data has been
migrated to the remaining workers.
Note that when the worker process exits, Kubernetes leaves the pods in
a 'Succeeded' state that we collect here.
If some workers have not been closed, we just delete the pods with
matching ip addresses.
Parameters
----------
workers: List[str] List of addresses of workers to close | [
"Remove",
"the",
"pods",
"for",
"the",
"requested",
"list",
"of",
"workers"
] | 8a4883ecd902460b446bb1f43ed97efe398a135e | https://github.com/dask/dask-kubernetes/blob/8a4883ecd902460b446bb1f43ed97efe398a135e/dask_kubernetes/core.py#L458-L485 | train | 226,519 |
dask/dask-kubernetes | dask_kubernetes/core.py | KubeCluster.close | def close(self, **kwargs):
""" Close this cluster """
self.scale_down(self.cluster.scheduler.workers)
return self.cluster.close(**kwargs) | python | def close(self, **kwargs):
""" Close this cluster """
self.scale_down(self.cluster.scheduler.workers)
return self.cluster.close(**kwargs) | [
"def",
"close",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"scale_down",
"(",
"self",
".",
"cluster",
".",
"scheduler",
".",
"workers",
")",
"return",
"self",
".",
"cluster",
".",
"close",
"(",
"*",
"*",
"kwargs",
")"
] | Close this cluster | [
"Close",
"this",
"cluster"
] | 8a4883ecd902460b446bb1f43ed97efe398a135e | https://github.com/dask/dask-kubernetes/blob/8a4883ecd902460b446bb1f43ed97efe398a135e/dask_kubernetes/core.py#L490-L493 | train | 226,520 |
viniciuschiele/flask-apscheduler | flask_apscheduler/utils.py | job_to_dict | def job_to_dict(job):
"""Converts a job to an OrderedDict."""
data = OrderedDict()
data['id'] = job.id
data['name'] = job.name
data['func'] = job.func_ref
data['args'] = job.args
data['kwargs'] = job.kwargs
data.update(trigger_to_dict(job.trigger))
if not job.pending:
data['misfire_grace_time'] = job.misfire_grace_time
data['max_instances'] = job.max_instances
data['next_run_time'] = None if job.next_run_time is None else job.next_run_time
return data | python | def job_to_dict(job):
"""Converts a job to an OrderedDict."""
data = OrderedDict()
data['id'] = job.id
data['name'] = job.name
data['func'] = job.func_ref
data['args'] = job.args
data['kwargs'] = job.kwargs
data.update(trigger_to_dict(job.trigger))
if not job.pending:
data['misfire_grace_time'] = job.misfire_grace_time
data['max_instances'] = job.max_instances
data['next_run_time'] = None if job.next_run_time is None else job.next_run_time
return data | [
"def",
"job_to_dict",
"(",
"job",
")",
":",
"data",
"=",
"OrderedDict",
"(",
")",
"data",
"[",
"'id'",
"]",
"=",
"job",
".",
"id",
"data",
"[",
"'name'",
"]",
"=",
"job",
".",
"name",
"data",
"[",
"'func'",
"]",
"=",
"job",
".",
"func_ref",
"data... | Converts a job to an OrderedDict. | [
"Converts",
"a",
"job",
"to",
"an",
"OrderedDict",
"."
] | cc52c39e1948c4e8de5da0d01db45f1779f61997 | https://github.com/viniciuschiele/flask-apscheduler/blob/cc52c39e1948c4e8de5da0d01db45f1779f61997/flask_apscheduler/utils.py#L26-L43 | train | 226,521 |
viniciuschiele/flask-apscheduler | flask_apscheduler/utils.py | pop_trigger | def pop_trigger(data):
"""Pops trigger and trigger args from a given dict."""
trigger_name = data.pop('trigger')
trigger_args = {}
if trigger_name == 'date':
trigger_arg_names = ('run_date', 'timezone')
elif trigger_name == 'interval':
trigger_arg_names = ('weeks', 'days', 'hours', 'minutes', 'seconds', 'start_date', 'end_date', 'timezone')
elif trigger_name == 'cron':
trigger_arg_names = ('year', 'month', 'day', 'week', 'day_of_week', 'hour', 'minute', 'second', 'start_date', 'end_date', 'timezone')
else:
raise Exception('Trigger %s is not supported.' % trigger_name)
for arg_name in trigger_arg_names:
if arg_name in data:
trigger_args[arg_name] = data.pop(arg_name)
return trigger_name, trigger_args | python | def pop_trigger(data):
"""Pops trigger and trigger args from a given dict."""
trigger_name = data.pop('trigger')
trigger_args = {}
if trigger_name == 'date':
trigger_arg_names = ('run_date', 'timezone')
elif trigger_name == 'interval':
trigger_arg_names = ('weeks', 'days', 'hours', 'minutes', 'seconds', 'start_date', 'end_date', 'timezone')
elif trigger_name == 'cron':
trigger_arg_names = ('year', 'month', 'day', 'week', 'day_of_week', 'hour', 'minute', 'second', 'start_date', 'end_date', 'timezone')
else:
raise Exception('Trigger %s is not supported.' % trigger_name)
for arg_name in trigger_arg_names:
if arg_name in data:
trigger_args[arg_name] = data.pop(arg_name)
return trigger_name, trigger_args | [
"def",
"pop_trigger",
"(",
"data",
")",
":",
"trigger_name",
"=",
"data",
".",
"pop",
"(",
"'trigger'",
")",
"trigger_args",
"=",
"{",
"}",
"if",
"trigger_name",
"==",
"'date'",
":",
"trigger_arg_names",
"=",
"(",
"'run_date'",
",",
"'timezone'",
")",
"eli... | Pops trigger and trigger args from a given dict. | [
"Pops",
"trigger",
"and",
"trigger",
"args",
"from",
"a",
"given",
"dict",
"."
] | cc52c39e1948c4e8de5da0d01db45f1779f61997 | https://github.com/viniciuschiele/flask-apscheduler/blob/cc52c39e1948c4e8de5da0d01db45f1779f61997/flask_apscheduler/utils.py#L46-L65 | train | 226,522 |
viniciuschiele/flask-apscheduler | flask_apscheduler/utils.py | trigger_to_dict | def trigger_to_dict(trigger):
"""Converts a trigger to an OrderedDict."""
data = OrderedDict()
if isinstance(trigger, DateTrigger):
data['trigger'] = 'date'
data['run_date'] = trigger.run_date
elif isinstance(trigger, IntervalTrigger):
data['trigger'] = 'interval'
data['start_date'] = trigger.start_date
if trigger.end_date:
data['end_date'] = trigger.end_date
w, d, hh, mm, ss = extract_timedelta(trigger.interval)
if w > 0:
data['weeks'] = w
if d > 0:
data['days'] = d
if hh > 0:
data['hours'] = hh
if mm > 0:
data['minutes'] = mm
if ss > 0:
data['seconds'] = ss
elif isinstance(trigger, CronTrigger):
data['trigger'] = 'cron'
if trigger.start_date:
data['start_date'] = trigger.start_date
if trigger.end_date:
data['end_date'] = trigger.end_date
for field in trigger.fields:
if not field.is_default:
data[field.name] = str(field)
else:
data['trigger'] = str(trigger)
return data | python | def trigger_to_dict(trigger):
"""Converts a trigger to an OrderedDict."""
data = OrderedDict()
if isinstance(trigger, DateTrigger):
data['trigger'] = 'date'
data['run_date'] = trigger.run_date
elif isinstance(trigger, IntervalTrigger):
data['trigger'] = 'interval'
data['start_date'] = trigger.start_date
if trigger.end_date:
data['end_date'] = trigger.end_date
w, d, hh, mm, ss = extract_timedelta(trigger.interval)
if w > 0:
data['weeks'] = w
if d > 0:
data['days'] = d
if hh > 0:
data['hours'] = hh
if mm > 0:
data['minutes'] = mm
if ss > 0:
data['seconds'] = ss
elif isinstance(trigger, CronTrigger):
data['trigger'] = 'cron'
if trigger.start_date:
data['start_date'] = trigger.start_date
if trigger.end_date:
data['end_date'] = trigger.end_date
for field in trigger.fields:
if not field.is_default:
data[field.name] = str(field)
else:
data['trigger'] = str(trigger)
return data | [
"def",
"trigger_to_dict",
"(",
"trigger",
")",
":",
"data",
"=",
"OrderedDict",
"(",
")",
"if",
"isinstance",
"(",
"trigger",
",",
"DateTrigger",
")",
":",
"data",
"[",
"'trigger'",
"]",
"=",
"'date'",
"data",
"[",
"'run_date'",
"]",
"=",
"trigger",
".",... | Converts a trigger to an OrderedDict. | [
"Converts",
"a",
"trigger",
"to",
"an",
"OrderedDict",
"."
] | cc52c39e1948c4e8de5da0d01db45f1779f61997 | https://github.com/viniciuschiele/flask-apscheduler/blob/cc52c39e1948c4e8de5da0d01db45f1779f61997/flask_apscheduler/utils.py#L68-L110 | train | 226,523 |
viniciuschiele/flask-apscheduler | flask_apscheduler/utils.py | fix_job_def | def fix_job_def(job_def):
"""
Replaces the datetime in string by datetime object.
"""
if six.PY2 and isinstance(job_def.get('func'), six.text_type):
# when a job comes from the endpoint, strings are unicode
# because that's how json package deserialize the bytes.
# we had a case where APScheduler failed to import the func based
# on its name because Py2 expected a str and not unicode on __import__().
# it happened only for a user, I wasn't able to determine why that occurred for him,
# a workaround is to convert the func to str.
# full story: https://github.com/viniciuschiele/flask-apscheduler/issues/75
job_def['func'] = str(job_def.get('func'))
if isinstance(job_def.get('start_date'), six.string_types):
job_def['start_date'] = dateutil.parser.parse(job_def.get('start_date'))
if isinstance(job_def.get('end_date'), six.string_types):
job_def['end_date'] = dateutil.parser.parse(job_def.get('end_date'))
if isinstance(job_def.get('run_date'), six.string_types):
job_def['run_date'] = dateutil.parser.parse(job_def.get('run_date'))
# it keeps compatibility backward
if isinstance(job_def.get('trigger'), dict):
trigger = job_def.pop('trigger')
job_def['trigger'] = trigger.pop('type', 'date')
job_def.update(trigger) | python | def fix_job_def(job_def):
"""
Replaces the datetime in string by datetime object.
"""
if six.PY2 and isinstance(job_def.get('func'), six.text_type):
# when a job comes from the endpoint, strings are unicode
# because that's how json package deserialize the bytes.
# we had a case where APScheduler failed to import the func based
# on its name because Py2 expected a str and not unicode on __import__().
# it happened only for a user, I wasn't able to determine why that occurred for him,
# a workaround is to convert the func to str.
# full story: https://github.com/viniciuschiele/flask-apscheduler/issues/75
job_def['func'] = str(job_def.get('func'))
if isinstance(job_def.get('start_date'), six.string_types):
job_def['start_date'] = dateutil.parser.parse(job_def.get('start_date'))
if isinstance(job_def.get('end_date'), six.string_types):
job_def['end_date'] = dateutil.parser.parse(job_def.get('end_date'))
if isinstance(job_def.get('run_date'), six.string_types):
job_def['run_date'] = dateutil.parser.parse(job_def.get('run_date'))
# it keeps compatibility backward
if isinstance(job_def.get('trigger'), dict):
trigger = job_def.pop('trigger')
job_def['trigger'] = trigger.pop('type', 'date')
job_def.update(trigger) | [
"def",
"fix_job_def",
"(",
"job_def",
")",
":",
"if",
"six",
".",
"PY2",
"and",
"isinstance",
"(",
"job_def",
".",
"get",
"(",
"'func'",
")",
",",
"six",
".",
"text_type",
")",
":",
"# when a job comes from the endpoint, strings are unicode",
"# because that's how... | Replaces the datetime in string by datetime object. | [
"Replaces",
"the",
"datetime",
"in",
"string",
"by",
"datetime",
"object",
"."
] | cc52c39e1948c4e8de5da0d01db45f1779f61997 | https://github.com/viniciuschiele/flask-apscheduler/blob/cc52c39e1948c4e8de5da0d01db45f1779f61997/flask_apscheduler/utils.py#L113-L142 | train | 226,524 |
viniciuschiele/flask-apscheduler | flask_apscheduler/scheduler.py | APScheduler.init_app | def init_app(self, app):
"""Initialize the APScheduler with a Flask application instance."""
self.app = app
self.app.apscheduler = self
self._load_config()
self._load_jobs()
if self.api_enabled:
self._load_api() | python | def init_app(self, app):
"""Initialize the APScheduler with a Flask application instance."""
self.app = app
self.app.apscheduler = self
self._load_config()
self._load_jobs()
if self.api_enabled:
self._load_api() | [
"def",
"init_app",
"(",
"self",
",",
"app",
")",
":",
"self",
".",
"app",
"=",
"app",
"self",
".",
"app",
".",
"apscheduler",
"=",
"self",
"self",
".",
"_load_config",
"(",
")",
"self",
".",
"_load_jobs",
"(",
")",
"if",
"self",
".",
"api_enabled",
... | Initialize the APScheduler with a Flask application instance. | [
"Initialize",
"the",
"APScheduler",
"with",
"a",
"Flask",
"application",
"instance",
"."
] | cc52c39e1948c4e8de5da0d01db45f1779f61997 | https://github.com/viniciuschiele/flask-apscheduler/blob/cc52c39e1948c4e8de5da0d01db45f1779f61997/flask_apscheduler/scheduler.py#L75-L85 | train | 226,525 |
viniciuschiele/flask-apscheduler | flask_apscheduler/scheduler.py | APScheduler.add_listener | def add_listener(self, callback, mask=EVENT_ALL):
"""
Add a listener for scheduler events.
When a matching event occurs, ``callback`` is executed with the event object as its
sole argument. If the ``mask`` parameter is not provided, the callback will receive events
of all types.
For further info: https://apscheduler.readthedocs.io/en/latest/userguide.html#scheduler-events
:param callback: any callable that takes one argument
:param int mask: bitmask that indicates which events should be listened to
"""
self._scheduler.add_listener(callback, mask) | python | def add_listener(self, callback, mask=EVENT_ALL):
"""
Add a listener for scheduler events.
When a matching event occurs, ``callback`` is executed with the event object as its
sole argument. If the ``mask`` parameter is not provided, the callback will receive events
of all types.
For further info: https://apscheduler.readthedocs.io/en/latest/userguide.html#scheduler-events
:param callback: any callable that takes one argument
:param int mask: bitmask that indicates which events should be listened to
"""
self._scheduler.add_listener(callback, mask) | [
"def",
"add_listener",
"(",
"self",
",",
"callback",
",",
"mask",
"=",
"EVENT_ALL",
")",
":",
"self",
".",
"_scheduler",
".",
"add_listener",
"(",
"callback",
",",
"mask",
")"
] | Add a listener for scheduler events.
When a matching event occurs, ``callback`` is executed with the event object as its
sole argument. If the ``mask`` parameter is not provided, the callback will receive events
of all types.
For further info: https://apscheduler.readthedocs.io/en/latest/userguide.html#scheduler-events
:param callback: any callable that takes one argument
:param int mask: bitmask that indicates which events should be listened to | [
"Add",
"a",
"listener",
"for",
"scheduler",
"events",
"."
] | cc52c39e1948c4e8de5da0d01db45f1779f61997 | https://github.com/viniciuschiele/flask-apscheduler/blob/cc52c39e1948c4e8de5da0d01db45f1779f61997/flask_apscheduler/scheduler.py#L124-L137 | train | 226,526 |
viniciuschiele/flask-apscheduler | flask_apscheduler/scheduler.py | APScheduler.add_job | def add_job(self, id, func, **kwargs):
"""
Add the given job to the job list and wakes up the scheduler if it's already running.
:param str id: explicit identifier for the job (for modifying it later)
:param func: callable (or a textual reference to one) to run at the given time
"""
job_def = dict(kwargs)
job_def['id'] = id
job_def['func'] = func
job_def['name'] = job_def.get('name') or id
fix_job_def(job_def)
return self._scheduler.add_job(**job_def) | python | def add_job(self, id, func, **kwargs):
"""
Add the given job to the job list and wakes up the scheduler if it's already running.
:param str id: explicit identifier for the job (for modifying it later)
:param func: callable (or a textual reference to one) to run at the given time
"""
job_def = dict(kwargs)
job_def['id'] = id
job_def['func'] = func
job_def['name'] = job_def.get('name') or id
fix_job_def(job_def)
return self._scheduler.add_job(**job_def) | [
"def",
"add_job",
"(",
"self",
",",
"id",
",",
"func",
",",
"*",
"*",
"kwargs",
")",
":",
"job_def",
"=",
"dict",
"(",
"kwargs",
")",
"job_def",
"[",
"'id'",
"]",
"=",
"id",
"job_def",
"[",
"'func'",
"]",
"=",
"func",
"job_def",
"[",
"'name'",
"]... | Add the given job to the job list and wakes up the scheduler if it's already running.
:param str id: explicit identifier for the job (for modifying it later)
:param func: callable (or a textual reference to one) to run at the given time | [
"Add",
"the",
"given",
"job",
"to",
"the",
"job",
"list",
"and",
"wakes",
"up",
"the",
"scheduler",
"if",
"it",
"s",
"already",
"running",
"."
] | cc52c39e1948c4e8de5da0d01db45f1779f61997 | https://github.com/viniciuschiele/flask-apscheduler/blob/cc52c39e1948c4e8de5da0d01db45f1779f61997/flask_apscheduler/scheduler.py#L145-L160 | train | 226,527 |
viniciuschiele/flask-apscheduler | flask_apscheduler/scheduler.py | APScheduler.delete_job | def delete_job(self, id, jobstore=None):
"""
DEPRECATED, use remove_job instead.
Remove a job, preventing it from being run any more.
:param str id: the identifier of the job
:param str jobstore: alias of the job store that contains the job
"""
warnings.warn('delete_job has been deprecated, use remove_job instead.', DeprecationWarning)
self.remove_job(id, jobstore) | python | def delete_job(self, id, jobstore=None):
"""
DEPRECATED, use remove_job instead.
Remove a job, preventing it from being run any more.
:param str id: the identifier of the job
:param str jobstore: alias of the job store that contains the job
"""
warnings.warn('delete_job has been deprecated, use remove_job instead.', DeprecationWarning)
self.remove_job(id, jobstore) | [
"def",
"delete_job",
"(",
"self",
",",
"id",
",",
"jobstore",
"=",
"None",
")",
":",
"warnings",
".",
"warn",
"(",
"'delete_job has been deprecated, use remove_job instead.'",
",",
"DeprecationWarning",
")",
"self",
".",
"remove_job",
"(",
"id",
",",
"jobstore",
... | DEPRECATED, use remove_job instead.
Remove a job, preventing it from being run any more.
:param str id: the identifier of the job
:param str jobstore: alias of the job store that contains the job | [
"DEPRECATED",
"use",
"remove_job",
"instead",
"."
] | cc52c39e1948c4e8de5da0d01db45f1779f61997 | https://github.com/viniciuschiele/flask-apscheduler/blob/cc52c39e1948c4e8de5da0d01db45f1779f61997/flask_apscheduler/scheduler.py#L162-L173 | train | 226,528 |
viniciuschiele/flask-apscheduler | flask_apscheduler/scheduler.py | APScheduler.modify_job | def modify_job(self, id, jobstore=None, **changes):
"""
Modify the properties of a single job. Modifications are passed to this method as extra keyword arguments.
:param str id: the identifier of the job
:param str jobstore: alias of the job store that contains the job
"""
fix_job_def(changes)
if 'trigger' in changes:
trigger, trigger_args = pop_trigger(changes)
self._scheduler.reschedule_job(id, jobstore, trigger, **trigger_args)
return self._scheduler.modify_job(id, jobstore, **changes) | python | def modify_job(self, id, jobstore=None, **changes):
"""
Modify the properties of a single job. Modifications are passed to this method as extra keyword arguments.
:param str id: the identifier of the job
:param str jobstore: alias of the job store that contains the job
"""
fix_job_def(changes)
if 'trigger' in changes:
trigger, trigger_args = pop_trigger(changes)
self._scheduler.reschedule_job(id, jobstore, trigger, **trigger_args)
return self._scheduler.modify_job(id, jobstore, **changes) | [
"def",
"modify_job",
"(",
"self",
",",
"id",
",",
"jobstore",
"=",
"None",
",",
"*",
"*",
"changes",
")",
":",
"fix_job_def",
"(",
"changes",
")",
"if",
"'trigger'",
"in",
"changes",
":",
"trigger",
",",
"trigger_args",
"=",
"pop_trigger",
"(",
"changes"... | Modify the properties of a single job. Modifications are passed to this method as extra keyword arguments.
:param str id: the identifier of the job
:param str jobstore: alias of the job store that contains the job | [
"Modify",
"the",
"properties",
"of",
"a",
"single",
"job",
".",
"Modifications",
"are",
"passed",
"to",
"this",
"method",
"as",
"extra",
"keyword",
"arguments",
"."
] | cc52c39e1948c4e8de5da0d01db45f1779f61997 | https://github.com/viniciuschiele/flask-apscheduler/blob/cc52c39e1948c4e8de5da0d01db45f1779f61997/flask_apscheduler/scheduler.py#L230-L244 | train | 226,529 |
viniciuschiele/flask-apscheduler | flask_apscheduler/scheduler.py | APScheduler._load_config | def _load_config(self):
"""
Load the configuration from the Flask configuration.
"""
options = dict()
job_stores = self.app.config.get('SCHEDULER_JOBSTORES')
if job_stores:
options['jobstores'] = job_stores
executors = self.app.config.get('SCHEDULER_EXECUTORS')
if executors:
options['executors'] = executors
job_defaults = self.app.config.get('SCHEDULER_JOB_DEFAULTS')
if job_defaults:
options['job_defaults'] = job_defaults
timezone = self.app.config.get('SCHEDULER_TIMEZONE')
if timezone:
options['timezone'] = timezone
self._scheduler.configure(**options)
self.auth = self.app.config.get('SCHEDULER_AUTH', self.auth)
self.api_enabled = self.app.config.get('SCHEDULER_VIEWS_ENABLED', self.api_enabled) # for compatibility reason
self.api_enabled = self.app.config.get('SCHEDULER_API_ENABLED', self.api_enabled)
self.api_prefix = self.app.config.get('SCHEDULER_API_PREFIX', self.api_prefix)
self.endpoint_prefix = self.app.config.get('SCHEDULER_ENDPOINT_PREFIX', self.endpoint_prefix)
self.allowed_hosts = self.app.config.get('SCHEDULER_ALLOWED_HOSTS', self.allowed_hosts) | python | def _load_config(self):
"""
Load the configuration from the Flask configuration.
"""
options = dict()
job_stores = self.app.config.get('SCHEDULER_JOBSTORES')
if job_stores:
options['jobstores'] = job_stores
executors = self.app.config.get('SCHEDULER_EXECUTORS')
if executors:
options['executors'] = executors
job_defaults = self.app.config.get('SCHEDULER_JOB_DEFAULTS')
if job_defaults:
options['job_defaults'] = job_defaults
timezone = self.app.config.get('SCHEDULER_TIMEZONE')
if timezone:
options['timezone'] = timezone
self._scheduler.configure(**options)
self.auth = self.app.config.get('SCHEDULER_AUTH', self.auth)
self.api_enabled = self.app.config.get('SCHEDULER_VIEWS_ENABLED', self.api_enabled) # for compatibility reason
self.api_enabled = self.app.config.get('SCHEDULER_API_ENABLED', self.api_enabled)
self.api_prefix = self.app.config.get('SCHEDULER_API_PREFIX', self.api_prefix)
self.endpoint_prefix = self.app.config.get('SCHEDULER_ENDPOINT_PREFIX', self.endpoint_prefix)
self.allowed_hosts = self.app.config.get('SCHEDULER_ALLOWED_HOSTS', self.allowed_hosts) | [
"def",
"_load_config",
"(",
"self",
")",
":",
"options",
"=",
"dict",
"(",
")",
"job_stores",
"=",
"self",
".",
"app",
".",
"config",
".",
"get",
"(",
"'SCHEDULER_JOBSTORES'",
")",
"if",
"job_stores",
":",
"options",
"[",
"'jobstores'",
"]",
"=",
"job_st... | Load the configuration from the Flask configuration. | [
"Load",
"the",
"configuration",
"from",
"the",
"Flask",
"configuration",
"."
] | cc52c39e1948c4e8de5da0d01db45f1779f61997 | https://github.com/viniciuschiele/flask-apscheduler/blob/cc52c39e1948c4e8de5da0d01db45f1779f61997/flask_apscheduler/scheduler.py#L286-L315 | train | 226,530 |
viniciuschiele/flask-apscheduler | flask_apscheduler/scheduler.py | APScheduler._load_jobs | def _load_jobs(self):
"""
Load the job definitions from the Flask configuration.
"""
jobs = self.app.config.get('SCHEDULER_JOBS')
if not jobs:
jobs = self.app.config.get('JOBS')
if jobs:
for job in jobs:
self.add_job(**job) | python | def _load_jobs(self):
"""
Load the job definitions from the Flask configuration.
"""
jobs = self.app.config.get('SCHEDULER_JOBS')
if not jobs:
jobs = self.app.config.get('JOBS')
if jobs:
for job in jobs:
self.add_job(**job) | [
"def",
"_load_jobs",
"(",
"self",
")",
":",
"jobs",
"=",
"self",
".",
"app",
".",
"config",
".",
"get",
"(",
"'SCHEDULER_JOBS'",
")",
"if",
"not",
"jobs",
":",
"jobs",
"=",
"self",
".",
"app",
".",
"config",
".",
"get",
"(",
"'JOBS'",
")",
"if",
... | Load the job definitions from the Flask configuration. | [
"Load",
"the",
"job",
"definitions",
"from",
"the",
"Flask",
"configuration",
"."
] | cc52c39e1948c4e8de5da0d01db45f1779f61997 | https://github.com/viniciuschiele/flask-apscheduler/blob/cc52c39e1948c4e8de5da0d01db45f1779f61997/flask_apscheduler/scheduler.py#L317-L328 | train | 226,531 |
viniciuschiele/flask-apscheduler | flask_apscheduler/scheduler.py | APScheduler._load_api | def _load_api(self):
"""
Add the routes for the scheduler API.
"""
self._add_url_route('get_scheduler_info', '', api.get_scheduler_info, 'GET')
self._add_url_route('add_job', '/jobs', api.add_job, 'POST')
self._add_url_route('get_job', '/jobs/<job_id>', api.get_job, 'GET')
self._add_url_route('get_jobs', '/jobs', api.get_jobs, 'GET')
self._add_url_route('delete_job', '/jobs/<job_id>', api.delete_job, 'DELETE')
self._add_url_route('update_job', '/jobs/<job_id>', api.update_job, 'PATCH')
self._add_url_route('pause_job', '/jobs/<job_id>/pause', api.pause_job, 'POST')
self._add_url_route('resume_job', '/jobs/<job_id>/resume', api.resume_job, 'POST')
self._add_url_route('run_job', '/jobs/<job_id>/run', api.run_job, 'POST') | python | def _load_api(self):
"""
Add the routes for the scheduler API.
"""
self._add_url_route('get_scheduler_info', '', api.get_scheduler_info, 'GET')
self._add_url_route('add_job', '/jobs', api.add_job, 'POST')
self._add_url_route('get_job', '/jobs/<job_id>', api.get_job, 'GET')
self._add_url_route('get_jobs', '/jobs', api.get_jobs, 'GET')
self._add_url_route('delete_job', '/jobs/<job_id>', api.delete_job, 'DELETE')
self._add_url_route('update_job', '/jobs/<job_id>', api.update_job, 'PATCH')
self._add_url_route('pause_job', '/jobs/<job_id>/pause', api.pause_job, 'POST')
self._add_url_route('resume_job', '/jobs/<job_id>/resume', api.resume_job, 'POST')
self._add_url_route('run_job', '/jobs/<job_id>/run', api.run_job, 'POST') | [
"def",
"_load_api",
"(",
"self",
")",
":",
"self",
".",
"_add_url_route",
"(",
"'get_scheduler_info'",
",",
"''",
",",
"api",
".",
"get_scheduler_info",
",",
"'GET'",
")",
"self",
".",
"_add_url_route",
"(",
"'add_job'",
",",
"'/jobs'",
",",
"api",
".",
"a... | Add the routes for the scheduler API. | [
"Add",
"the",
"routes",
"for",
"the",
"scheduler",
"API",
"."
] | cc52c39e1948c4e8de5da0d01db45f1779f61997 | https://github.com/viniciuschiele/flask-apscheduler/blob/cc52c39e1948c4e8de5da0d01db45f1779f61997/flask_apscheduler/scheduler.py#L330-L342 | train | 226,532 |
viniciuschiele/flask-apscheduler | flask_apscheduler/scheduler.py | APScheduler._handle_authentication_error | def _handle_authentication_error(self):
"""
Return an authentication error.
"""
response = make_response('Access Denied')
response.headers['WWW-Authenticate'] = self.auth.get_authenticate_header()
response.status_code = 401
return response | python | def _handle_authentication_error(self):
"""
Return an authentication error.
"""
response = make_response('Access Denied')
response.headers['WWW-Authenticate'] = self.auth.get_authenticate_header()
response.status_code = 401
return response | [
"def",
"_handle_authentication_error",
"(",
"self",
")",
":",
"response",
"=",
"make_response",
"(",
"'Access Denied'",
")",
"response",
".",
"headers",
"[",
"'WWW-Authenticate'",
"]",
"=",
"self",
".",
"auth",
".",
"get_authenticate_header",
"(",
")",
"response",... | Return an authentication error. | [
"Return",
"an",
"authentication",
"error",
"."
] | cc52c39e1948c4e8de5da0d01db45f1779f61997 | https://github.com/viniciuschiele/flask-apscheduler/blob/cc52c39e1948c4e8de5da0d01db45f1779f61997/flask_apscheduler/scheduler.py#L387-L394 | train | 226,533 |
viniciuschiele/flask-apscheduler | flask_apscheduler/api.py | get_scheduler_info | def get_scheduler_info():
"""Gets the scheduler info."""
scheduler = current_app.apscheduler
d = OrderedDict([
('current_host', scheduler.host_name),
('allowed_hosts', scheduler.allowed_hosts),
('running', scheduler.running)
])
return jsonify(d) | python | def get_scheduler_info():
"""Gets the scheduler info."""
scheduler = current_app.apscheduler
d = OrderedDict([
('current_host', scheduler.host_name),
('allowed_hosts', scheduler.allowed_hosts),
('running', scheduler.running)
])
return jsonify(d) | [
"def",
"get_scheduler_info",
"(",
")",
":",
"scheduler",
"=",
"current_app",
".",
"apscheduler",
"d",
"=",
"OrderedDict",
"(",
"[",
"(",
"'current_host'",
",",
"scheduler",
".",
"host_name",
")",
",",
"(",
"'allowed_hosts'",
",",
"scheduler",
".",
"allowed_hos... | Gets the scheduler info. | [
"Gets",
"the",
"scheduler",
"info",
"."
] | cc52c39e1948c4e8de5da0d01db45f1779f61997 | https://github.com/viniciuschiele/flask-apscheduler/blob/cc52c39e1948c4e8de5da0d01db45f1779f61997/flask_apscheduler/api.py#L21-L32 | train | 226,534 |
viniciuschiele/flask-apscheduler | flask_apscheduler/api.py | add_job | def add_job():
"""Adds a new job."""
data = request.get_json(force=True)
try:
job = current_app.apscheduler.add_job(**data)
return jsonify(job)
except ConflictingIdError:
return jsonify(dict(error_message='Job %s already exists.' % data.get('id')), status=409)
except Exception as e:
return jsonify(dict(error_message=str(e)), status=500) | python | def add_job():
"""Adds a new job."""
data = request.get_json(force=True)
try:
job = current_app.apscheduler.add_job(**data)
return jsonify(job)
except ConflictingIdError:
return jsonify(dict(error_message='Job %s already exists.' % data.get('id')), status=409)
except Exception as e:
return jsonify(dict(error_message=str(e)), status=500) | [
"def",
"add_job",
"(",
")",
":",
"data",
"=",
"request",
".",
"get_json",
"(",
"force",
"=",
"True",
")",
"try",
":",
"job",
"=",
"current_app",
".",
"apscheduler",
".",
"add_job",
"(",
"*",
"*",
"data",
")",
"return",
"jsonify",
"(",
"job",
")",
"... | Adds a new job. | [
"Adds",
"a",
"new",
"job",
"."
] | cc52c39e1948c4e8de5da0d01db45f1779f61997 | https://github.com/viniciuschiele/flask-apscheduler/blob/cc52c39e1948c4e8de5da0d01db45f1779f61997/flask_apscheduler/api.py#L35-L46 | train | 226,535 |
viniciuschiele/flask-apscheduler | flask_apscheduler/api.py | get_job | def get_job(job_id):
"""Gets a job."""
job = current_app.apscheduler.get_job(job_id)
if not job:
return jsonify(dict(error_message='Job %s not found' % job_id), status=404)
return jsonify(job) | python | def get_job(job_id):
"""Gets a job."""
job = current_app.apscheduler.get_job(job_id)
if not job:
return jsonify(dict(error_message='Job %s not found' % job_id), status=404)
return jsonify(job) | [
"def",
"get_job",
"(",
"job_id",
")",
":",
"job",
"=",
"current_app",
".",
"apscheduler",
".",
"get_job",
"(",
"job_id",
")",
"if",
"not",
"job",
":",
"return",
"jsonify",
"(",
"dict",
"(",
"error_message",
"=",
"'Job %s not found'",
"%",
"job_id",
")",
... | Gets a job. | [
"Gets",
"a",
"job",
"."
] | cc52c39e1948c4e8de5da0d01db45f1779f61997 | https://github.com/viniciuschiele/flask-apscheduler/blob/cc52c39e1948c4e8de5da0d01db45f1779f61997/flask_apscheduler/api.py#L61-L69 | train | 226,536 |
viniciuschiele/flask-apscheduler | flask_apscheduler/api.py | get_jobs | def get_jobs():
"""Gets all scheduled jobs."""
jobs = current_app.apscheduler.get_jobs()
job_states = []
for job in jobs:
job_states.append(job)
return jsonify(job_states) | python | def get_jobs():
"""Gets all scheduled jobs."""
jobs = current_app.apscheduler.get_jobs()
job_states = []
for job in jobs:
job_states.append(job)
return jsonify(job_states) | [
"def",
"get_jobs",
"(",
")",
":",
"jobs",
"=",
"current_app",
".",
"apscheduler",
".",
"get_jobs",
"(",
")",
"job_states",
"=",
"[",
"]",
"for",
"job",
"in",
"jobs",
":",
"job_states",
".",
"append",
"(",
"job",
")",
"return",
"jsonify",
"(",
"job_stat... | Gets all scheduled jobs. | [
"Gets",
"all",
"scheduled",
"jobs",
"."
] | cc52c39e1948c4e8de5da0d01db45f1779f61997 | https://github.com/viniciuschiele/flask-apscheduler/blob/cc52c39e1948c4e8de5da0d01db45f1779f61997/flask_apscheduler/api.py#L72-L82 | train | 226,537 |
viniciuschiele/flask-apscheduler | flask_apscheduler/api.py | update_job | def update_job(job_id):
"""Updates a job."""
data = request.get_json(force=True)
try:
current_app.apscheduler.modify_job(job_id, **data)
job = current_app.apscheduler.get_job(job_id)
return jsonify(job)
except JobLookupError:
return jsonify(dict(error_message='Job %s not found' % job_id), status=404)
except Exception as e:
return jsonify(dict(error_message=str(e)), status=500) | python | def update_job(job_id):
"""Updates a job."""
data = request.get_json(force=True)
try:
current_app.apscheduler.modify_job(job_id, **data)
job = current_app.apscheduler.get_job(job_id)
return jsonify(job)
except JobLookupError:
return jsonify(dict(error_message='Job %s not found' % job_id), status=404)
except Exception as e:
return jsonify(dict(error_message=str(e)), status=500) | [
"def",
"update_job",
"(",
"job_id",
")",
":",
"data",
"=",
"request",
".",
"get_json",
"(",
"force",
"=",
"True",
")",
"try",
":",
"current_app",
".",
"apscheduler",
".",
"modify_job",
"(",
"job_id",
",",
"*",
"*",
"data",
")",
"job",
"=",
"current_app... | Updates a job. | [
"Updates",
"a",
"job",
"."
] | cc52c39e1948c4e8de5da0d01db45f1779f61997 | https://github.com/viniciuschiele/flask-apscheduler/blob/cc52c39e1948c4e8de5da0d01db45f1779f61997/flask_apscheduler/api.py#L85-L97 | train | 226,538 |
viniciuschiele/flask-apscheduler | flask_apscheduler/api.py | resume_job | def resume_job(job_id):
"""Resumes a job."""
try:
current_app.apscheduler.resume_job(job_id)
job = current_app.apscheduler.get_job(job_id)
return jsonify(job)
except JobLookupError:
return jsonify(dict(error_message='Job %s not found' % job_id), status=404)
except Exception as e:
return jsonify(dict(error_message=str(e)), status=500) | python | def resume_job(job_id):
"""Resumes a job."""
try:
current_app.apscheduler.resume_job(job_id)
job = current_app.apscheduler.get_job(job_id)
return jsonify(job)
except JobLookupError:
return jsonify(dict(error_message='Job %s not found' % job_id), status=404)
except Exception as e:
return jsonify(dict(error_message=str(e)), status=500) | [
"def",
"resume_job",
"(",
"job_id",
")",
":",
"try",
":",
"current_app",
".",
"apscheduler",
".",
"resume_job",
"(",
"job_id",
")",
"job",
"=",
"current_app",
".",
"apscheduler",
".",
"get_job",
"(",
"job_id",
")",
"return",
"jsonify",
"(",
"job",
")",
"... | Resumes a job. | [
"Resumes",
"a",
"job",
"."
] | cc52c39e1948c4e8de5da0d01db45f1779f61997 | https://github.com/viniciuschiele/flask-apscheduler/blob/cc52c39e1948c4e8de5da0d01db45f1779f61997/flask_apscheduler/api.py#L113-L123 | train | 226,539 |
pgjones/quart | quart/cli.py | QuartGroup.get_command | def get_command(self, ctx: click.Context, name: str) -> click.Command:
"""Return the relevant command given the context and name.
.. warning::
This differs substaintially from Flask in that it allows
for the inbuilt commands to be overridden.
"""
info = ctx.ensure_object(ScriptInfo)
command = None
try:
command = info.load_app().cli.get_command(ctx, name)
except NoAppException:
pass
if command is None:
command = super().get_command(ctx, name)
return command | python | def get_command(self, ctx: click.Context, name: str) -> click.Command:
"""Return the relevant command given the context and name.
.. warning::
This differs substaintially from Flask in that it allows
for the inbuilt commands to be overridden.
"""
info = ctx.ensure_object(ScriptInfo)
command = None
try:
command = info.load_app().cli.get_command(ctx, name)
except NoAppException:
pass
if command is None:
command = super().get_command(ctx, name)
return command | [
"def",
"get_command",
"(",
"self",
",",
"ctx",
":",
"click",
".",
"Context",
",",
"name",
":",
"str",
")",
"->",
"click",
".",
"Command",
":",
"info",
"=",
"ctx",
".",
"ensure_object",
"(",
"ScriptInfo",
")",
"command",
"=",
"None",
"try",
":",
"comm... | Return the relevant command given the context and name.
.. warning::
This differs substaintially from Flask in that it allows
for the inbuilt commands to be overridden. | [
"Return",
"the",
"relevant",
"command",
"given",
"the",
"context",
"and",
"name",
"."
] | 7cb2d3bd98e8746025764f2b933abc12041fa175 | https://github.com/pgjones/quart/blob/7cb2d3bd98e8746025764f2b933abc12041fa175/quart/cli.py#L155-L171 | train | 226,540 |
pgjones/quart | quart/templating.py | render_template | async def render_template(template_name_or_list: Union[str, List[str]], **context: Any) -> str:
"""Render the template with the context given.
Arguments:
template_name_or_list: Template name to render of a list of
possible template names.
context: The variables to pass to the template.
"""
await current_app.update_template_context(context)
template = current_app.jinja_env.get_or_select_template(template_name_or_list)
return await _render(template, context) | python | async def render_template(template_name_or_list: Union[str, List[str]], **context: Any) -> str:
"""Render the template with the context given.
Arguments:
template_name_or_list: Template name to render of a list of
possible template names.
context: The variables to pass to the template.
"""
await current_app.update_template_context(context)
template = current_app.jinja_env.get_or_select_template(template_name_or_list)
return await _render(template, context) | [
"async",
"def",
"render_template",
"(",
"template_name_or_list",
":",
"Union",
"[",
"str",
",",
"List",
"[",
"str",
"]",
"]",
",",
"*",
"*",
"context",
":",
"Any",
")",
"->",
"str",
":",
"await",
"current_app",
".",
"update_template_context",
"(",
"context... | Render the template with the context given.
Arguments:
template_name_or_list: Template name to render of a list of
possible template names.
context: The variables to pass to the template. | [
"Render",
"the",
"template",
"with",
"the",
"context",
"given",
"."
] | 7cb2d3bd98e8746025764f2b933abc12041fa175 | https://github.com/pgjones/quart/blob/7cb2d3bd98e8746025764f2b933abc12041fa175/quart/templating.py#L79-L89 | train | 226,541 |
pgjones/quart | quart/templating.py | render_template_string | async def render_template_string(source: str, **context: Any) -> str:
"""Render the template source with the context given.
Arguments:
source: The template source code.
context: The variables to pass to the template.
"""
await current_app.update_template_context(context)
template = current_app.jinja_env.from_string(source)
return await _render(template, context) | python | async def render_template_string(source: str, **context: Any) -> str:
"""Render the template source with the context given.
Arguments:
source: The template source code.
context: The variables to pass to the template.
"""
await current_app.update_template_context(context)
template = current_app.jinja_env.from_string(source)
return await _render(template, context) | [
"async",
"def",
"render_template_string",
"(",
"source",
":",
"str",
",",
"*",
"*",
"context",
":",
"Any",
")",
"->",
"str",
":",
"await",
"current_app",
".",
"update_template_context",
"(",
"context",
")",
"template",
"=",
"current_app",
".",
"jinja_env",
"... | Render the template source with the context given.
Arguments:
source: The template source code.
context: The variables to pass to the template. | [
"Render",
"the",
"template",
"source",
"with",
"the",
"context",
"given",
"."
] | 7cb2d3bd98e8746025764f2b933abc12041fa175 | https://github.com/pgjones/quart/blob/7cb2d3bd98e8746025764f2b933abc12041fa175/quart/templating.py#L92-L101 | train | 226,542 |
pgjones/quart | quart/templating.py | DispatchingJinjaLoader.get_source | def get_source(
self, environment: Environment, template: str,
) -> Tuple[str, Optional[str], Callable]:
"""Returns the template source from the environment.
This considers the loaders on the :attr:`app` and blueprints.
"""
for loader in self._loaders():
try:
return loader.get_source(environment, template)
except TemplateNotFound:
continue
raise TemplateNotFound(template) | python | def get_source(
self, environment: Environment, template: str,
) -> Tuple[str, Optional[str], Callable]:
"""Returns the template source from the environment.
This considers the loaders on the :attr:`app` and blueprints.
"""
for loader in self._loaders():
try:
return loader.get_source(environment, template)
except TemplateNotFound:
continue
raise TemplateNotFound(template) | [
"def",
"get_source",
"(",
"self",
",",
"environment",
":",
"Environment",
",",
"template",
":",
"str",
",",
")",
"->",
"Tuple",
"[",
"str",
",",
"Optional",
"[",
"str",
"]",
",",
"Callable",
"]",
":",
"for",
"loader",
"in",
"self",
".",
"_loaders",
"... | Returns the template source from the environment.
This considers the loaders on the :attr:`app` and blueprints. | [
"Returns",
"the",
"template",
"source",
"from",
"the",
"environment",
"."
] | 7cb2d3bd98e8746025764f2b933abc12041fa175 | https://github.com/pgjones/quart/blob/7cb2d3bd98e8746025764f2b933abc12041fa175/quart/templating.py#L43-L55 | train | 226,543 |
pgjones/quart | quart/templating.py | DispatchingJinjaLoader.list_templates | def list_templates(self) -> List[str]:
"""Returns a list of all avilable templates in environment.
This considers the loaders on the :attr:`app` and blueprints.
"""
result = set()
for loader in self._loaders():
for template in loader.list_templates():
result.add(str(template))
return list(result) | python | def list_templates(self) -> List[str]:
"""Returns a list of all avilable templates in environment.
This considers the loaders on the :attr:`app` and blueprints.
"""
result = set()
for loader in self._loaders():
for template in loader.list_templates():
result.add(str(template))
return list(result) | [
"def",
"list_templates",
"(",
"self",
")",
"->",
"List",
"[",
"str",
"]",
":",
"result",
"=",
"set",
"(",
")",
"for",
"loader",
"in",
"self",
".",
"_loaders",
"(",
")",
":",
"for",
"template",
"in",
"loader",
".",
"list_templates",
"(",
")",
":",
"... | Returns a list of all avilable templates in environment.
This considers the loaders on the :attr:`app` and blueprints. | [
"Returns",
"a",
"list",
"of",
"all",
"avilable",
"templates",
"in",
"environment",
"."
] | 7cb2d3bd98e8746025764f2b933abc12041fa175 | https://github.com/pgjones/quart/blob/7cb2d3bd98e8746025764f2b933abc12041fa175/quart/templating.py#L67-L76 | train | 226,544 |
pgjones/quart | quart/blueprints.py | Blueprint.route | def route(
self,
path: str,
methods: Optional[List[str]]=None,
endpoint: Optional[str]=None,
defaults: Optional[dict]=None,
host: Optional[str]=None,
subdomain: Optional[str]=None,
*,
provide_automatic_options: Optional[bool]=None,
strict_slashes: bool=True,
) -> Callable:
"""Add a route to the blueprint.
This is designed to be used as a decorator, and has the same arguments
as :meth:`~quart.Quart.route`. An example usage,
.. code-block:: python
blueprint = Blueprint(__name__)
@blueprint.route('/')
def route():
...
"""
def decorator(func: Callable) -> Callable:
self.add_url_rule(
path, endpoint, func, methods, defaults=defaults, host=host, subdomain=subdomain,
provide_automatic_options=provide_automatic_options, strict_slashes=strict_slashes,
)
return func
return decorator | python | def route(
self,
path: str,
methods: Optional[List[str]]=None,
endpoint: Optional[str]=None,
defaults: Optional[dict]=None,
host: Optional[str]=None,
subdomain: Optional[str]=None,
*,
provide_automatic_options: Optional[bool]=None,
strict_slashes: bool=True,
) -> Callable:
"""Add a route to the blueprint.
This is designed to be used as a decorator, and has the same arguments
as :meth:`~quart.Quart.route`. An example usage,
.. code-block:: python
blueprint = Blueprint(__name__)
@blueprint.route('/')
def route():
...
"""
def decorator(func: Callable) -> Callable:
self.add_url_rule(
path, endpoint, func, methods, defaults=defaults, host=host, subdomain=subdomain,
provide_automatic_options=provide_automatic_options, strict_slashes=strict_slashes,
)
return func
return decorator | [
"def",
"route",
"(",
"self",
",",
"path",
":",
"str",
",",
"methods",
":",
"Optional",
"[",
"List",
"[",
"str",
"]",
"]",
"=",
"None",
",",
"endpoint",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
",",
"defaults",
":",
"Optional",
"[",
"dict",
... | Add a route to the blueprint.
This is designed to be used as a decorator, and has the same arguments
as :meth:`~quart.Quart.route`. An example usage,
.. code-block:: python
blueprint = Blueprint(__name__)
@blueprint.route('/')
def route():
... | [
"Add",
"a",
"route",
"to",
"the",
"blueprint",
"."
] | 7cb2d3bd98e8746025764f2b933abc12041fa175 | https://github.com/pgjones/quart/blob/7cb2d3bd98e8746025764f2b933abc12041fa175/quart/blueprints.py#L53-L83 | train | 226,545 |
pgjones/quart | quart/blueprints.py | Blueprint.websocket | def websocket(
self,
path: str,
endpoint: Optional[str]=None,
defaults: Optional[dict]=None,
host: Optional[str]=None,
subdomain: Optional[str]=None,
*,
strict_slashes: bool=True,
) -> Callable:
"""Add a websocket to the blueprint.
This is designed to be used as a decorator, and has the same arguments
as :meth:`~quart.Quart.websocket`. An example usage,
.. code-block:: python
blueprint = Blueprint(__name__)
@blueprint.websocket('/')
async def route():
...
"""
def decorator(func: Callable) -> Callable:
self.add_websocket(
path, endpoint, func, defaults=defaults, host=host, subdomain=subdomain,
strict_slashes=strict_slashes,
)
return func
return decorator | python | def websocket(
self,
path: str,
endpoint: Optional[str]=None,
defaults: Optional[dict]=None,
host: Optional[str]=None,
subdomain: Optional[str]=None,
*,
strict_slashes: bool=True,
) -> Callable:
"""Add a websocket to the blueprint.
This is designed to be used as a decorator, and has the same arguments
as :meth:`~quart.Quart.websocket`. An example usage,
.. code-block:: python
blueprint = Blueprint(__name__)
@blueprint.websocket('/')
async def route():
...
"""
def decorator(func: Callable) -> Callable:
self.add_websocket(
path, endpoint, func, defaults=defaults, host=host, subdomain=subdomain,
strict_slashes=strict_slashes,
)
return func
return decorator | [
"def",
"websocket",
"(",
"self",
",",
"path",
":",
"str",
",",
"endpoint",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
",",
"defaults",
":",
"Optional",
"[",
"dict",
"]",
"=",
"None",
",",
"host",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
... | Add a websocket to the blueprint.
This is designed to be used as a decorator, and has the same arguments
as :meth:`~quart.Quart.websocket`. An example usage,
.. code-block:: python
blueprint = Blueprint(__name__)
@blueprint.websocket('/')
async def route():
... | [
"Add",
"a",
"websocket",
"to",
"the",
"blueprint",
"."
] | 7cb2d3bd98e8746025764f2b933abc12041fa175 | https://github.com/pgjones/quart/blob/7cb2d3bd98e8746025764f2b933abc12041fa175/quart/blueprints.py#L124-L152 | train | 226,546 |
pgjones/quart | quart/blueprints.py | Blueprint.add_websocket | def add_websocket(
self,
path: str,
endpoint: Optional[str]=None,
view_func: Optional[Callable]=None,
defaults: Optional[dict]=None,
host: Optional[str]=None,
subdomain: Optional[str]=None,
*,
strict_slashes: bool=True,
) -> None:
"""Add a websocket rule to the blueprint.
This is designed to be used on the blueprint directly, and
has the same arguments as
:meth:`~quart.Quart.add_websocket`. An example usage,
.. code-block:: python
def route():
...
blueprint = Blueprint(__name__)
blueprint.add_websocket('/', route)
"""
return self.add_url_rule(
path, endpoint, view_func, {'GET'}, defaults=defaults, host=host, subdomain=subdomain,
provide_automatic_options=False, is_websocket=True, strict_slashes=strict_slashes,
) | python | def add_websocket(
self,
path: str,
endpoint: Optional[str]=None,
view_func: Optional[Callable]=None,
defaults: Optional[dict]=None,
host: Optional[str]=None,
subdomain: Optional[str]=None,
*,
strict_slashes: bool=True,
) -> None:
"""Add a websocket rule to the blueprint.
This is designed to be used on the blueprint directly, and
has the same arguments as
:meth:`~quart.Quart.add_websocket`. An example usage,
.. code-block:: python
def route():
...
blueprint = Blueprint(__name__)
blueprint.add_websocket('/', route)
"""
return self.add_url_rule(
path, endpoint, view_func, {'GET'}, defaults=defaults, host=host, subdomain=subdomain,
provide_automatic_options=False, is_websocket=True, strict_slashes=strict_slashes,
) | [
"def",
"add_websocket",
"(",
"self",
",",
"path",
":",
"str",
",",
"endpoint",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
",",
"view_func",
":",
"Optional",
"[",
"Callable",
"]",
"=",
"None",
",",
"defaults",
":",
"Optional",
"[",
"dict",
"]",
"=... | Add a websocket rule to the blueprint.
This is designed to be used on the blueprint directly, and
has the same arguments as
:meth:`~quart.Quart.add_websocket`. An example usage,
.. code-block:: python
def route():
...
blueprint = Blueprint(__name__)
blueprint.add_websocket('/', route) | [
"Add",
"a",
"websocket",
"rule",
"to",
"the",
"blueprint",
"."
] | 7cb2d3bd98e8746025764f2b933abc12041fa175 | https://github.com/pgjones/quart/blob/7cb2d3bd98e8746025764f2b933abc12041fa175/quart/blueprints.py#L154-L182 | train | 226,547 |
pgjones/quart | quart/blueprints.py | Blueprint.endpoint | def endpoint(self, endpoint: str) -> Callable:
"""Add an endpoint to the blueprint.
This is designed to be used as a decorator, and has the same arguments
as :meth:`~quart.Quart.endpoint`. An example usage,
.. code-block:: python
blueprint = Blueprint(__name__)
@blueprint.endpoint('index')
def index():
...
"""
def decorator(func: Callable) -> Callable:
self.record_once(lambda state: state.register_endpoint(endpoint, func))
return func
return decorator | python | def endpoint(self, endpoint: str) -> Callable:
"""Add an endpoint to the blueprint.
This is designed to be used as a decorator, and has the same arguments
as :meth:`~quart.Quart.endpoint`. An example usage,
.. code-block:: python
blueprint = Blueprint(__name__)
@blueprint.endpoint('index')
def index():
...
"""
def decorator(func: Callable) -> Callable:
self.record_once(lambda state: state.register_endpoint(endpoint, func))
return func
return decorator | [
"def",
"endpoint",
"(",
"self",
",",
"endpoint",
":",
"str",
")",
"->",
"Callable",
":",
"def",
"decorator",
"(",
"func",
":",
"Callable",
")",
"->",
"Callable",
":",
"self",
".",
"record_once",
"(",
"lambda",
"state",
":",
"state",
".",
"register_endpoi... | Add an endpoint to the blueprint.
This is designed to be used as a decorator, and has the same arguments
as :meth:`~quart.Quart.endpoint`. An example usage,
.. code-block:: python
blueprint = Blueprint(__name__)
@blueprint.endpoint('index')
def index():
... | [
"Add",
"an",
"endpoint",
"to",
"the",
"blueprint",
"."
] | 7cb2d3bd98e8746025764f2b933abc12041fa175 | https://github.com/pgjones/quart/blob/7cb2d3bd98e8746025764f2b933abc12041fa175/quart/blueprints.py#L184-L200 | train | 226,548 |
pgjones/quart | quart/blueprints.py | Blueprint.before_request | def before_request(self, func: Callable) -> Callable:
"""Add a before request function to the Blueprint.
This is designed to be used as a decorator, and has the same arguments
as :meth:`~quart.Quart.before_request`. It applies only to requests that
are routed to an endpoint in this blueprint. An example usage,
.. code-block:: python
blueprint = Blueprint(__name__)
@blueprint.before_request
def before():
...
"""
self.record_once(lambda state: state.app.before_request(func, self.name))
return func | python | def before_request(self, func: Callable) -> Callable:
"""Add a before request function to the Blueprint.
This is designed to be used as a decorator, and has the same arguments
as :meth:`~quart.Quart.before_request`. It applies only to requests that
are routed to an endpoint in this blueprint. An example usage,
.. code-block:: python
blueprint = Blueprint(__name__)
@blueprint.before_request
def before():
...
"""
self.record_once(lambda state: state.app.before_request(func, self.name))
return func | [
"def",
"before_request",
"(",
"self",
",",
"func",
":",
"Callable",
")",
"->",
"Callable",
":",
"self",
".",
"record_once",
"(",
"lambda",
"state",
":",
"state",
".",
"app",
".",
"before_request",
"(",
"func",
",",
"self",
".",
"name",
")",
")",
"retur... | Add a before request function to the Blueprint.
This is designed to be used as a decorator, and has the same arguments
as :meth:`~quart.Quart.before_request`. It applies only to requests that
are routed to an endpoint in this blueprint. An example usage,
.. code-block:: python
blueprint = Blueprint(__name__)
@blueprint.before_request
def before():
... | [
"Add",
"a",
"before",
"request",
"function",
"to",
"the",
"Blueprint",
"."
] | 7cb2d3bd98e8746025764f2b933abc12041fa175 | https://github.com/pgjones/quart/blob/7cb2d3bd98e8746025764f2b933abc12041fa175/quart/blueprints.py#L307-L322 | train | 226,549 |
pgjones/quart | quart/blueprints.py | Blueprint.before_websocket | def before_websocket(self, func: Callable) -> Callable:
"""Add a before request websocket to the Blueprint.
This is designed to be used as a decorator, and has the same arguments
as :meth:`~quart.Quart.before_websocket`. It applies only to requests that
are routed to an endpoint in this blueprint. An example usage,
.. code-block:: python
blueprint = Blueprint(__name__)
@blueprint.before_websocket
def before():
...
"""
self.record_once(lambda state: state.app.before_websocket(func, self.name))
return func | python | def before_websocket(self, func: Callable) -> Callable:
"""Add a before request websocket to the Blueprint.
This is designed to be used as a decorator, and has the same arguments
as :meth:`~quart.Quart.before_websocket`. It applies only to requests that
are routed to an endpoint in this blueprint. An example usage,
.. code-block:: python
blueprint = Blueprint(__name__)
@blueprint.before_websocket
def before():
...
"""
self.record_once(lambda state: state.app.before_websocket(func, self.name))
return func | [
"def",
"before_websocket",
"(",
"self",
",",
"func",
":",
"Callable",
")",
"->",
"Callable",
":",
"self",
".",
"record_once",
"(",
"lambda",
"state",
":",
"state",
".",
"app",
".",
"before_websocket",
"(",
"func",
",",
"self",
".",
"name",
")",
")",
"r... | Add a before request websocket to the Blueprint.
This is designed to be used as a decorator, and has the same arguments
as :meth:`~quart.Quart.before_websocket`. It applies only to requests that
are routed to an endpoint in this blueprint. An example usage,
.. code-block:: python
blueprint = Blueprint(__name__)
@blueprint.before_websocket
def before():
... | [
"Add",
"a",
"before",
"request",
"websocket",
"to",
"the",
"Blueprint",
"."
] | 7cb2d3bd98e8746025764f2b933abc12041fa175 | https://github.com/pgjones/quart/blob/7cb2d3bd98e8746025764f2b933abc12041fa175/quart/blueprints.py#L324-L340 | train | 226,550 |
pgjones/quart | quart/blueprints.py | Blueprint.before_app_request | def before_app_request(self, func: Callable) -> Callable:
"""Add a before request function to the app.
This is designed to be used as a decorator, and has the same arguments
as :meth:`~quart.Quart.before_request`. It applies to all requests to the
app this blueprint is registered on. An example usage,
.. code-block:: python
blueprint = Blueprint(__name__)
@blueprint.before_app_request
def before():
...
"""
self.record_once(lambda state: state.app.before_request(func))
return func | python | def before_app_request(self, func: Callable) -> Callable:
"""Add a before request function to the app.
This is designed to be used as a decorator, and has the same arguments
as :meth:`~quart.Quart.before_request`. It applies to all requests to the
app this blueprint is registered on. An example usage,
.. code-block:: python
blueprint = Blueprint(__name__)
@blueprint.before_app_request
def before():
...
"""
self.record_once(lambda state: state.app.before_request(func))
return func | [
"def",
"before_app_request",
"(",
"self",
",",
"func",
":",
"Callable",
")",
"->",
"Callable",
":",
"self",
".",
"record_once",
"(",
"lambda",
"state",
":",
"state",
".",
"app",
".",
"before_request",
"(",
"func",
")",
")",
"return",
"func"
] | Add a before request function to the app.
This is designed to be used as a decorator, and has the same arguments
as :meth:`~quart.Quart.before_request`. It applies to all requests to the
app this blueprint is registered on. An example usage,
.. code-block:: python
blueprint = Blueprint(__name__)
@blueprint.before_app_request
def before():
... | [
"Add",
"a",
"before",
"request",
"function",
"to",
"the",
"app",
"."
] | 7cb2d3bd98e8746025764f2b933abc12041fa175 | https://github.com/pgjones/quart/blob/7cb2d3bd98e8746025764f2b933abc12041fa175/quart/blueprints.py#L342-L357 | train | 226,551 |
pgjones/quart | quart/blueprints.py | Blueprint.before_app_websocket | def before_app_websocket(self, func: Callable) -> Callable:
"""Add a before request websocket to the App.
This is designed to be used as a decorator, and has the same arguments
as :meth:`~quart.Quart.before_websocket`. It applies to all requests to the
app this blueprint is registered on. An example usage,
.. code-block:: python
blueprint = Blueprint(__name__)
@blueprint.before_app_websocket
def before():
...
"""
self.record_once(lambda state: state.app.before_websocket(func))
return func | python | def before_app_websocket(self, func: Callable) -> Callable:
"""Add a before request websocket to the App.
This is designed to be used as a decorator, and has the same arguments
as :meth:`~quart.Quart.before_websocket`. It applies to all requests to the
app this blueprint is registered on. An example usage,
.. code-block:: python
blueprint = Blueprint(__name__)
@blueprint.before_app_websocket
def before():
...
"""
self.record_once(lambda state: state.app.before_websocket(func))
return func | [
"def",
"before_app_websocket",
"(",
"self",
",",
"func",
":",
"Callable",
")",
"->",
"Callable",
":",
"self",
".",
"record_once",
"(",
"lambda",
"state",
":",
"state",
".",
"app",
".",
"before_websocket",
"(",
"func",
")",
")",
"return",
"func"
] | Add a before request websocket to the App.
This is designed to be used as a decorator, and has the same arguments
as :meth:`~quart.Quart.before_websocket`. It applies to all requests to the
app this blueprint is registered on. An example usage,
.. code-block:: python
blueprint = Blueprint(__name__)
@blueprint.before_app_websocket
def before():
... | [
"Add",
"a",
"before",
"request",
"websocket",
"to",
"the",
"App",
"."
] | 7cb2d3bd98e8746025764f2b933abc12041fa175 | https://github.com/pgjones/quart/blob/7cb2d3bd98e8746025764f2b933abc12041fa175/quart/blueprints.py#L359-L375 | train | 226,552 |
pgjones/quart | quart/blueprints.py | Blueprint.before_app_first_request | def before_app_first_request(self, func: Callable) -> Callable:
"""Add a before request first function to the app.
This is designed to be used as a decorator, and has the same
arguments as :meth:`~quart.Quart.before_first_request`. It is
triggered before the first request to the app this blueprint
is registered on. An example usage,
.. code-block:: python
blueprint = Blueprint(__name__)
@blueprint.before_app_first_request
def before_first():
...
"""
self.record_once(lambda state: state.app.before_first_request(func))
return func | python | def before_app_first_request(self, func: Callable) -> Callable:
"""Add a before request first function to the app.
This is designed to be used as a decorator, and has the same
arguments as :meth:`~quart.Quart.before_first_request`. It is
triggered before the first request to the app this blueprint
is registered on. An example usage,
.. code-block:: python
blueprint = Blueprint(__name__)
@blueprint.before_app_first_request
def before_first():
...
"""
self.record_once(lambda state: state.app.before_first_request(func))
return func | [
"def",
"before_app_first_request",
"(",
"self",
",",
"func",
":",
"Callable",
")",
"->",
"Callable",
":",
"self",
".",
"record_once",
"(",
"lambda",
"state",
":",
"state",
".",
"app",
".",
"before_first_request",
"(",
"func",
")",
")",
"return",
"func"
] | Add a before request first function to the app.
This is designed to be used as a decorator, and has the same
arguments as :meth:`~quart.Quart.before_first_request`. It is
triggered before the first request to the app this blueprint
is registered on. An example usage,
.. code-block:: python
blueprint = Blueprint(__name__)
@blueprint.before_app_first_request
def before_first():
... | [
"Add",
"a",
"before",
"request",
"first",
"function",
"to",
"the",
"app",
"."
] | 7cb2d3bd98e8746025764f2b933abc12041fa175 | https://github.com/pgjones/quart/blob/7cb2d3bd98e8746025764f2b933abc12041fa175/quart/blueprints.py#L377-L394 | train | 226,553 |
pgjones/quart | quart/blueprints.py | Blueprint.after_request | def after_request(self, func: Callable) -> Callable:
"""Add an after request function to the Blueprint.
This is designed to be used as a decorator, and has the same arguments
as :meth:`~quart.Quart.after_request`. It applies only to requests that
are routed to an endpoint in this blueprint. An example usage,
.. code-block:: python
blueprint = Blueprint(__name__)
@blueprint.after_request
def after():
...
"""
self.record_once(lambda state: state.app.after_request(func, self.name))
return func | python | def after_request(self, func: Callable) -> Callable:
"""Add an after request function to the Blueprint.
This is designed to be used as a decorator, and has the same arguments
as :meth:`~quart.Quart.after_request`. It applies only to requests that
are routed to an endpoint in this blueprint. An example usage,
.. code-block:: python
blueprint = Blueprint(__name__)
@blueprint.after_request
def after():
...
"""
self.record_once(lambda state: state.app.after_request(func, self.name))
return func | [
"def",
"after_request",
"(",
"self",
",",
"func",
":",
"Callable",
")",
"->",
"Callable",
":",
"self",
".",
"record_once",
"(",
"lambda",
"state",
":",
"state",
".",
"app",
".",
"after_request",
"(",
"func",
",",
"self",
".",
"name",
")",
")",
"return"... | Add an after request function to the Blueprint.
This is designed to be used as a decorator, and has the same arguments
as :meth:`~quart.Quart.after_request`. It applies only to requests that
are routed to an endpoint in this blueprint. An example usage,
.. code-block:: python
blueprint = Blueprint(__name__)
@blueprint.after_request
def after():
... | [
"Add",
"an",
"after",
"request",
"function",
"to",
"the",
"Blueprint",
"."
] | 7cb2d3bd98e8746025764f2b933abc12041fa175 | https://github.com/pgjones/quart/blob/7cb2d3bd98e8746025764f2b933abc12041fa175/quart/blueprints.py#L396-L411 | train | 226,554 |
pgjones/quart | quart/blueprints.py | Blueprint.after_websocket | def after_websocket(self, func: Callable) -> Callable:
"""Add an after websocket function to the Blueprint.
This is designed to be used as a decorator, and has the same arguments
as :meth:`~quart.Quart.after_websocket`. It applies only to requests that
are routed to an endpoint in this blueprint. An example usage,
.. code-block:: python
blueprint = Blueprint(__name__)
@blueprint.after_websocket
def after():
...
"""
self.record_once(lambda state: state.app.after_websocket(func, self.name))
return func | python | def after_websocket(self, func: Callable) -> Callable:
"""Add an after websocket function to the Blueprint.
This is designed to be used as a decorator, and has the same arguments
as :meth:`~quart.Quart.after_websocket`. It applies only to requests that
are routed to an endpoint in this blueprint. An example usage,
.. code-block:: python
blueprint = Blueprint(__name__)
@blueprint.after_websocket
def after():
...
"""
self.record_once(lambda state: state.app.after_websocket(func, self.name))
return func | [
"def",
"after_websocket",
"(",
"self",
",",
"func",
":",
"Callable",
")",
"->",
"Callable",
":",
"self",
".",
"record_once",
"(",
"lambda",
"state",
":",
"state",
".",
"app",
".",
"after_websocket",
"(",
"func",
",",
"self",
".",
"name",
")",
")",
"ret... | Add an after websocket function to the Blueprint.
This is designed to be used as a decorator, and has the same arguments
as :meth:`~quart.Quart.after_websocket`. It applies only to requests that
are routed to an endpoint in this blueprint. An example usage,
.. code-block:: python
blueprint = Blueprint(__name__)
@blueprint.after_websocket
def after():
... | [
"Add",
"an",
"after",
"websocket",
"function",
"to",
"the",
"Blueprint",
"."
] | 7cb2d3bd98e8746025764f2b933abc12041fa175 | https://github.com/pgjones/quart/blob/7cb2d3bd98e8746025764f2b933abc12041fa175/quart/blueprints.py#L413-L428 | train | 226,555 |
pgjones/quart | quart/blueprints.py | Blueprint.after_app_request | def after_app_request(self, func: Callable) -> Callable:
"""Add a after request function to the app.
This is designed to be used as a decorator, and has the same arguments
as :meth:`~quart.Quart.after_request`. It applies to all requests to the
app this blueprint is registered on. An example usage,
.. code-block:: python
blueprint = Blueprint(__name__)
@blueprint.after_app_request
def after():
...
"""
self.record_once(lambda state: state.app.after_request(func))
return func | python | def after_app_request(self, func: Callable) -> Callable:
"""Add a after request function to the app.
This is designed to be used as a decorator, and has the same arguments
as :meth:`~quart.Quart.after_request`. It applies to all requests to the
app this blueprint is registered on. An example usage,
.. code-block:: python
blueprint = Blueprint(__name__)
@blueprint.after_app_request
def after():
...
"""
self.record_once(lambda state: state.app.after_request(func))
return func | [
"def",
"after_app_request",
"(",
"self",
",",
"func",
":",
"Callable",
")",
"->",
"Callable",
":",
"self",
".",
"record_once",
"(",
"lambda",
"state",
":",
"state",
".",
"app",
".",
"after_request",
"(",
"func",
")",
")",
"return",
"func"
] | Add a after request function to the app.
This is designed to be used as a decorator, and has the same arguments
as :meth:`~quart.Quart.after_request`. It applies to all requests to the
app this blueprint is registered on. An example usage,
.. code-block:: python
blueprint = Blueprint(__name__)
@blueprint.after_app_request
def after():
... | [
"Add",
"a",
"after",
"request",
"function",
"to",
"the",
"app",
"."
] | 7cb2d3bd98e8746025764f2b933abc12041fa175 | https://github.com/pgjones/quart/blob/7cb2d3bd98e8746025764f2b933abc12041fa175/quart/blueprints.py#L430-L445 | train | 226,556 |
pgjones/quart | quart/blueprints.py | Blueprint.after_app_websocket | def after_app_websocket(self, func: Callable) -> Callable:
"""Add an after websocket function to the App.
This is designed to be used as a decorator, and has the same arguments
as :meth:`~quart.Quart.after_websocket`. It applies to all requests to the
ppe this blueprint is registerd on. An example usage,
.. code-block:: python
blueprint = Blueprint(__name__)
@blueprint.after_app_websocket
def after():
...
"""
self.record_once(lambda state: state.app.after_websocket(func))
return func | python | def after_app_websocket(self, func: Callable) -> Callable:
"""Add an after websocket function to the App.
This is designed to be used as a decorator, and has the same arguments
as :meth:`~quart.Quart.after_websocket`. It applies to all requests to the
ppe this blueprint is registerd on. An example usage,
.. code-block:: python
blueprint = Blueprint(__name__)
@blueprint.after_app_websocket
def after():
...
"""
self.record_once(lambda state: state.app.after_websocket(func))
return func | [
"def",
"after_app_websocket",
"(",
"self",
",",
"func",
":",
"Callable",
")",
"->",
"Callable",
":",
"self",
".",
"record_once",
"(",
"lambda",
"state",
":",
"state",
".",
"app",
".",
"after_websocket",
"(",
"func",
")",
")",
"return",
"func"
] | Add an after websocket function to the App.
This is designed to be used as a decorator, and has the same arguments
as :meth:`~quart.Quart.after_websocket`. It applies to all requests to the
ppe this blueprint is registerd on. An example usage,
.. code-block:: python
blueprint = Blueprint(__name__)
@blueprint.after_app_websocket
def after():
... | [
"Add",
"an",
"after",
"websocket",
"function",
"to",
"the",
"App",
"."
] | 7cb2d3bd98e8746025764f2b933abc12041fa175 | https://github.com/pgjones/quart/blob/7cb2d3bd98e8746025764f2b933abc12041fa175/quart/blueprints.py#L447-L462 | train | 226,557 |
pgjones/quart | quart/blueprints.py | Blueprint.teardown_request | def teardown_request(self, func: Callable) -> Callable:
"""Add a teardown request function to the Blueprint.
This is designed to be used as a decorator, and has the same arguments
as :meth:`~quart.Quart.teardown_request`. It applies only to requests that
are routed to an endpoint in this blueprint. An example usage,
.. code-block:: python
blueprint = Blueprint(__name__)
@blueprint.teardown_request
def teardown():
...
"""
self.record_once(lambda state: state.app.teardown_request(func, self.name))
return func | python | def teardown_request(self, func: Callable) -> Callable:
"""Add a teardown request function to the Blueprint.
This is designed to be used as a decorator, and has the same arguments
as :meth:`~quart.Quart.teardown_request`. It applies only to requests that
are routed to an endpoint in this blueprint. An example usage,
.. code-block:: python
blueprint = Blueprint(__name__)
@blueprint.teardown_request
def teardown():
...
"""
self.record_once(lambda state: state.app.teardown_request(func, self.name))
return func | [
"def",
"teardown_request",
"(",
"self",
",",
"func",
":",
"Callable",
")",
"->",
"Callable",
":",
"self",
".",
"record_once",
"(",
"lambda",
"state",
":",
"state",
".",
"app",
".",
"teardown_request",
"(",
"func",
",",
"self",
".",
"name",
")",
")",
"r... | Add a teardown request function to the Blueprint.
This is designed to be used as a decorator, and has the same arguments
as :meth:`~quart.Quart.teardown_request`. It applies only to requests that
are routed to an endpoint in this blueprint. An example usage,
.. code-block:: python
blueprint = Blueprint(__name__)
@blueprint.teardown_request
def teardown():
... | [
"Add",
"a",
"teardown",
"request",
"function",
"to",
"the",
"Blueprint",
"."
] | 7cb2d3bd98e8746025764f2b933abc12041fa175 | https://github.com/pgjones/quart/blob/7cb2d3bd98e8746025764f2b933abc12041fa175/quart/blueprints.py#L464-L479 | train | 226,558 |
pgjones/quart | quart/blueprints.py | Blueprint.teardown_websocket | def teardown_websocket(self, func: Callable) -> Callable:
"""Add a teardown websocket function to the Blueprint.
This is designed to be used as a decorator, and has the same
arguments as :meth:`~quart.Quart.teardown_websocket`. It
applies only to requests that are routed to an endpoint in
this blueprint. An example usage,
.. code-block:: python
blueprint = Blueprint(__name__)
@blueprint.teardown_websocket
def teardown():
...
"""
self.record_once(lambda state: state.app.teardown_websocket(func, self.name))
return func | python | def teardown_websocket(self, func: Callable) -> Callable:
"""Add a teardown websocket function to the Blueprint.
This is designed to be used as a decorator, and has the same
arguments as :meth:`~quart.Quart.teardown_websocket`. It
applies only to requests that are routed to an endpoint in
this blueprint. An example usage,
.. code-block:: python
blueprint = Blueprint(__name__)
@blueprint.teardown_websocket
def teardown():
...
"""
self.record_once(lambda state: state.app.teardown_websocket(func, self.name))
return func | [
"def",
"teardown_websocket",
"(",
"self",
",",
"func",
":",
"Callable",
")",
"->",
"Callable",
":",
"self",
".",
"record_once",
"(",
"lambda",
"state",
":",
"state",
".",
"app",
".",
"teardown_websocket",
"(",
"func",
",",
"self",
".",
"name",
")",
")",
... | Add a teardown websocket function to the Blueprint.
This is designed to be used as a decorator, and has the same
arguments as :meth:`~quart.Quart.teardown_websocket`. It
applies only to requests that are routed to an endpoint in
this blueprint. An example usage,
.. code-block:: python
blueprint = Blueprint(__name__)
@blueprint.teardown_websocket
def teardown():
... | [
"Add",
"a",
"teardown",
"websocket",
"function",
"to",
"the",
"Blueprint",
"."
] | 7cb2d3bd98e8746025764f2b933abc12041fa175 | https://github.com/pgjones/quart/blob/7cb2d3bd98e8746025764f2b933abc12041fa175/quart/blueprints.py#L481-L498 | train | 226,559 |
pgjones/quart | quart/blueprints.py | Blueprint.teardown_app_request | def teardown_app_request(self, func: Callable) -> Callable:
"""Add a teardown request function to the app.
This is designed to be used as a decorator, and has the same
arguments as :meth:`~quart.Quart.teardown_request`. It applies
to all requests to the app this blueprint is registered on. An
example usage,
.. code-block:: python
blueprint = Blueprint(__name__)
@blueprint.teardown_app_request
def teardown():
...
"""
self.record_once(lambda state: state.app.teardown_request(func))
return func | python | def teardown_app_request(self, func: Callable) -> Callable:
"""Add a teardown request function to the app.
This is designed to be used as a decorator, and has the same
arguments as :meth:`~quart.Quart.teardown_request`. It applies
to all requests to the app this blueprint is registered on. An
example usage,
.. code-block:: python
blueprint = Blueprint(__name__)
@blueprint.teardown_app_request
def teardown():
...
"""
self.record_once(lambda state: state.app.teardown_request(func))
return func | [
"def",
"teardown_app_request",
"(",
"self",
",",
"func",
":",
"Callable",
")",
"->",
"Callable",
":",
"self",
".",
"record_once",
"(",
"lambda",
"state",
":",
"state",
".",
"app",
".",
"teardown_request",
"(",
"func",
")",
")",
"return",
"func"
] | Add a teardown request function to the app.
This is designed to be used as a decorator, and has the same
arguments as :meth:`~quart.Quart.teardown_request`. It applies
to all requests to the app this blueprint is registered on. An
example usage,
.. code-block:: python
blueprint = Blueprint(__name__)
@blueprint.teardown_app_request
def teardown():
... | [
"Add",
"a",
"teardown",
"request",
"function",
"to",
"the",
"app",
"."
] | 7cb2d3bd98e8746025764f2b933abc12041fa175 | https://github.com/pgjones/quart/blob/7cb2d3bd98e8746025764f2b933abc12041fa175/quart/blueprints.py#L500-L516 | train | 226,560 |
pgjones/quart | quart/blueprints.py | Blueprint.errorhandler | def errorhandler(self, error: Union[Type[Exception], int]) -> Callable:
"""Add an error handler function to the Blueprint.
This is designed to be used as a decorator, and has the same
arguments as :meth:`~quart.Quart.errorhandler`. It applies
only to errors that originate in routes in this blueprint. An
example usage,
.. code-block:: python
blueprint = Blueprint(__name__)
@blueprint.errorhandler(404)
def not_found():
...
"""
def decorator(func: Callable) -> Callable:
self.register_error_handler(error, func)
return func
return decorator | python | def errorhandler(self, error: Union[Type[Exception], int]) -> Callable:
"""Add an error handler function to the Blueprint.
This is designed to be used as a decorator, and has the same
arguments as :meth:`~quart.Quart.errorhandler`. It applies
only to errors that originate in routes in this blueprint. An
example usage,
.. code-block:: python
blueprint = Blueprint(__name__)
@blueprint.errorhandler(404)
def not_found():
...
"""
def decorator(func: Callable) -> Callable:
self.register_error_handler(error, func)
return func
return decorator | [
"def",
"errorhandler",
"(",
"self",
",",
"error",
":",
"Union",
"[",
"Type",
"[",
"Exception",
"]",
",",
"int",
"]",
")",
"->",
"Callable",
":",
"def",
"decorator",
"(",
"func",
":",
"Callable",
")",
"->",
"Callable",
":",
"self",
".",
"register_error_... | Add an error handler function to the Blueprint.
This is designed to be used as a decorator, and has the same
arguments as :meth:`~quart.Quart.errorhandler`. It applies
only to errors that originate in routes in this blueprint. An
example usage,
.. code-block:: python
blueprint = Blueprint(__name__)
@blueprint.errorhandler(404)
def not_found():
... | [
"Add",
"an",
"error",
"handler",
"function",
"to",
"the",
"Blueprint",
"."
] | 7cb2d3bd98e8746025764f2b933abc12041fa175 | https://github.com/pgjones/quart/blob/7cb2d3bd98e8746025764f2b933abc12041fa175/quart/blueprints.py#L518-L537 | train | 226,561 |
pgjones/quart | quart/blueprints.py | Blueprint.app_errorhandler | def app_errorhandler(self, error: Union[Type[Exception], int]) -> Callable:
"""Add an error handler function to the App.
This is designed to be used as a decorator, and has the same
arguments as :meth:`~quart.Quart.errorhandler`. It applies
only to all errors. An example usage,
.. code-block:: python
blueprint = Blueprint(__name__)
@blueprint.app_errorhandler(404)
def not_found():
...
"""
def decorator(func: Callable) -> Callable:
self.record_once(lambda state: state.app.register_error_handler(error, func))
return func
return decorator | python | def app_errorhandler(self, error: Union[Type[Exception], int]) -> Callable:
"""Add an error handler function to the App.
This is designed to be used as a decorator, and has the same
arguments as :meth:`~quart.Quart.errorhandler`. It applies
only to all errors. An example usage,
.. code-block:: python
blueprint = Blueprint(__name__)
@blueprint.app_errorhandler(404)
def not_found():
...
"""
def decorator(func: Callable) -> Callable:
self.record_once(lambda state: state.app.register_error_handler(error, func))
return func
return decorator | [
"def",
"app_errorhandler",
"(",
"self",
",",
"error",
":",
"Union",
"[",
"Type",
"[",
"Exception",
"]",
",",
"int",
"]",
")",
"->",
"Callable",
":",
"def",
"decorator",
"(",
"func",
":",
"Callable",
")",
"->",
"Callable",
":",
"self",
".",
"record_once... | Add an error handler function to the App.
This is designed to be used as a decorator, and has the same
arguments as :meth:`~quart.Quart.errorhandler`. It applies
only to all errors. An example usage,
.. code-block:: python
blueprint = Blueprint(__name__)
@blueprint.app_errorhandler(404)
def not_found():
... | [
"Add",
"an",
"error",
"handler",
"function",
"to",
"the",
"App",
"."
] | 7cb2d3bd98e8746025764f2b933abc12041fa175 | https://github.com/pgjones/quart/blob/7cb2d3bd98e8746025764f2b933abc12041fa175/quart/blueprints.py#L539-L556 | train | 226,562 |
pgjones/quart | quart/blueprints.py | Blueprint.register_error_handler | def register_error_handler(self, error: Union[Type[Exception], int], func: Callable) -> None:
"""Add an error handler function to the blueprint.
This is designed to be used on the blueprint directly, and
has the same arguments as
:meth:`~quart.Quart.register_error_handler`. An example usage,
.. code-block:: python
def not_found():
...
blueprint = Blueprint(__name__)
blueprint.register_error_handler(404, not_found)
"""
self.record_once(lambda state: state.app.register_error_handler(error, func, self.name)) | python | def register_error_handler(self, error: Union[Type[Exception], int], func: Callable) -> None:
"""Add an error handler function to the blueprint.
This is designed to be used on the blueprint directly, and
has the same arguments as
:meth:`~quart.Quart.register_error_handler`. An example usage,
.. code-block:: python
def not_found():
...
blueprint = Blueprint(__name__)
blueprint.register_error_handler(404, not_found)
"""
self.record_once(lambda state: state.app.register_error_handler(error, func, self.name)) | [
"def",
"register_error_handler",
"(",
"self",
",",
"error",
":",
"Union",
"[",
"Type",
"[",
"Exception",
"]",
",",
"int",
"]",
",",
"func",
":",
"Callable",
")",
"->",
"None",
":",
"self",
".",
"record_once",
"(",
"lambda",
"state",
":",
"state",
".",
... | Add an error handler function to the blueprint.
This is designed to be used on the blueprint directly, and
has the same arguments as
:meth:`~quart.Quart.register_error_handler`. An example usage,
.. code-block:: python
def not_found():
...
blueprint = Blueprint(__name__)
blueprint.register_error_handler(404, not_found) | [
"Add",
"an",
"error",
"handler",
"function",
"to",
"the",
"blueprint",
"."
] | 7cb2d3bd98e8746025764f2b933abc12041fa175 | https://github.com/pgjones/quart/blob/7cb2d3bd98e8746025764f2b933abc12041fa175/quart/blueprints.py#L558-L573 | train | 226,563 |
pgjones/quart | quart/blueprints.py | Blueprint.context_processor | def context_processor(self, func: Callable) -> Callable:
"""Add a context processor function to this blueprint.
This is designed to be used as a decorator, and has the same
arguments as :meth:`~quart.Quart.context_processor`. This will
add context to all templates rendered in this blueprint's
routes. An example usage,
.. code-block:: python
blueprint = Blueprint(__name__)
@blueprint.context_processor
def processor():
...
"""
self.record_once(lambda state: state.app.context_processor(func, self.name))
return func | python | def context_processor(self, func: Callable) -> Callable:
"""Add a context processor function to this blueprint.
This is designed to be used as a decorator, and has the same
arguments as :meth:`~quart.Quart.context_processor`. This will
add context to all templates rendered in this blueprint's
routes. An example usage,
.. code-block:: python
blueprint = Blueprint(__name__)
@blueprint.context_processor
def processor():
...
"""
self.record_once(lambda state: state.app.context_processor(func, self.name))
return func | [
"def",
"context_processor",
"(",
"self",
",",
"func",
":",
"Callable",
")",
"->",
"Callable",
":",
"self",
".",
"record_once",
"(",
"lambda",
"state",
":",
"state",
".",
"app",
".",
"context_processor",
"(",
"func",
",",
"self",
".",
"name",
")",
")",
... | Add a context processor function to this blueprint.
This is designed to be used as a decorator, and has the same
arguments as :meth:`~quart.Quart.context_processor`. This will
add context to all templates rendered in this blueprint's
routes. An example usage,
.. code-block:: python
blueprint = Blueprint(__name__)
@blueprint.context_processor
def processor():
... | [
"Add",
"a",
"context",
"processor",
"function",
"to",
"this",
"blueprint",
"."
] | 7cb2d3bd98e8746025764f2b933abc12041fa175 | https://github.com/pgjones/quart/blob/7cb2d3bd98e8746025764f2b933abc12041fa175/quart/blueprints.py#L575-L591 | train | 226,564 |
pgjones/quart | quart/blueprints.py | Blueprint.app_context_processor | def app_context_processor(self, func: Callable) -> Callable:
"""Add a context processor function to the app.
This is designed to be used as a decorator, and has the same
arguments as :meth:`~quart.Quart.context_processor`. This will
add context to all templates rendered. An example usage,
.. code-block:: python
blueprint = Blueprint(__name__)
@blueprint.app_context_processor
def processor():
...
"""
self.record_once(lambda state: state.app.context_processor(func))
return func | python | def app_context_processor(self, func: Callable) -> Callable:
"""Add a context processor function to the app.
This is designed to be used as a decorator, and has the same
arguments as :meth:`~quart.Quart.context_processor`. This will
add context to all templates rendered. An example usage,
.. code-block:: python
blueprint = Blueprint(__name__)
@blueprint.app_context_processor
def processor():
...
"""
self.record_once(lambda state: state.app.context_processor(func))
return func | [
"def",
"app_context_processor",
"(",
"self",
",",
"func",
":",
"Callable",
")",
"->",
"Callable",
":",
"self",
".",
"record_once",
"(",
"lambda",
"state",
":",
"state",
".",
"app",
".",
"context_processor",
"(",
"func",
")",
")",
"return",
"func"
] | Add a context processor function to the app.
This is designed to be used as a decorator, and has the same
arguments as :meth:`~quart.Quart.context_processor`. This will
add context to all templates rendered. An example usage,
.. code-block:: python
blueprint = Blueprint(__name__)
@blueprint.app_context_processor
def processor():
... | [
"Add",
"a",
"context",
"processor",
"function",
"to",
"the",
"app",
"."
] | 7cb2d3bd98e8746025764f2b933abc12041fa175 | https://github.com/pgjones/quart/blob/7cb2d3bd98e8746025764f2b933abc12041fa175/quart/blueprints.py#L593-L608 | train | 226,565 |
pgjones/quart | quart/blueprints.py | Blueprint.record_once | def record_once(self, func: DeferedSetupFunction) -> None:
"""Used to register a deferred action that happens only once."""
def wrapper(state: 'BlueprintSetupState') -> None:
if state.first_registration:
func(state)
self.record(update_wrapper(wrapper, func)) | python | def record_once(self, func: DeferedSetupFunction) -> None:
"""Used to register a deferred action that happens only once."""
def wrapper(state: 'BlueprintSetupState') -> None:
if state.first_registration:
func(state)
self.record(update_wrapper(wrapper, func)) | [
"def",
"record_once",
"(",
"self",
",",
"func",
":",
"DeferedSetupFunction",
")",
"->",
"None",
":",
"def",
"wrapper",
"(",
"state",
":",
"'BlueprintSetupState'",
")",
"->",
"None",
":",
"if",
"state",
".",
"first_registration",
":",
"func",
"(",
"state",
... | Used to register a deferred action that happens only once. | [
"Used",
"to",
"register",
"a",
"deferred",
"action",
"that",
"happens",
"only",
"once",
"."
] | 7cb2d3bd98e8746025764f2b933abc12041fa175 | https://github.com/pgjones/quart/blob/7cb2d3bd98e8746025764f2b933abc12041fa175/quart/blueprints.py#L687-L692 | train | 226,566 |
pgjones/quart | quart/blueprints.py | Blueprint.register | def register(
self,
app: 'Quart',
first_registration: bool,
*,
url_prefix: Optional[str]=None,
) -> None:
"""Register this blueprint on the app given."""
state = self.make_setup_state(app, first_registration, url_prefix=url_prefix)
if self.has_static_folder:
state.add_url_rule(
self.static_url_path + '/<path:filename>',
view_func=self.send_static_file, endpoint='static',
)
for func in self.deferred_functions:
func(state) | python | def register(
self,
app: 'Quart',
first_registration: bool,
*,
url_prefix: Optional[str]=None,
) -> None:
"""Register this blueprint on the app given."""
state = self.make_setup_state(app, first_registration, url_prefix=url_prefix)
if self.has_static_folder:
state.add_url_rule(
self.static_url_path + '/<path:filename>',
view_func=self.send_static_file, endpoint='static',
)
for func in self.deferred_functions:
func(state) | [
"def",
"register",
"(",
"self",
",",
"app",
":",
"'Quart'",
",",
"first_registration",
":",
"bool",
",",
"*",
",",
"url_prefix",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
",",
")",
"->",
"None",
":",
"state",
"=",
"self",
".",
"make_setup_state",
... | Register this blueprint on the app given. | [
"Register",
"this",
"blueprint",
"on",
"the",
"app",
"given",
"."
] | 7cb2d3bd98e8746025764f2b933abc12041fa175 | https://github.com/pgjones/quart/blob/7cb2d3bd98e8746025764f2b933abc12041fa175/quart/blueprints.py#L694-L711 | train | 226,567 |
pgjones/quart | quart/blueprints.py | Blueprint.make_setup_state | def make_setup_state(
self,
app: 'Quart',
first_registration: bool,
*,
url_prefix: Optional[str]=None,
) -> 'BlueprintSetupState':
"""Return a blueprint setup state instance.
Arguments:
first_registration: True if this is the first registration
of this blueprint on the app.
url_prefix: An optional prefix to all rules
"""
return BlueprintSetupState(self, app, first_registration, url_prefix=url_prefix) | python | def make_setup_state(
self,
app: 'Quart',
first_registration: bool,
*,
url_prefix: Optional[str]=None,
) -> 'BlueprintSetupState':
"""Return a blueprint setup state instance.
Arguments:
first_registration: True if this is the first registration
of this blueprint on the app.
url_prefix: An optional prefix to all rules
"""
return BlueprintSetupState(self, app, first_registration, url_prefix=url_prefix) | [
"def",
"make_setup_state",
"(",
"self",
",",
"app",
":",
"'Quart'",
",",
"first_registration",
":",
"bool",
",",
"*",
",",
"url_prefix",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
",",
")",
"->",
"'BlueprintSetupState'",
":",
"return",
"BlueprintSetupSta... | Return a blueprint setup state instance.
Arguments:
first_registration: True if this is the first registration
of this blueprint on the app.
url_prefix: An optional prefix to all rules | [
"Return",
"a",
"blueprint",
"setup",
"state",
"instance",
"."
] | 7cb2d3bd98e8746025764f2b933abc12041fa175 | https://github.com/pgjones/quart/blob/7cb2d3bd98e8746025764f2b933abc12041fa175/quart/blueprints.py#L713-L727 | train | 226,568 |
pgjones/quart | quart/datastructures.py | _WerkzeugMultidictMixin.to_dict | def to_dict(self, flat: bool=True) -> Dict[Any, Any]:
"""Convert the multidict to a plain dictionary.
Arguments:
flat: If True only return the a value for each key, if
False return all values as lists.
"""
if flat:
return {key: value for key, value in self.items()} # type: ignore
else:
return {key: self.getall(key) for key in self} | python | def to_dict(self, flat: bool=True) -> Dict[Any, Any]:
"""Convert the multidict to a plain dictionary.
Arguments:
flat: If True only return the a value for each key, if
False return all values as lists.
"""
if flat:
return {key: value for key, value in self.items()} # type: ignore
else:
return {key: self.getall(key) for key in self} | [
"def",
"to_dict",
"(",
"self",
",",
"flat",
":",
"bool",
"=",
"True",
")",
"->",
"Dict",
"[",
"Any",
",",
"Any",
"]",
":",
"if",
"flat",
":",
"return",
"{",
"key",
":",
"value",
"for",
"key",
",",
"value",
"in",
"self",
".",
"items",
"(",
")",
... | Convert the multidict to a plain dictionary.
Arguments:
flat: If True only return the a value for each key, if
False return all values as lists. | [
"Convert",
"the",
"multidict",
"to",
"a",
"plain",
"dictionary",
"."
] | 7cb2d3bd98e8746025764f2b933abc12041fa175 | https://github.com/pgjones/quart/blob/7cb2d3bd98e8746025764f2b933abc12041fa175/quart/datastructures.py#L42-L53 | train | 226,569 |
pgjones/quart | quart/datastructures.py | FileStorage.save | def save(self, destination: BinaryIO, buffer_size: int=16384) -> None:
"""Save the file to the destination.
Arguments:
destination: A filename (str) or file object to write to.
buffer_size: Buffer size as used as length in
:func:`shutil.copyfileobj`.
"""
close_destination = False
if isinstance(destination, str):
destination = open(destination, 'wb')
close_destination = True
try:
copyfileobj(self.stream, destination, buffer_size)
finally:
if close_destination:
destination.close() | python | def save(self, destination: BinaryIO, buffer_size: int=16384) -> None:
"""Save the file to the destination.
Arguments:
destination: A filename (str) or file object to write to.
buffer_size: Buffer size as used as length in
:func:`shutil.copyfileobj`.
"""
close_destination = False
if isinstance(destination, str):
destination = open(destination, 'wb')
close_destination = True
try:
copyfileobj(self.stream, destination, buffer_size)
finally:
if close_destination:
destination.close() | [
"def",
"save",
"(",
"self",
",",
"destination",
":",
"BinaryIO",
",",
"buffer_size",
":",
"int",
"=",
"16384",
")",
"->",
"None",
":",
"close_destination",
"=",
"False",
"if",
"isinstance",
"(",
"destination",
",",
"str",
")",
":",
"destination",
"=",
"o... | Save the file to the destination.
Arguments:
destination: A filename (str) or file object to write to.
buffer_size: Buffer size as used as length in
:func:`shutil.copyfileobj`. | [
"Save",
"the",
"file",
"to",
"the",
"destination",
"."
] | 7cb2d3bd98e8746025764f2b933abc12041fa175 | https://github.com/pgjones/quart/blob/7cb2d3bd98e8746025764f2b933abc12041fa175/quart/datastructures.py#L136-L152 | train | 226,570 |
pgjones/quart | quart/wrappers/request.py | Request.get_data | async def get_data(self, raw: bool=True) -> AnyStr:
"""The request body data."""
try:
body_future = asyncio.ensure_future(self.body)
raw_data = await asyncio.wait_for(body_future, timeout=self.body_timeout)
except asyncio.TimeoutError:
body_future.cancel()
from ..exceptions import RequestTimeout # noqa Avoiding circular import
raise RequestTimeout()
if raw:
return raw_data
else:
return raw_data.decode(self.charset) | python | async def get_data(self, raw: bool=True) -> AnyStr:
"""The request body data."""
try:
body_future = asyncio.ensure_future(self.body)
raw_data = await asyncio.wait_for(body_future, timeout=self.body_timeout)
except asyncio.TimeoutError:
body_future.cancel()
from ..exceptions import RequestTimeout # noqa Avoiding circular import
raise RequestTimeout()
if raw:
return raw_data
else:
return raw_data.decode(self.charset) | [
"async",
"def",
"get_data",
"(",
"self",
",",
"raw",
":",
"bool",
"=",
"True",
")",
"->",
"AnyStr",
":",
"try",
":",
"body_future",
"=",
"asyncio",
".",
"ensure_future",
"(",
"self",
".",
"body",
")",
"raw_data",
"=",
"await",
"asyncio",
".",
"wait_for... | The request body data. | [
"The",
"request",
"body",
"data",
"."
] | 7cb2d3bd98e8746025764f2b933abc12041fa175 | https://github.com/pgjones/quart/blob/7cb2d3bd98e8746025764f2b933abc12041fa175/quart/wrappers/request.py#L158-L171 | train | 226,571 |
pgjones/quart | quart/wrappers/request.py | Websocket.accept | async def accept(
self,
headers: Optional[Union[dict, CIMultiDict, Headers]] = None,
subprotocol: Optional[str] = None,
) -> None:
"""Manually chose to accept the websocket connection.
Arguments:
headers: Additional headers to send with the acceptance
response.
subprotocol: The chosen subprotocol, optional.
"""
if headers is None:
headers_ = Headers()
else:
headers_ = Headers(headers)
await self._accept(headers_, subprotocol) | python | async def accept(
self,
headers: Optional[Union[dict, CIMultiDict, Headers]] = None,
subprotocol: Optional[str] = None,
) -> None:
"""Manually chose to accept the websocket connection.
Arguments:
headers: Additional headers to send with the acceptance
response.
subprotocol: The chosen subprotocol, optional.
"""
if headers is None:
headers_ = Headers()
else:
headers_ = Headers(headers)
await self._accept(headers_, subprotocol) | [
"async",
"def",
"accept",
"(",
"self",
",",
"headers",
":",
"Optional",
"[",
"Union",
"[",
"dict",
",",
"CIMultiDict",
",",
"Headers",
"]",
"]",
"=",
"None",
",",
"subprotocol",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
",",
")",
"->",
"None",
... | Manually chose to accept the websocket connection.
Arguments:
headers: Additional headers to send with the acceptance
response.
subprotocol: The chosen subprotocol, optional. | [
"Manually",
"chose",
"to",
"accept",
"the",
"websocket",
"connection",
"."
] | 7cb2d3bd98e8746025764f2b933abc12041fa175 | https://github.com/pgjones/quart/blob/7cb2d3bd98e8746025764f2b933abc12041fa175/quart/wrappers/request.py#L326-L342 | train | 226,572 |
pgjones/quart | quart/logging.py | create_logger | def create_logger(app: 'Quart') -> Logger:
"""Create a logger for the app based on the app settings.
This creates a logger named quart.app that has a log level based
on the app configuration.
"""
logger = getLogger('quart.app')
if app.debug and logger.level == NOTSET:
logger.setLevel(DEBUG)
logger.addHandler(default_handler)
return logger | python | def create_logger(app: 'Quart') -> Logger:
"""Create a logger for the app based on the app settings.
This creates a logger named quart.app that has a log level based
on the app configuration.
"""
logger = getLogger('quart.app')
if app.debug and logger.level == NOTSET:
logger.setLevel(DEBUG)
logger.addHandler(default_handler)
return logger | [
"def",
"create_logger",
"(",
"app",
":",
"'Quart'",
")",
"->",
"Logger",
":",
"logger",
"=",
"getLogger",
"(",
"'quart.app'",
")",
"if",
"app",
".",
"debug",
"and",
"logger",
".",
"level",
"==",
"NOTSET",
":",
"logger",
".",
"setLevel",
"(",
"DEBUG",
"... | Create a logger for the app based on the app settings.
This creates a logger named quart.app that has a log level based
on the app configuration. | [
"Create",
"a",
"logger",
"for",
"the",
"app",
"based",
"on",
"the",
"app",
"settings",
"."
] | 7cb2d3bd98e8746025764f2b933abc12041fa175 | https://github.com/pgjones/quart/blob/7cb2d3bd98e8746025764f2b933abc12041fa175/quart/logging.py#L15-L27 | train | 226,573 |
pgjones/quart | quart/logging.py | create_serving_logger | def create_serving_logger() -> Logger:
"""Create a logger for serving.
This creates a logger named quart.serving.
"""
logger = getLogger('quart.serving')
if logger.level == NOTSET:
logger.setLevel(INFO)
logger.addHandler(serving_handler)
return logger | python | def create_serving_logger() -> Logger:
"""Create a logger for serving.
This creates a logger named quart.serving.
"""
logger = getLogger('quart.serving')
if logger.level == NOTSET:
logger.setLevel(INFO)
logger.addHandler(serving_handler)
return logger | [
"def",
"create_serving_logger",
"(",
")",
"->",
"Logger",
":",
"logger",
"=",
"getLogger",
"(",
"'quart.serving'",
")",
"if",
"logger",
".",
"level",
"==",
"NOTSET",
":",
"logger",
".",
"setLevel",
"(",
"INFO",
")",
"logger",
".",
"addHandler",
"(",
"servi... | Create a logger for serving.
This creates a logger named quart.serving. | [
"Create",
"a",
"logger",
"for",
"serving",
"."
] | 7cb2d3bd98e8746025764f2b933abc12041fa175 | https://github.com/pgjones/quart/blob/7cb2d3bd98e8746025764f2b933abc12041fa175/quart/logging.py#L30-L41 | train | 226,574 |
pgjones/quart | quart/utils.py | create_cookie | def create_cookie(
key: str,
value: str='',
max_age: Optional[Union[int, timedelta]]=None,
expires: Optional[Union[int, float, datetime]]=None,
path: str='/',
domain: Optional[str]=None,
secure: bool=False,
httponly: bool=False,
) -> SimpleCookie:
"""Create a Cookie given the options set
The arguments are the standard cookie morsels and this is a
wrapper around the stdlib SimpleCookie code.
"""
cookie = SimpleCookie()
cookie[key] = value
cookie[key]['path'] = path
cookie[key]['httponly'] = httponly # type: ignore
cookie[key]['secure'] = secure # type: ignore
if isinstance(max_age, timedelta):
cookie[key]['max-age'] = f"{max_age.total_seconds():d}"
if isinstance(max_age, int):
cookie[key]['max-age'] = str(max_age)
if expires is not None and isinstance(expires, (int, float)):
cookie[key]['expires'] = format_date_time(int(expires))
elif expires is not None and isinstance(expires, datetime):
cookie[key]['expires'] = format_date_time(expires.replace(tzinfo=timezone.utc).timestamp())
if domain is not None:
cookie[key]['domain'] = domain
return cookie | python | def create_cookie(
key: str,
value: str='',
max_age: Optional[Union[int, timedelta]]=None,
expires: Optional[Union[int, float, datetime]]=None,
path: str='/',
domain: Optional[str]=None,
secure: bool=False,
httponly: bool=False,
) -> SimpleCookie:
"""Create a Cookie given the options set
The arguments are the standard cookie morsels and this is a
wrapper around the stdlib SimpleCookie code.
"""
cookie = SimpleCookie()
cookie[key] = value
cookie[key]['path'] = path
cookie[key]['httponly'] = httponly # type: ignore
cookie[key]['secure'] = secure # type: ignore
if isinstance(max_age, timedelta):
cookie[key]['max-age'] = f"{max_age.total_seconds():d}"
if isinstance(max_age, int):
cookie[key]['max-age'] = str(max_age)
if expires is not None and isinstance(expires, (int, float)):
cookie[key]['expires'] = format_date_time(int(expires))
elif expires is not None and isinstance(expires, datetime):
cookie[key]['expires'] = format_date_time(expires.replace(tzinfo=timezone.utc).timestamp())
if domain is not None:
cookie[key]['domain'] = domain
return cookie | [
"def",
"create_cookie",
"(",
"key",
":",
"str",
",",
"value",
":",
"str",
"=",
"''",
",",
"max_age",
":",
"Optional",
"[",
"Union",
"[",
"int",
",",
"timedelta",
"]",
"]",
"=",
"None",
",",
"expires",
":",
"Optional",
"[",
"Union",
"[",
"int",
",",... | Create a Cookie given the options set
The arguments are the standard cookie morsels and this is a
wrapper around the stdlib SimpleCookie code. | [
"Create",
"a",
"Cookie",
"given",
"the",
"options",
"set"
] | 7cb2d3bd98e8746025764f2b933abc12041fa175 | https://github.com/pgjones/quart/blob/7cb2d3bd98e8746025764f2b933abc12041fa175/quart/utils.py#L29-L59 | train | 226,575 |
pgjones/quart | quart/app.py | Quart.name | def name(self) -> str:
"""The name of this application.
This is taken from the :attr:`import_name` and is used for
debugging purposes.
"""
if self.import_name == '__main__':
path = Path(getattr(sys.modules['__main__'], '__file__', '__main__.py'))
return path.stem
return self.import_name | python | def name(self) -> str:
"""The name of this application.
This is taken from the :attr:`import_name` and is used for
debugging purposes.
"""
if self.import_name == '__main__':
path = Path(getattr(sys.modules['__main__'], '__file__', '__main__.py'))
return path.stem
return self.import_name | [
"def",
"name",
"(",
"self",
")",
"->",
"str",
":",
"if",
"self",
".",
"import_name",
"==",
"'__main__'",
":",
"path",
"=",
"Path",
"(",
"getattr",
"(",
"sys",
".",
"modules",
"[",
"'__main__'",
"]",
",",
"'__file__'",
",",
"'__main__.py'",
")",
")",
... | The name of this application.
This is taken from the :attr:`import_name` and is used for
debugging purposes. | [
"The",
"name",
"of",
"this",
"application",
"."
] | 7cb2d3bd98e8746025764f2b933abc12041fa175 | https://github.com/pgjones/quart/blob/7cb2d3bd98e8746025764f2b933abc12041fa175/quart/app.py#L223-L232 | train | 226,576 |
pgjones/quart | quart/app.py | Quart.jinja_env | def jinja_env(self) -> Environment:
"""The jinja environment used to load templates."""
if self._jinja_env is None:
self._jinja_env = self.create_jinja_environment()
return self._jinja_env | python | def jinja_env(self) -> Environment:
"""The jinja environment used to load templates."""
if self._jinja_env is None:
self._jinja_env = self.create_jinja_environment()
return self._jinja_env | [
"def",
"jinja_env",
"(",
"self",
")",
"->",
"Environment",
":",
"if",
"self",
".",
"_jinja_env",
"is",
"None",
":",
"self",
".",
"_jinja_env",
"=",
"self",
".",
"create_jinja_environment",
"(",
")",
"return",
"self",
".",
"_jinja_env"
] | The jinja environment used to load templates. | [
"The",
"jinja",
"environment",
"used",
"to",
"load",
"templates",
"."
] | 7cb2d3bd98e8746025764f2b933abc12041fa175 | https://github.com/pgjones/quart/blob/7cb2d3bd98e8746025764f2b933abc12041fa175/quart/app.py#L261-L265 | train | 226,577 |
pgjones/quart | quart/app.py | Quart.auto_find_instance_path | def auto_find_instance_path(self) -> Path:
"""Locates the instace_path if it was not provided
"""
prefix, package_path = find_package(self.import_name)
if prefix is None:
return package_path / "instance"
return prefix / "var" / f"{self.name}-instance" | python | def auto_find_instance_path(self) -> Path:
"""Locates the instace_path if it was not provided
"""
prefix, package_path = find_package(self.import_name)
if prefix is None:
return package_path / "instance"
return prefix / "var" / f"{self.name}-instance" | [
"def",
"auto_find_instance_path",
"(",
"self",
")",
"->",
"Path",
":",
"prefix",
",",
"package_path",
"=",
"find_package",
"(",
"self",
".",
"import_name",
")",
"if",
"prefix",
"is",
"None",
":",
"return",
"package_path",
"/",
"\"instance\"",
"return",
"prefix... | Locates the instace_path if it was not provided | [
"Locates",
"the",
"instace_path",
"if",
"it",
"was",
"not",
"provided"
] | 7cb2d3bd98e8746025764f2b933abc12041fa175 | https://github.com/pgjones/quart/blob/7cb2d3bd98e8746025764f2b933abc12041fa175/quart/app.py#L272-L278 | train | 226,578 |
pgjones/quart | quart/app.py | Quart.make_config | def make_config(self, instance_relative: bool = False) -> Config:
"""Create and return the configuration with appropriate defaults."""
config = self.config_class(
self.instance_path if instance_relative else self.root_path,
DEFAULT_CONFIG,
)
config['ENV'] = get_env()
config['DEBUG'] = get_debug_flag()
return config | python | def make_config(self, instance_relative: bool = False) -> Config:
"""Create and return the configuration with appropriate defaults."""
config = self.config_class(
self.instance_path if instance_relative else self.root_path,
DEFAULT_CONFIG,
)
config['ENV'] = get_env()
config['DEBUG'] = get_debug_flag()
return config | [
"def",
"make_config",
"(",
"self",
",",
"instance_relative",
":",
"bool",
"=",
"False",
")",
"->",
"Config",
":",
"config",
"=",
"self",
".",
"config_class",
"(",
"self",
".",
"instance_path",
"if",
"instance_relative",
"else",
"self",
".",
"root_path",
",",... | Create and return the configuration with appropriate defaults. | [
"Create",
"and",
"return",
"the",
"configuration",
"with",
"appropriate",
"defaults",
"."
] | 7cb2d3bd98e8746025764f2b933abc12041fa175 | https://github.com/pgjones/quart/blob/7cb2d3bd98e8746025764f2b933abc12041fa175/quart/app.py#L280-L288 | train | 226,579 |
pgjones/quart | quart/app.py | Quart.create_url_adapter | def create_url_adapter(self, request: Optional[BaseRequestWebsocket]) -> Optional[MapAdapter]:
"""Create and return a URL adapter.
This will create the adapter based on the request if present
otherwise the app configuration.
"""
if request is not None:
host = request.host
return self.url_map.bind_to_request(
request.scheme, host, request.method, request.path, request.query_string,
)
if self.config['SERVER_NAME'] is not None:
return self.url_map.bind(
self.config['PREFERRED_URL_SCHEME'], self.config['SERVER_NAME'],
)
return None | python | def create_url_adapter(self, request: Optional[BaseRequestWebsocket]) -> Optional[MapAdapter]:
"""Create and return a URL adapter.
This will create the adapter based on the request if present
otherwise the app configuration.
"""
if request is not None:
host = request.host
return self.url_map.bind_to_request(
request.scheme, host, request.method, request.path, request.query_string,
)
if self.config['SERVER_NAME'] is not None:
return self.url_map.bind(
self.config['PREFERRED_URL_SCHEME'], self.config['SERVER_NAME'],
)
return None | [
"def",
"create_url_adapter",
"(",
"self",
",",
"request",
":",
"Optional",
"[",
"BaseRequestWebsocket",
"]",
")",
"->",
"Optional",
"[",
"MapAdapter",
"]",
":",
"if",
"request",
"is",
"not",
"None",
":",
"host",
"=",
"request",
".",
"host",
"return",
"self... | Create and return a URL adapter.
This will create the adapter based on the request if present
otherwise the app configuration. | [
"Create",
"and",
"return",
"a",
"URL",
"adapter",
"."
] | 7cb2d3bd98e8746025764f2b933abc12041fa175 | https://github.com/pgjones/quart/blob/7cb2d3bd98e8746025764f2b933abc12041fa175/quart/app.py#L302-L318 | train | 226,580 |
pgjones/quart | quart/app.py | Quart.create_jinja_environment | def create_jinja_environment(self) -> Environment:
"""Create and return the jinja environment.
This will create the environment based on the
:attr:`jinja_options` and configuration settings. The
environment will include the Quart globals by default.
"""
options = dict(self.jinja_options)
if 'autoescape' not in options:
options['autoescape'] = self.select_jinja_autoescape
if 'auto_reload' not in options:
options['auto_reload'] = self.config['TEMPLATES_AUTO_RELOAD'] or self.debug
jinja_env = self.jinja_environment(self, **options)
jinja_env.globals.update({
'config': self.config,
'g': g,
'get_flashed_messages': get_flashed_messages,
'request': request,
'session': session,
'url_for': url_for,
})
jinja_env.filters['tojson'] = tojson_filter
return jinja_env | python | def create_jinja_environment(self) -> Environment:
"""Create and return the jinja environment.
This will create the environment based on the
:attr:`jinja_options` and configuration settings. The
environment will include the Quart globals by default.
"""
options = dict(self.jinja_options)
if 'autoescape' not in options:
options['autoescape'] = self.select_jinja_autoescape
if 'auto_reload' not in options:
options['auto_reload'] = self.config['TEMPLATES_AUTO_RELOAD'] or self.debug
jinja_env = self.jinja_environment(self, **options)
jinja_env.globals.update({
'config': self.config,
'g': g,
'get_flashed_messages': get_flashed_messages,
'request': request,
'session': session,
'url_for': url_for,
})
jinja_env.filters['tojson'] = tojson_filter
return jinja_env | [
"def",
"create_jinja_environment",
"(",
"self",
")",
"->",
"Environment",
":",
"options",
"=",
"dict",
"(",
"self",
".",
"jinja_options",
")",
"if",
"'autoescape'",
"not",
"in",
"options",
":",
"options",
"[",
"'autoescape'",
"]",
"=",
"self",
".",
"select_j... | Create and return the jinja environment.
This will create the environment based on the
:attr:`jinja_options` and configuration settings. The
environment will include the Quart globals by default. | [
"Create",
"and",
"return",
"the",
"jinja",
"environment",
"."
] | 7cb2d3bd98e8746025764f2b933abc12041fa175 | https://github.com/pgjones/quart/blob/7cb2d3bd98e8746025764f2b933abc12041fa175/quart/app.py#L320-L342 | train | 226,581 |
pgjones/quart | quart/app.py | Quart.select_jinja_autoescape | def select_jinja_autoescape(self, filename: str) -> bool:
"""Returns True if the filename indicates that it should be escaped."""
if filename is None:
return True
return Path(filename).suffix in {'.htm', '.html', '.xhtml', '.xml'} | python | def select_jinja_autoescape(self, filename: str) -> bool:
"""Returns True if the filename indicates that it should be escaped."""
if filename is None:
return True
return Path(filename).suffix in {'.htm', '.html', '.xhtml', '.xml'} | [
"def",
"select_jinja_autoescape",
"(",
"self",
",",
"filename",
":",
"str",
")",
"->",
"bool",
":",
"if",
"filename",
"is",
"None",
":",
"return",
"True",
"return",
"Path",
"(",
"filename",
")",
".",
"suffix",
"in",
"{",
"'.htm'",
",",
"'.html'",
",",
... | Returns True if the filename indicates that it should be escaped. | [
"Returns",
"True",
"if",
"the",
"filename",
"indicates",
"that",
"it",
"should",
"be",
"escaped",
"."
] | 7cb2d3bd98e8746025764f2b933abc12041fa175 | https://github.com/pgjones/quart/blob/7cb2d3bd98e8746025764f2b933abc12041fa175/quart/app.py#L348-L352 | train | 226,582 |
pgjones/quart | quart/app.py | Quart.update_template_context | async def update_template_context(self, context: dict) -> None:
"""Update the provided template context.
This adds additional context from the various template context
processors.
Arguments:
context: The context to update (mutate).
"""
processors = self.template_context_processors[None]
if has_request_context():
blueprint = _request_ctx_stack.top.request.blueprint
if blueprint is not None and blueprint in self.template_context_processors:
processors = chain(processors, self.template_context_processors[blueprint]) # type: ignore # noqa
extra_context: dict = {}
for processor in processors:
extra_context.update(await processor())
original = context.copy()
context.update(extra_context)
context.update(original) | python | async def update_template_context(self, context: dict) -> None:
"""Update the provided template context.
This adds additional context from the various template context
processors.
Arguments:
context: The context to update (mutate).
"""
processors = self.template_context_processors[None]
if has_request_context():
blueprint = _request_ctx_stack.top.request.blueprint
if blueprint is not None and blueprint in self.template_context_processors:
processors = chain(processors, self.template_context_processors[blueprint]) # type: ignore # noqa
extra_context: dict = {}
for processor in processors:
extra_context.update(await processor())
original = context.copy()
context.update(extra_context)
context.update(original) | [
"async",
"def",
"update_template_context",
"(",
"self",
",",
"context",
":",
"dict",
")",
"->",
"None",
":",
"processors",
"=",
"self",
".",
"template_context_processors",
"[",
"None",
"]",
"if",
"has_request_context",
"(",
")",
":",
"blueprint",
"=",
"_reques... | Update the provided template context.
This adds additional context from the various template context
processors.
Arguments:
context: The context to update (mutate). | [
"Update",
"the",
"provided",
"template",
"context",
"."
] | 7cb2d3bd98e8746025764f2b933abc12041fa175 | https://github.com/pgjones/quart/blob/7cb2d3bd98e8746025764f2b933abc12041fa175/quart/app.py#L354-L373 | train | 226,583 |
pgjones/quart | quart/app.py | Quart.make_shell_context | def make_shell_context(self) -> dict:
"""Create a context for interactive shell usage.
The :attr:`shell_context_processors` can be used to add
additional context.
"""
context = {'app': self, 'g': g}
for processor in self.shell_context_processors:
context.update(processor())
return context | python | def make_shell_context(self) -> dict:
"""Create a context for interactive shell usage.
The :attr:`shell_context_processors` can be used to add
additional context.
"""
context = {'app': self, 'g': g}
for processor in self.shell_context_processors:
context.update(processor())
return context | [
"def",
"make_shell_context",
"(",
"self",
")",
"->",
"dict",
":",
"context",
"=",
"{",
"'app'",
":",
"self",
",",
"'g'",
":",
"g",
"}",
"for",
"processor",
"in",
"self",
".",
"shell_context_processors",
":",
"context",
".",
"update",
"(",
"processor",
"(... | Create a context for interactive shell usage.
The :attr:`shell_context_processors` can be used to add
additional context. | [
"Create",
"a",
"context",
"for",
"interactive",
"shell",
"usage",
"."
] | 7cb2d3bd98e8746025764f2b933abc12041fa175 | https://github.com/pgjones/quart/blob/7cb2d3bd98e8746025764f2b933abc12041fa175/quart/app.py#L375-L384 | train | 226,584 |
pgjones/quart | quart/app.py | Quart.endpoint | def endpoint(self, endpoint: str) -> Callable:
"""Register a function as an endpoint.
This is designed to be used as a decorator. An example usage,
.. code-block:: python
@app.endpoint('name')
def endpoint():
...
Arguments:
endpoint: The endpoint name to use.
"""
def decorator(func: Callable) -> Callable:
handler = ensure_coroutine(func)
self.view_functions[endpoint] = handler
return func
return decorator | python | def endpoint(self, endpoint: str) -> Callable:
"""Register a function as an endpoint.
This is designed to be used as a decorator. An example usage,
.. code-block:: python
@app.endpoint('name')
def endpoint():
...
Arguments:
endpoint: The endpoint name to use.
"""
def decorator(func: Callable) -> Callable:
handler = ensure_coroutine(func)
self.view_functions[endpoint] = handler
return func
return decorator | [
"def",
"endpoint",
"(",
"self",
",",
"endpoint",
":",
"str",
")",
"->",
"Callable",
":",
"def",
"decorator",
"(",
"func",
":",
"Callable",
")",
"->",
"Callable",
":",
"handler",
"=",
"ensure_coroutine",
"(",
"func",
")",
"self",
".",
"view_functions",
"[... | Register a function as an endpoint.
This is designed to be used as a decorator. An example usage,
.. code-block:: python
@app.endpoint('name')
def endpoint():
...
Arguments:
endpoint: The endpoint name to use. | [
"Register",
"a",
"function",
"as",
"an",
"endpoint",
"."
] | 7cb2d3bd98e8746025764f2b933abc12041fa175 | https://github.com/pgjones/quart/blob/7cb2d3bd98e8746025764f2b933abc12041fa175/quart/app.py#L638-L656 | train | 226,585 |
pgjones/quart | quart/app.py | Quart.register_error_handler | def register_error_handler(
self, error: Union[Type[Exception], int], func: Callable, name: AppOrBlueprintKey=None,
) -> None:
"""Register a function as an error handler.
This is designed to be used on the application directly. An
example usage,
.. code-block:: python
def error_handler():
return "Error", 500
app.register_error_handler(500, error_handler)
Arguments:
error: The error code or Exception to handle.
func: The function to handle the error.
name: Optional blueprint key name.
"""
handler = ensure_coroutine(func)
if isinstance(error, int):
error = all_http_exceptions[error]
self.error_handler_spec[name][error] = handler | python | def register_error_handler(
self, error: Union[Type[Exception], int], func: Callable, name: AppOrBlueprintKey=None,
) -> None:
"""Register a function as an error handler.
This is designed to be used on the application directly. An
example usage,
.. code-block:: python
def error_handler():
return "Error", 500
app.register_error_handler(500, error_handler)
Arguments:
error: The error code or Exception to handle.
func: The function to handle the error.
name: Optional blueprint key name.
"""
handler = ensure_coroutine(func)
if isinstance(error, int):
error = all_http_exceptions[error]
self.error_handler_spec[name][error] = handler | [
"def",
"register_error_handler",
"(",
"self",
",",
"error",
":",
"Union",
"[",
"Type",
"[",
"Exception",
"]",
",",
"int",
"]",
",",
"func",
":",
"Callable",
",",
"name",
":",
"AppOrBlueprintKey",
"=",
"None",
",",
")",
"->",
"None",
":",
"handler",
"="... | Register a function as an error handler.
This is designed to be used on the application directly. An
example usage,
.. code-block:: python
def error_handler():
return "Error", 500
app.register_error_handler(500, error_handler)
Arguments:
error: The error code or Exception to handle.
func: The function to handle the error.
name: Optional blueprint key name. | [
"Register",
"a",
"function",
"as",
"an",
"error",
"handler",
"."
] | 7cb2d3bd98e8746025764f2b933abc12041fa175 | https://github.com/pgjones/quart/blob/7cb2d3bd98e8746025764f2b933abc12041fa175/quart/app.py#L677-L700 | train | 226,586 |
pgjones/quart | quart/app.py | Quart.context_processor | def context_processor(self, func: Callable, name: AppOrBlueprintKey=None) -> Callable:
"""Add a template context processor.
This is designed to be used as a decorator. An example usage,
.. code-block:: python
@app.context_processor
def update_context(context):
return context
"""
self.template_context_processors[name].append(ensure_coroutine(func))
return func | python | def context_processor(self, func: Callable, name: AppOrBlueprintKey=None) -> Callable:
"""Add a template context processor.
This is designed to be used as a decorator. An example usage,
.. code-block:: python
@app.context_processor
def update_context(context):
return context
"""
self.template_context_processors[name].append(ensure_coroutine(func))
return func | [
"def",
"context_processor",
"(",
"self",
",",
"func",
":",
"Callable",
",",
"name",
":",
"AppOrBlueprintKey",
"=",
"None",
")",
"->",
"Callable",
":",
"self",
".",
"template_context_processors",
"[",
"name",
"]",
".",
"append",
"(",
"ensure_coroutine",
"(",
... | Add a template context processor.
This is designed to be used as a decorator. An example usage,
.. code-block:: python
@app.context_processor
def update_context(context):
return context | [
"Add",
"a",
"template",
"context",
"processor",
"."
] | 7cb2d3bd98e8746025764f2b933abc12041fa175 | https://github.com/pgjones/quart/blob/7cb2d3bd98e8746025764f2b933abc12041fa175/quart/app.py#L816-L829 | train | 226,587 |
pgjones/quart | quart/app.py | Quart.shell_context_processor | def shell_context_processor(self, func: Callable) -> Callable:
"""Add a shell context processor.
This is designed to be used as a decorator. An example usage,
.. code-block:: python
@app.shell_context_processor
def additional_context():
return context
"""
self.shell_context_processors.append(func)
return func | python | def shell_context_processor(self, func: Callable) -> Callable:
"""Add a shell context processor.
This is designed to be used as a decorator. An example usage,
.. code-block:: python
@app.shell_context_processor
def additional_context():
return context
"""
self.shell_context_processors.append(func)
return func | [
"def",
"shell_context_processor",
"(",
"self",
",",
"func",
":",
"Callable",
")",
"->",
"Callable",
":",
"self",
".",
"shell_context_processors",
".",
"append",
"(",
"func",
")",
"return",
"func"
] | Add a shell context processor.
This is designed to be used as a decorator. An example usage,
.. code-block:: python
@app.shell_context_processor
def additional_context():
return context | [
"Add",
"a",
"shell",
"context",
"processor",
"."
] | 7cb2d3bd98e8746025764f2b933abc12041fa175 | https://github.com/pgjones/quart/blob/7cb2d3bd98e8746025764f2b933abc12041fa175/quart/app.py#L831-L844 | train | 226,588 |
pgjones/quart | quart/app.py | Quart.inject_url_defaults | def inject_url_defaults(self, endpoint: str, values: dict) -> None:
"""Injects default URL values into the passed values dict.
This is used to assist when building urls, see
:func:`~quart.helpers.url_for`.
"""
functions = self.url_value_preprocessors[None]
if '.' in endpoint:
blueprint = endpoint.rsplit('.', 1)[0]
functions = chain(functions, self.url_value_preprocessors[blueprint]) # type: ignore
for function in functions:
function(endpoint, values) | python | def inject_url_defaults(self, endpoint: str, values: dict) -> None:
"""Injects default URL values into the passed values dict.
This is used to assist when building urls, see
:func:`~quart.helpers.url_for`.
"""
functions = self.url_value_preprocessors[None]
if '.' in endpoint:
blueprint = endpoint.rsplit('.', 1)[0]
functions = chain(functions, self.url_value_preprocessors[blueprint]) # type: ignore
for function in functions:
function(endpoint, values) | [
"def",
"inject_url_defaults",
"(",
"self",
",",
"endpoint",
":",
"str",
",",
"values",
":",
"dict",
")",
"->",
"None",
":",
"functions",
"=",
"self",
".",
"url_value_preprocessors",
"[",
"None",
"]",
"if",
"'.'",
"in",
"endpoint",
":",
"blueprint",
"=",
... | Injects default URL values into the passed values dict.
This is used to assist when building urls, see
:func:`~quart.helpers.url_for`. | [
"Injects",
"default",
"URL",
"values",
"into",
"the",
"passed",
"values",
"dict",
"."
] | 7cb2d3bd98e8746025764f2b933abc12041fa175 | https://github.com/pgjones/quart/blob/7cb2d3bd98e8746025764f2b933abc12041fa175/quart/app.py#L874-L886 | train | 226,589 |
pgjones/quart | quart/app.py | Quart.handle_url_build_error | def handle_url_build_error(self, error: Exception, endpoint: str, values: dict) -> str:
"""Handle a build error.
Ideally this will return a valid url given the error endpoint
and values.
"""
for handler in self.url_build_error_handlers:
result = handler(error, endpoint, values)
if result is not None:
return result
raise error | python | def handle_url_build_error(self, error: Exception, endpoint: str, values: dict) -> str:
"""Handle a build error.
Ideally this will return a valid url given the error endpoint
and values.
"""
for handler in self.url_build_error_handlers:
result = handler(error, endpoint, values)
if result is not None:
return result
raise error | [
"def",
"handle_url_build_error",
"(",
"self",
",",
"error",
":",
"Exception",
",",
"endpoint",
":",
"str",
",",
"values",
":",
"dict",
")",
"->",
"str",
":",
"for",
"handler",
"in",
"self",
".",
"url_build_error_handlers",
":",
"result",
"=",
"handler",
"(... | Handle a build error.
Ideally this will return a valid url given the error endpoint
and values. | [
"Handle",
"a",
"build",
"error",
"."
] | 7cb2d3bd98e8746025764f2b933abc12041fa175 | https://github.com/pgjones/quart/blob/7cb2d3bd98e8746025764f2b933abc12041fa175/quart/app.py#L888-L898 | train | 226,590 |
pgjones/quart | quart/app.py | Quart.handle_http_exception | async def handle_http_exception(self, error: Exception) -> Response:
"""Handle a HTTPException subclass error.
This will attempt to find a handler for the error and if fails
will fall back to the error response.
"""
handler = self._find_exception_handler(error)
if handler is None:
return error.get_response() # type: ignore
else:
return await handler(error) | python | async def handle_http_exception(self, error: Exception) -> Response:
"""Handle a HTTPException subclass error.
This will attempt to find a handler for the error and if fails
will fall back to the error response.
"""
handler = self._find_exception_handler(error)
if handler is None:
return error.get_response() # type: ignore
else:
return await handler(error) | [
"async",
"def",
"handle_http_exception",
"(",
"self",
",",
"error",
":",
"Exception",
")",
"->",
"Response",
":",
"handler",
"=",
"self",
".",
"_find_exception_handler",
"(",
"error",
")",
"if",
"handler",
"is",
"None",
":",
"return",
"error",
".",
"get_resp... | Handle a HTTPException subclass error.
This will attempt to find a handler for the error and if fails
will fall back to the error response. | [
"Handle",
"a",
"HTTPException",
"subclass",
"error",
"."
] | 7cb2d3bd98e8746025764f2b933abc12041fa175 | https://github.com/pgjones/quart/blob/7cb2d3bd98e8746025764f2b933abc12041fa175/quart/app.py#L914-L924 | train | 226,591 |
pgjones/quart | quart/app.py | Quart.handle_user_exception | async def handle_user_exception(self, error: Exception) -> Response:
"""Handle an exception that has been raised.
This should forward :class:`~quart.exception.HTTPException` to
:meth:`handle_http_exception`, then attempt to handle the
error. If it cannot it should reraise the error.
"""
if isinstance(error, HTTPException) and not self.trap_http_exception(error):
return await self.handle_http_exception(error)
handler = self._find_exception_handler(error)
if handler is None:
raise error
return await handler(error) | python | async def handle_user_exception(self, error: Exception) -> Response:
"""Handle an exception that has been raised.
This should forward :class:`~quart.exception.HTTPException` to
:meth:`handle_http_exception`, then attempt to handle the
error. If it cannot it should reraise the error.
"""
if isinstance(error, HTTPException) and not self.trap_http_exception(error):
return await self.handle_http_exception(error)
handler = self._find_exception_handler(error)
if handler is None:
raise error
return await handler(error) | [
"async",
"def",
"handle_user_exception",
"(",
"self",
",",
"error",
":",
"Exception",
")",
"->",
"Response",
":",
"if",
"isinstance",
"(",
"error",
",",
"HTTPException",
")",
"and",
"not",
"self",
".",
"trap_http_exception",
"(",
"error",
")",
":",
"return",... | Handle an exception that has been raised.
This should forward :class:`~quart.exception.HTTPException` to
:meth:`handle_http_exception`, then attempt to handle the
error. If it cannot it should reraise the error. | [
"Handle",
"an",
"exception",
"that",
"has",
"been",
"raised",
"."
] | 7cb2d3bd98e8746025764f2b933abc12041fa175 | https://github.com/pgjones/quart/blob/7cb2d3bd98e8746025764f2b933abc12041fa175/quart/app.py#L936-L949 | train | 226,592 |
pgjones/quart | quart/app.py | Quart.before_request | def before_request(self, func: Callable, name: AppOrBlueprintKey=None) -> Callable:
"""Add a before request function.
This is designed to be used as a decorator. An example usage,
.. code-block:: python
@app.before_request
def func():
...
Arguments:
func: The before request function itself.
name: Optional blueprint key name.
"""
handler = ensure_coroutine(func)
self.before_request_funcs[name].append(handler)
return func | python | def before_request(self, func: Callable, name: AppOrBlueprintKey=None) -> Callable:
"""Add a before request function.
This is designed to be used as a decorator. An example usage,
.. code-block:: python
@app.before_request
def func():
...
Arguments:
func: The before request function itself.
name: Optional blueprint key name.
"""
handler = ensure_coroutine(func)
self.before_request_funcs[name].append(handler)
return func | [
"def",
"before_request",
"(",
"self",
",",
"func",
":",
"Callable",
",",
"name",
":",
"AppOrBlueprintKey",
"=",
"None",
")",
"->",
"Callable",
":",
"handler",
"=",
"ensure_coroutine",
"(",
"func",
")",
"self",
".",
"before_request_funcs",
"[",
"name",
"]",
... | Add a before request function.
This is designed to be used as a decorator. An example usage,
.. code-block:: python
@app.before_request
def func():
...
Arguments:
func: The before request function itself.
name: Optional blueprint key name. | [
"Add",
"a",
"before",
"request",
"function",
"."
] | 7cb2d3bd98e8746025764f2b933abc12041fa175 | https://github.com/pgjones/quart/blob/7cb2d3bd98e8746025764f2b933abc12041fa175/quart/app.py#L1007-L1024 | train | 226,593 |
pgjones/quart | quart/app.py | Quart.before_websocket | def before_websocket(self, func: Callable, name: AppOrBlueprintKey=None) -> Callable:
"""Add a before websocket function.
This is designed to be used as a decorator. An example usage,
.. code-block:: python
@app.before_websocket
def func():
...
Arguments:
func: The before websocket function itself.
name: Optional blueprint key name.
"""
handler = ensure_coroutine(func)
self.before_websocket_funcs[name].append(handler)
return func | python | def before_websocket(self, func: Callable, name: AppOrBlueprintKey=None) -> Callable:
"""Add a before websocket function.
This is designed to be used as a decorator. An example usage,
.. code-block:: python
@app.before_websocket
def func():
...
Arguments:
func: The before websocket function itself.
name: Optional blueprint key name.
"""
handler = ensure_coroutine(func)
self.before_websocket_funcs[name].append(handler)
return func | [
"def",
"before_websocket",
"(",
"self",
",",
"func",
":",
"Callable",
",",
"name",
":",
"AppOrBlueprintKey",
"=",
"None",
")",
"->",
"Callable",
":",
"handler",
"=",
"ensure_coroutine",
"(",
"func",
")",
"self",
".",
"before_websocket_funcs",
"[",
"name",
"]... | Add a before websocket function.
This is designed to be used as a decorator. An example usage,
.. code-block:: python
@app.before_websocket
def func():
...
Arguments:
func: The before websocket function itself.
name: Optional blueprint key name. | [
"Add",
"a",
"before",
"websocket",
"function",
"."
] | 7cb2d3bd98e8746025764f2b933abc12041fa175 | https://github.com/pgjones/quart/blob/7cb2d3bd98e8746025764f2b933abc12041fa175/quart/app.py#L1026-L1043 | train | 226,594 |
pgjones/quart | quart/app.py | Quart.before_serving | def before_serving(self, func: Callable) -> Callable:
"""Add a before serving function.
This will allow the function provided to be called once before
anything is served (before any byte is received).
This is designed to be used as a decorator. An example usage,
.. code-block:: python
@app.before_serving
def func():
...
Arguments:
func: The function itself.
"""
handler = ensure_coroutine(func)
self.before_serving_funcs.append(handler)
return func | python | def before_serving(self, func: Callable) -> Callable:
"""Add a before serving function.
This will allow the function provided to be called once before
anything is served (before any byte is received).
This is designed to be used as a decorator. An example usage,
.. code-block:: python
@app.before_serving
def func():
...
Arguments:
func: The function itself.
"""
handler = ensure_coroutine(func)
self.before_serving_funcs.append(handler)
return func | [
"def",
"before_serving",
"(",
"self",
",",
"func",
":",
"Callable",
")",
"->",
"Callable",
":",
"handler",
"=",
"ensure_coroutine",
"(",
"func",
")",
"self",
".",
"before_serving_funcs",
".",
"append",
"(",
"handler",
")",
"return",
"func"
] | Add a before serving function.
This will allow the function provided to be called once before
anything is served (before any byte is received).
This is designed to be used as a decorator. An example usage,
.. code-block:: python
@app.before_serving
def func():
...
Arguments:
func: The function itself. | [
"Add",
"a",
"before",
"serving",
"function",
"."
] | 7cb2d3bd98e8746025764f2b933abc12041fa175 | https://github.com/pgjones/quart/blob/7cb2d3bd98e8746025764f2b933abc12041fa175/quart/app.py#L1064-L1083 | train | 226,595 |
pgjones/quart | quart/app.py | Quart.after_request | def after_request(self, func: Callable, name: AppOrBlueprintKey=None) -> Callable:
"""Add an after request function.
This is designed to be used as a decorator. An example usage,
.. code-block:: python
@app.after_request
def func(response):
return response
Arguments:
func: The after request function itself.
name: Optional blueprint key name.
"""
handler = ensure_coroutine(func)
self.after_request_funcs[name].append(handler)
return func | python | def after_request(self, func: Callable, name: AppOrBlueprintKey=None) -> Callable:
"""Add an after request function.
This is designed to be used as a decorator. An example usage,
.. code-block:: python
@app.after_request
def func(response):
return response
Arguments:
func: The after request function itself.
name: Optional blueprint key name.
"""
handler = ensure_coroutine(func)
self.after_request_funcs[name].append(handler)
return func | [
"def",
"after_request",
"(",
"self",
",",
"func",
":",
"Callable",
",",
"name",
":",
"AppOrBlueprintKey",
"=",
"None",
")",
"->",
"Callable",
":",
"handler",
"=",
"ensure_coroutine",
"(",
"func",
")",
"self",
".",
"after_request_funcs",
"[",
"name",
"]",
"... | Add an after request function.
This is designed to be used as a decorator. An example usage,
.. code-block:: python
@app.after_request
def func(response):
return response
Arguments:
func: The after request function itself.
name: Optional blueprint key name. | [
"Add",
"an",
"after",
"request",
"function",
"."
] | 7cb2d3bd98e8746025764f2b933abc12041fa175 | https://github.com/pgjones/quart/blob/7cb2d3bd98e8746025764f2b933abc12041fa175/quart/app.py#L1085-L1102 | train | 226,596 |
pgjones/quart | quart/app.py | Quart.after_websocket | def after_websocket(self, func: Callable, name: AppOrBlueprintKey=None) -> Callable:
"""Add an after websocket function.
This is designed to be used as a decorator. An example usage,
.. code-block:: python
@app.after_websocket
def func(response):
return response
Arguments:
func: The after websocket function itself.
name: Optional blueprint key name.
"""
handler = ensure_coroutine(func)
self.after_websocket_funcs[name].append(handler)
return func | python | def after_websocket(self, func: Callable, name: AppOrBlueprintKey=None) -> Callable:
"""Add an after websocket function.
This is designed to be used as a decorator. An example usage,
.. code-block:: python
@app.after_websocket
def func(response):
return response
Arguments:
func: The after websocket function itself.
name: Optional blueprint key name.
"""
handler = ensure_coroutine(func)
self.after_websocket_funcs[name].append(handler)
return func | [
"def",
"after_websocket",
"(",
"self",
",",
"func",
":",
"Callable",
",",
"name",
":",
"AppOrBlueprintKey",
"=",
"None",
")",
"->",
"Callable",
":",
"handler",
"=",
"ensure_coroutine",
"(",
"func",
")",
"self",
".",
"after_websocket_funcs",
"[",
"name",
"]",... | Add an after websocket function.
This is designed to be used as a decorator. An example usage,
.. code-block:: python
@app.after_websocket
def func(response):
return response
Arguments:
func: The after websocket function itself.
name: Optional blueprint key name. | [
"Add",
"an",
"after",
"websocket",
"function",
"."
] | 7cb2d3bd98e8746025764f2b933abc12041fa175 | https://github.com/pgjones/quart/blob/7cb2d3bd98e8746025764f2b933abc12041fa175/quart/app.py#L1104-L1121 | train | 226,597 |
pgjones/quart | quart/app.py | Quart.after_serving | def after_serving(self, func: Callable) -> Callable:
"""Add a after serving function.
This will allow the function provided to be called once after
anything is served (after last byte is sent).
This is designed to be used as a decorator. An example usage,
.. code-block:: python
@app.after_serving
def func():
...
Arguments:
func: The function itself.
"""
handler = ensure_coroutine(func)
self.after_serving_funcs.append(handler)
return func | python | def after_serving(self, func: Callable) -> Callable:
"""Add a after serving function.
This will allow the function provided to be called once after
anything is served (after last byte is sent).
This is designed to be used as a decorator. An example usage,
.. code-block:: python
@app.after_serving
def func():
...
Arguments:
func: The function itself.
"""
handler = ensure_coroutine(func)
self.after_serving_funcs.append(handler)
return func | [
"def",
"after_serving",
"(",
"self",
",",
"func",
":",
"Callable",
")",
"->",
"Callable",
":",
"handler",
"=",
"ensure_coroutine",
"(",
"func",
")",
"self",
".",
"after_serving_funcs",
".",
"append",
"(",
"handler",
")",
"return",
"func"
] | Add a after serving function.
This will allow the function provided to be called once after
anything is served (after last byte is sent).
This is designed to be used as a decorator. An example usage,
.. code-block:: python
@app.after_serving
def func():
...
Arguments:
func: The function itself. | [
"Add",
"a",
"after",
"serving",
"function",
"."
] | 7cb2d3bd98e8746025764f2b933abc12041fa175 | https://github.com/pgjones/quart/blob/7cb2d3bd98e8746025764f2b933abc12041fa175/quart/app.py#L1123-L1143 | train | 226,598 |
pgjones/quart | quart/app.py | Quart.teardown_request | def teardown_request(self, func: Callable, name: AppOrBlueprintKey=None) -> Callable:
"""Add a teardown request function.
This is designed to be used as a decorator. An example usage,
.. code-block:: python
@app.teardown_request
def func():
...
Arguments:
func: The teardown request function itself.
name: Optional blueprint key name.
"""
handler = ensure_coroutine(func)
self.teardown_request_funcs[name].append(handler)
return func | python | def teardown_request(self, func: Callable, name: AppOrBlueprintKey=None) -> Callable:
"""Add a teardown request function.
This is designed to be used as a decorator. An example usage,
.. code-block:: python
@app.teardown_request
def func():
...
Arguments:
func: The teardown request function itself.
name: Optional blueprint key name.
"""
handler = ensure_coroutine(func)
self.teardown_request_funcs[name].append(handler)
return func | [
"def",
"teardown_request",
"(",
"self",
",",
"func",
":",
"Callable",
",",
"name",
":",
"AppOrBlueprintKey",
"=",
"None",
")",
"->",
"Callable",
":",
"handler",
"=",
"ensure_coroutine",
"(",
"func",
")",
"self",
".",
"teardown_request_funcs",
"[",
"name",
"]... | Add a teardown request function.
This is designed to be used as a decorator. An example usage,
.. code-block:: python
@app.teardown_request
def func():
...
Arguments:
func: The teardown request function itself.
name: Optional blueprint key name. | [
"Add",
"a",
"teardown",
"request",
"function",
"."
] | 7cb2d3bd98e8746025764f2b933abc12041fa175 | https://github.com/pgjones/quart/blob/7cb2d3bd98e8746025764f2b933abc12041fa175/quart/app.py#L1145-L1162 | train | 226,599 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.