id
int32
0
252k
repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
51
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
245,500
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): 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
245,501
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): 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
245,502
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: 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
245,503
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: 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
245,504
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: 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
245,505
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]: 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
245,506
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]: 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
245,507
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: 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
245,508
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: 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
245,509
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: 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
245,510
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: 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
245,511
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: 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
245,512
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: 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
245,513
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: 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
245,514
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: 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
245,515
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: 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
245,516
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: 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
245,517
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: 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
245,518
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: 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
245,519
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: 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
245,520
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: 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
245,521
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: 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
245,522
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: 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
245,523
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: 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
245,524
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: 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
245,525
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: 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
245,526
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: 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
245,527
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: 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
245,528
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: 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
245,529
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: 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
245,530
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 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
245,531
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]: 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
245,532
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: 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
245,533
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: 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
245,534
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: 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
245,535
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: 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
245,536
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: 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
245,537
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: 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
245,538
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: 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
245,539
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: 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
245,540
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: 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
245,541
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: 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
245,542
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]: 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
245,543
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: 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
245,544
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: 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
245,545
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: 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
245,546
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: 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
245,547
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: 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
245,548
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: 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
245,549
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: 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
245,550
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: 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
245,551
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: 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
245,552
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: 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
245,553
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: 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
245,554
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: 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
245,555
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: 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
245,556
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: 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
245,557
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: 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
245,558
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: 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
245,559
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: 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
245,560
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: 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
245,561
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: 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
245,562
pgjones/quart
quart/app.py
Quart.teardown_websocket
def teardown_websocket(self, func: Callable, name: AppOrBlueprintKey=None) -> Callable: """Add a teardown websocket function. This is designed to be used as a decorator. An example usage, .. code-block:: python @app.teardown_websocket def func(): ... Arguments: func: The teardown websocket function itself. name: Optional blueprint key name. """ handler = ensure_coroutine(func) self.teardown_websocket_funcs[name].append(handler) return func
python
def teardown_websocket(self, func: Callable, name: AppOrBlueprintKey=None) -> Callable: handler = ensure_coroutine(func) self.teardown_websocket_funcs[name].append(handler) return func
[ "def", "teardown_websocket", "(", "self", ",", "func", ":", "Callable", ",", "name", ":", "AppOrBlueprintKey", "=", "None", ")", "->", "Callable", ":", "handler", "=", "ensure_coroutine", "(", "func", ")", "self", ".", "teardown_websocket_funcs", "[", "name", ...
Add a teardown websocket function. This is designed to be used as a decorator. An example usage, .. code-block:: python @app.teardown_websocket def func(): ... Arguments: func: The teardown websocket function itself. name: Optional blueprint key name.
[ "Add", "a", "teardown", "websocket", "function", "." ]
7cb2d3bd98e8746025764f2b933abc12041fa175
https://github.com/pgjones/quart/blob/7cb2d3bd98e8746025764f2b933abc12041fa175/quart/app.py#L1164-L1181
245,563
pgjones/quart
quart/app.py
Quart.register_blueprint
def register_blueprint(self, blueprint: Blueprint, url_prefix: Optional[str]=None) -> None: """Register a blueprint on the app. This results in the blueprint's routes, error handlers etc... being added to the app. Arguments: blueprint: The blueprint to register. url_prefix: Optional prefix to apply to all paths. """ first_registration = False if blueprint.name in self.blueprints and self.blueprints[blueprint.name] is not blueprint: raise RuntimeError( f"Blueprint name '{blueprint.name}' " f"is already registered by {self.blueprints[blueprint.name]}. " "Blueprints must have unique names", ) else: self.blueprints[blueprint.name] = blueprint first_registration = True blueprint.register(self, first_registration, url_prefix=url_prefix)
python
def register_blueprint(self, blueprint: Blueprint, url_prefix: Optional[str]=None) -> None: first_registration = False if blueprint.name in self.blueprints and self.blueprints[blueprint.name] is not blueprint: raise RuntimeError( f"Blueprint name '{blueprint.name}' " f"is already registered by {self.blueprints[blueprint.name]}. " "Blueprints must have unique names", ) else: self.blueprints[blueprint.name] = blueprint first_registration = True blueprint.register(self, first_registration, url_prefix=url_prefix)
[ "def", "register_blueprint", "(", "self", ",", "blueprint", ":", "Blueprint", ",", "url_prefix", ":", "Optional", "[", "str", "]", "=", "None", ")", "->", "None", ":", "first_registration", "=", "False", "if", "blueprint", ".", "name", "in", "self", ".", ...
Register a blueprint on the app. This results in the blueprint's routes, error handlers etc... being added to the app. Arguments: blueprint: The blueprint to register. url_prefix: Optional prefix to apply to all paths.
[ "Register", "a", "blueprint", "on", "the", "app", "." ]
7cb2d3bd98e8746025764f2b933abc12041fa175
https://github.com/pgjones/quart/blob/7cb2d3bd98e8746025764f2b933abc12041fa175/quart/app.py#L1202-L1222
245,564
pgjones/quart
quart/app.py
Quart.open_session
async def open_session(self, request: BaseRequestWebsocket) -> Session: """Open and return a Session using the request.""" return await ensure_coroutine(self.session_interface.open_session)(self, request)
python
async def open_session(self, request: BaseRequestWebsocket) -> Session: return await ensure_coroutine(self.session_interface.open_session)(self, request)
[ "async", "def", "open_session", "(", "self", ",", "request", ":", "BaseRequestWebsocket", ")", "->", "Session", ":", "return", "await", "ensure_coroutine", "(", "self", ".", "session_interface", ".", "open_session", ")", "(", "self", ",", "request", ")" ]
Open and return a Session using the request.
[ "Open", "and", "return", "a", "Session", "using", "the", "request", "." ]
7cb2d3bd98e8746025764f2b933abc12041fa175
https://github.com/pgjones/quart/blob/7cb2d3bd98e8746025764f2b933abc12041fa175/quart/app.py#L1228-L1230
245,565
pgjones/quart
quart/app.py
Quart.save_session
async def save_session(self, session: Session, response: Response) -> None: """Saves the session to the response.""" await ensure_coroutine(self.session_interface.save_session)(self, session, response)
python
async def save_session(self, session: Session, response: Response) -> None: await ensure_coroutine(self.session_interface.save_session)(self, session, response)
[ "async", "def", "save_session", "(", "self", ",", "session", ":", "Session", ",", "response", ":", "Response", ")", "->", "None", ":", "await", "ensure_coroutine", "(", "self", ".", "session_interface", ".", "save_session", ")", "(", "self", ",", "session", ...
Saves the session to the response.
[ "Saves", "the", "session", "to", "the", "response", "." ]
7cb2d3bd98e8746025764f2b933abc12041fa175
https://github.com/pgjones/quart/blob/7cb2d3bd98e8746025764f2b933abc12041fa175/quart/app.py#L1236-L1238
245,566
pgjones/quart
quart/app.py
Quart.do_teardown_request
async def do_teardown_request( self, exc: Optional[BaseException], request_context: Optional[RequestContext]=None, ) -> None: """Teardown the request, calling the teardown functions. Arguments: exc: Any exception not handled that has caused the request to teardown. request_context: The request context, optional as Flask omits this argument. """ request_ = (request_context or _request_ctx_stack.top).request functions = self.teardown_request_funcs[None] blueprint = request_.blueprint if blueprint is not None: functions = chain(functions, self.teardown_request_funcs[blueprint]) # type: ignore for function in functions: await function(exc=exc) await request_tearing_down.send(self, exc=exc)
python
async def do_teardown_request( self, exc: Optional[BaseException], request_context: Optional[RequestContext]=None, ) -> None: request_ = (request_context or _request_ctx_stack.top).request functions = self.teardown_request_funcs[None] blueprint = request_.blueprint if blueprint is not None: functions = chain(functions, self.teardown_request_funcs[blueprint]) # type: ignore for function in functions: await function(exc=exc) await request_tearing_down.send(self, exc=exc)
[ "async", "def", "do_teardown_request", "(", "self", ",", "exc", ":", "Optional", "[", "BaseException", "]", ",", "request_context", ":", "Optional", "[", "RequestContext", "]", "=", "None", ",", ")", "->", "None", ":", "request_", "=", "(", "request_context"...
Teardown the request, calling the teardown functions. Arguments: exc: Any exception not handled that has caused the request to teardown. request_context: The request context, optional as Flask omits this argument.
[ "Teardown", "the", "request", "calling", "the", "teardown", "functions", "." ]
7cb2d3bd98e8746025764f2b933abc12041fa175
https://github.com/pgjones/quart/blob/7cb2d3bd98e8746025764f2b933abc12041fa175/quart/app.py#L1240-L1261
245,567
pgjones/quart
quart/app.py
Quart.do_teardown_websocket
async def do_teardown_websocket( self, exc: Optional[BaseException], websocket_context: Optional[WebsocketContext]=None, ) -> None: """Teardown the websocket, calling the teardown functions. Arguments: exc: Any exception not handled that has caused the websocket to teardown. websocket_context: The websocket context, optional as Flask omits this argument. """ websocket_ = (websocket_context or _websocket_ctx_stack.top).websocket functions = self.teardown_websocket_funcs[None] blueprint = websocket_.blueprint if blueprint is not None: functions = chain(functions, self.teardown_websocket_funcs[blueprint]) # type: ignore for function in functions: await function(exc=exc) await websocket_tearing_down.send(self, exc=exc)
python
async def do_teardown_websocket( self, exc: Optional[BaseException], websocket_context: Optional[WebsocketContext]=None, ) -> None: websocket_ = (websocket_context or _websocket_ctx_stack.top).websocket functions = self.teardown_websocket_funcs[None] blueprint = websocket_.blueprint if blueprint is not None: functions = chain(functions, self.teardown_websocket_funcs[blueprint]) # type: ignore for function in functions: await function(exc=exc) await websocket_tearing_down.send(self, exc=exc)
[ "async", "def", "do_teardown_websocket", "(", "self", ",", "exc", ":", "Optional", "[", "BaseException", "]", ",", "websocket_context", ":", "Optional", "[", "WebsocketContext", "]", "=", "None", ",", ")", "->", "None", ":", "websocket_", "=", "(", "websocke...
Teardown the websocket, calling the teardown functions. Arguments: exc: Any exception not handled that has caused the websocket to teardown. websocket_context: The websocket context, optional as Flask omits this argument.
[ "Teardown", "the", "websocket", "calling", "the", "teardown", "functions", "." ]
7cb2d3bd98e8746025764f2b933abc12041fa175
https://github.com/pgjones/quart/blob/7cb2d3bd98e8746025764f2b933abc12041fa175/quart/app.py#L1263-L1284
245,568
pgjones/quart
quart/app.py
Quart.run
def run( self, host: str='127.0.0.1', port: int=5000, debug: Optional[bool]=None, use_reloader: bool=True, loop: Optional[asyncio.AbstractEventLoop]=None, ca_certs: Optional[str]=None, certfile: Optional[str]=None, keyfile: Optional[str]=None, **kwargs: Any, ) -> None: """Run this application. This is best used for development only, see Hypercorn for production servers. Arguments: host: Hostname to listen on. By default this is loopback only, use 0.0.0.0 to have the server listen externally. port: Port number to listen on. debug: If set enable (or disable) debug mode and debug output. use_reloader: Automatically reload on code changes. loop: Asyncio loop to create the server in, if None, take default one. If specified it is the caller's responsibility to close and cleanup the loop. ca_certs: Path to the SSL CA certificate file. certfile: Path to the SSL certificate file. keyfile: Path to the SSL key file. """ if kwargs: warnings.warn( f"Additional arguments, {','.join(kwargs.keys())}, are not supported.\n" "They may be supported by Hypercorn, which is the ASGI server Quart " "uses by default. This method is meant for development and debugging." ) config = HyperConfig() config.access_log_format = "%(h)s %(r)s %(s)s %(b)s %(D)s" config.access_logger = create_serving_logger() # type: ignore config.bind = [f"{host}:{port}"] config.ca_certs = ca_certs config.certfile = certfile if debug is not None: self.debug = debug config.error_logger = config.access_logger # type: ignore config.keyfile = keyfile config.use_reloader = use_reloader scheme = 'https' if config.ssl_enabled else 'http' print("Running on {}://{} (CTRL + C to quit)".format(scheme, config.bind[0])) # noqa: T001 if loop is not None: loop.set_debug(debug or False) loop.run_until_complete(serve(self, config)) else: asyncio.run(serve(self, config), debug=config.debug)
python
def run( self, host: str='127.0.0.1', port: int=5000, debug: Optional[bool]=None, use_reloader: bool=True, loop: Optional[asyncio.AbstractEventLoop]=None, ca_certs: Optional[str]=None, certfile: Optional[str]=None, keyfile: Optional[str]=None, **kwargs: Any, ) -> None: if kwargs: warnings.warn( f"Additional arguments, {','.join(kwargs.keys())}, are not supported.\n" "They may be supported by Hypercorn, which is the ASGI server Quart " "uses by default. This method is meant for development and debugging." ) config = HyperConfig() config.access_log_format = "%(h)s %(r)s %(s)s %(b)s %(D)s" config.access_logger = create_serving_logger() # type: ignore config.bind = [f"{host}:{port}"] config.ca_certs = ca_certs config.certfile = certfile if debug is not None: self.debug = debug config.error_logger = config.access_logger # type: ignore config.keyfile = keyfile config.use_reloader = use_reloader scheme = 'https' if config.ssl_enabled else 'http' print("Running on {}://{} (CTRL + C to quit)".format(scheme, config.bind[0])) # noqa: T001 if loop is not None: loop.set_debug(debug or False) loop.run_until_complete(serve(self, config)) else: asyncio.run(serve(self, config), debug=config.debug)
[ "def", "run", "(", "self", ",", "host", ":", "str", "=", "'127.0.0.1'", ",", "port", ":", "int", "=", "5000", ",", "debug", ":", "Optional", "[", "bool", "]", "=", "None", ",", "use_reloader", ":", "bool", "=", "True", ",", "loop", ":", "Optional",...
Run this application. This is best used for development only, see Hypercorn for production servers. Arguments: host: Hostname to listen on. By default this is loopback only, use 0.0.0.0 to have the server listen externally. port: Port number to listen on. debug: If set enable (or disable) debug mode and debug output. use_reloader: Automatically reload on code changes. loop: Asyncio loop to create the server in, if None, take default one. If specified it is the caller's responsibility to close and cleanup the loop. ca_certs: Path to the SSL CA certificate file. certfile: Path to the SSL certificate file. keyfile: Path to the SSL key file.
[ "Run", "this", "application", "." ]
7cb2d3bd98e8746025764f2b933abc12041fa175
https://github.com/pgjones/quart/blob/7cb2d3bd98e8746025764f2b933abc12041fa175/quart/app.py#L1336-L1393
245,569
pgjones/quart
quart/app.py
Quart.try_trigger_before_first_request_functions
async def try_trigger_before_first_request_functions(self) -> None: """Trigger the before first request methods.""" if self._got_first_request: return # Reverse the teardown functions, so as to match the expected usage self.teardown_appcontext_funcs = list(reversed(self.teardown_appcontext_funcs)) for key, value in self.teardown_request_funcs.items(): self.teardown_request_funcs[key] = list(reversed(value)) for key, value in self.teardown_websocket_funcs.items(): self.teardown_websocket_funcs[key] = list(reversed(value)) async with self._first_request_lock: if self._got_first_request: return for function in self.before_first_request_funcs: await function() self._got_first_request = True
python
async def try_trigger_before_first_request_functions(self) -> None: if self._got_first_request: return # Reverse the teardown functions, so as to match the expected usage self.teardown_appcontext_funcs = list(reversed(self.teardown_appcontext_funcs)) for key, value in self.teardown_request_funcs.items(): self.teardown_request_funcs[key] = list(reversed(value)) for key, value in self.teardown_websocket_funcs.items(): self.teardown_websocket_funcs[key] = list(reversed(value)) async with self._first_request_lock: if self._got_first_request: return for function in self.before_first_request_funcs: await function() self._got_first_request = True
[ "async", "def", "try_trigger_before_first_request_functions", "(", "self", ")", "->", "None", ":", "if", "self", ".", "_got_first_request", ":", "return", "# Reverse the teardown functions, so as to match the expected usage", "self", ".", "teardown_appcontext_funcs", "=", "li...
Trigger the before first request methods.
[ "Trigger", "the", "before", "first", "request", "methods", "." ]
7cb2d3bd98e8746025764f2b933abc12041fa175
https://github.com/pgjones/quart/blob/7cb2d3bd98e8746025764f2b933abc12041fa175/quart/app.py#L1437-L1454
245,570
pgjones/quart
quart/app.py
Quart.make_default_options_response
async def make_default_options_response(self) -> Response: """This is the default route function for OPTIONS requests.""" methods = _request_ctx_stack.top.url_adapter.allowed_methods() return self.response_class('', headers={'Allow': ', '.join(methods)})
python
async def make_default_options_response(self) -> Response: methods = _request_ctx_stack.top.url_adapter.allowed_methods() return self.response_class('', headers={'Allow': ', '.join(methods)})
[ "async", "def", "make_default_options_response", "(", "self", ")", "->", "Response", ":", "methods", "=", "_request_ctx_stack", ".", "top", ".", "url_adapter", ".", "allowed_methods", "(", ")", "return", "self", ".", "response_class", "(", "''", ",", "headers", ...
This is the default route function for OPTIONS requests.
[ "This", "is", "the", "default", "route", "function", "for", "OPTIONS", "requests", "." ]
7cb2d3bd98e8746025764f2b933abc12041fa175
https://github.com/pgjones/quart/blob/7cb2d3bd98e8746025764f2b933abc12041fa175/quart/app.py#L1456-L1459
245,571
pgjones/quart
quart/app.py
Quart.make_response
async def make_response(self, result: ResponseReturnValue) -> Response: """Make a Response from the result of the route handler. The result itself can either be: - A Response object (or subclass). - A tuple of a ResponseValue and a header dictionary. - A tuple of a ResponseValue, status code and a header dictionary. A ResponseValue is either a Response object (or subclass) or a str. """ status_or_headers = None headers = None status = None if isinstance(result, tuple): value, status_or_headers, headers = result + (None,) * (3 - len(result)) else: value = result if value is None: raise TypeError('The response value returned by the view function cannot be None') if isinstance(status_or_headers, (dict, list)): headers = status_or_headers status = None elif status_or_headers is not None: status = status_or_headers if not isinstance(value, Response): response = self.response_class( # type: ignore value, timeout=self.config['RESPONSE_TIMEOUT'], ) else: response = value if status is not None: response.status_code = status # type: ignore if headers is not None: response.headers.update(headers) # type: ignore return response
python
async def make_response(self, result: ResponseReturnValue) -> Response: status_or_headers = None headers = None status = None if isinstance(result, tuple): value, status_or_headers, headers = result + (None,) * (3 - len(result)) else: value = result if value is None: raise TypeError('The response value returned by the view function cannot be None') if isinstance(status_or_headers, (dict, list)): headers = status_or_headers status = None elif status_or_headers is not None: status = status_or_headers if not isinstance(value, Response): response = self.response_class( # type: ignore value, timeout=self.config['RESPONSE_TIMEOUT'], ) else: response = value if status is not None: response.status_code = status # type: ignore if headers is not None: response.headers.update(headers) # type: ignore return response
[ "async", "def", "make_response", "(", "self", ",", "result", ":", "ResponseReturnValue", ")", "->", "Response", ":", "status_or_headers", "=", "None", "headers", "=", "None", "status", "=", "None", "if", "isinstance", "(", "result", ",", "tuple", ")", ":", ...
Make a Response from the result of the route handler. The result itself can either be: - A Response object (or subclass). - A tuple of a ResponseValue and a header dictionary. - A tuple of a ResponseValue, status code and a header dictionary. A ResponseValue is either a Response object (or subclass) or a str.
[ "Make", "a", "Response", "from", "the", "result", "of", "the", "route", "handler", "." ]
7cb2d3bd98e8746025764f2b933abc12041fa175
https://github.com/pgjones/quart/blob/7cb2d3bd98e8746025764f2b933abc12041fa175/quart/app.py#L1461-L1501
245,572
pgjones/quart
quart/app.py
Quart.full_dispatch_request
async def full_dispatch_request( self, request_context: Optional[RequestContext]=None, ) -> Response: """Adds pre and post processing to the request dispatching. Arguments: request_context: The request context, optional as Flask omits this argument. """ await self.try_trigger_before_first_request_functions() await request_started.send(self) try: result = await self.preprocess_request(request_context) if result is None: result = await self.dispatch_request(request_context) except Exception as error: result = await self.handle_user_exception(error) return await self.finalize_request(result, request_context)
python
async def full_dispatch_request( self, request_context: Optional[RequestContext]=None, ) -> Response: await self.try_trigger_before_first_request_functions() await request_started.send(self) try: result = await self.preprocess_request(request_context) if result is None: result = await self.dispatch_request(request_context) except Exception as error: result = await self.handle_user_exception(error) return await self.finalize_request(result, request_context)
[ "async", "def", "full_dispatch_request", "(", "self", ",", "request_context", ":", "Optional", "[", "RequestContext", "]", "=", "None", ",", ")", "->", "Response", ":", "await", "self", ".", "try_trigger_before_first_request_functions", "(", ")", "await", "request...
Adds pre and post processing to the request dispatching. Arguments: request_context: The request context, optional as Flask omits this argument.
[ "Adds", "pre", "and", "post", "processing", "to", "the", "request", "dispatching", "." ]
7cb2d3bd98e8746025764f2b933abc12041fa175
https://github.com/pgjones/quart/blob/7cb2d3bd98e8746025764f2b933abc12041fa175/quart/app.py#L1512-L1529
245,573
pgjones/quart
quart/app.py
Quart.preprocess_request
async def preprocess_request( self, request_context: Optional[RequestContext]=None, ) -> Optional[ResponseReturnValue]: """Preprocess the request i.e. call before_request functions. Arguments: request_context: The request context, optional as Flask omits this argument. """ request_ = (request_context or _request_ctx_stack.top).request blueprint = request_.blueprint processors = self.url_value_preprocessors[None] if blueprint is not None: processors = chain(processors, self.url_value_preprocessors[blueprint]) # type: ignore for processor in processors: processor(request.endpoint, request.view_args) functions = self.before_request_funcs[None] if blueprint is not None: functions = chain(functions, self.before_request_funcs[blueprint]) # type: ignore for function in functions: result = await function() if result is not None: return result return None
python
async def preprocess_request( self, request_context: Optional[RequestContext]=None, ) -> Optional[ResponseReturnValue]: request_ = (request_context or _request_ctx_stack.top).request blueprint = request_.blueprint processors = self.url_value_preprocessors[None] if blueprint is not None: processors = chain(processors, self.url_value_preprocessors[blueprint]) # type: ignore for processor in processors: processor(request.endpoint, request.view_args) functions = self.before_request_funcs[None] if blueprint is not None: functions = chain(functions, self.before_request_funcs[blueprint]) # type: ignore for function in functions: result = await function() if result is not None: return result return None
[ "async", "def", "preprocess_request", "(", "self", ",", "request_context", ":", "Optional", "[", "RequestContext", "]", "=", "None", ",", ")", "->", "Optional", "[", "ResponseReturnValue", "]", ":", "request_", "=", "(", "request_context", "or", "_request_ctx_st...
Preprocess the request i.e. call before_request functions. Arguments: request_context: The request context, optional as Flask omits this argument.
[ "Preprocess", "the", "request", "i", ".", "e", ".", "call", "before_request", "functions", "." ]
7cb2d3bd98e8746025764f2b933abc12041fa175
https://github.com/pgjones/quart/blob/7cb2d3bd98e8746025764f2b933abc12041fa175/quart/app.py#L1531-L1555
245,574
pgjones/quart
quart/app.py
Quart.dispatch_request
async def dispatch_request( self, request_context: Optional[RequestContext]=None, ) -> ResponseReturnValue: """Dispatch the request to the view function. Arguments: request_context: The request context, optional as Flask omits this argument. """ request_ = (request_context or _request_ctx_stack.top).request if request_.routing_exception is not None: raise request_.routing_exception if request_.method == 'OPTIONS' and request_.url_rule.provide_automatic_options: return await self.make_default_options_response() handler = self.view_functions[request_.url_rule.endpoint] return await handler(**request_.view_args)
python
async def dispatch_request( self, request_context: Optional[RequestContext]=None, ) -> ResponseReturnValue: request_ = (request_context or _request_ctx_stack.top).request if request_.routing_exception is not None: raise request_.routing_exception if request_.method == 'OPTIONS' and request_.url_rule.provide_automatic_options: return await self.make_default_options_response() handler = self.view_functions[request_.url_rule.endpoint] return await handler(**request_.view_args)
[ "async", "def", "dispatch_request", "(", "self", ",", "request_context", ":", "Optional", "[", "RequestContext", "]", "=", "None", ",", ")", "->", "ResponseReturnValue", ":", "request_", "=", "(", "request_context", "or", "_request_ctx_stack", ".", "top", ")", ...
Dispatch the request to the view function. Arguments: request_context: The request context, optional as Flask omits this argument.
[ "Dispatch", "the", "request", "to", "the", "view", "function", "." ]
7cb2d3bd98e8746025764f2b933abc12041fa175
https://github.com/pgjones/quart/blob/7cb2d3bd98e8746025764f2b933abc12041fa175/quart/app.py#L1557-L1574
245,575
pgjones/quart
quart/app.py
Quart.process_response
async def process_response( self, response: Response, request_context: Optional[RequestContext]=None, ) -> Response: """Postprocess the request acting on the response. Arguments: response: The response after the request is finalized. request_context: The request context, optional as Flask omits this argument. """ request_ = (request_context or _request_ctx_stack.top).request functions = (request_context or _request_ctx_stack.top)._after_request_functions blueprint = request_.blueprint if blueprint is not None: functions = chain(functions, self.after_request_funcs[blueprint]) functions = chain(functions, self.after_request_funcs[None]) for function in functions: response = await function(response) session_ = (request_context or _request_ctx_stack.top).session if not self.session_interface.is_null_session(session_): await self.save_session(session_, response) return response
python
async def process_response( self, response: Response, request_context: Optional[RequestContext]=None, ) -> Response: request_ = (request_context or _request_ctx_stack.top).request functions = (request_context or _request_ctx_stack.top)._after_request_functions blueprint = request_.blueprint if blueprint is not None: functions = chain(functions, self.after_request_funcs[blueprint]) functions = chain(functions, self.after_request_funcs[None]) for function in functions: response = await function(response) session_ = (request_context or _request_ctx_stack.top).session if not self.session_interface.is_null_session(session_): await self.save_session(session_, response) return response
[ "async", "def", "process_response", "(", "self", ",", "response", ":", "Response", ",", "request_context", ":", "Optional", "[", "RequestContext", "]", "=", "None", ",", ")", "->", "Response", ":", "request_", "=", "(", "request_context", "or", "_request_ctx_s...
Postprocess the request acting on the response. Arguments: response: The response after the request is finalized. request_context: The request context, optional as Flask omits this argument.
[ "Postprocess", "the", "request", "acting", "on", "the", "response", "." ]
7cb2d3bd98e8746025764f2b933abc12041fa175
https://github.com/pgjones/quart/blob/7cb2d3bd98e8746025764f2b933abc12041fa175/quart/app.py#L1599-L1624
245,576
pgjones/quart
quart/app.py
Quart.full_dispatch_websocket
async def full_dispatch_websocket( self, websocket_context: Optional[WebsocketContext]=None, ) -> Optional[Response]: """Adds pre and post processing to the websocket dispatching. Arguments: websocket_context: The websocket context, optional to match the Flask convention. """ await self.try_trigger_before_first_request_functions() await websocket_started.send(self) try: result = await self.preprocess_websocket(websocket_context) if result is None: result = await self.dispatch_websocket(websocket_context) except Exception as error: result = await self.handle_user_exception(error) return await self.finalize_websocket(result, websocket_context)
python
async def full_dispatch_websocket( self, websocket_context: Optional[WebsocketContext]=None, ) -> Optional[Response]: await self.try_trigger_before_first_request_functions() await websocket_started.send(self) try: result = await self.preprocess_websocket(websocket_context) if result is None: result = await self.dispatch_websocket(websocket_context) except Exception as error: result = await self.handle_user_exception(error) return await self.finalize_websocket(result, websocket_context)
[ "async", "def", "full_dispatch_websocket", "(", "self", ",", "websocket_context", ":", "Optional", "[", "WebsocketContext", "]", "=", "None", ",", ")", "->", "Optional", "[", "Response", "]", ":", "await", "self", ".", "try_trigger_before_first_request_functions", ...
Adds pre and post processing to the websocket dispatching. Arguments: websocket_context: The websocket context, optional to match the Flask convention.
[ "Adds", "pre", "and", "post", "processing", "to", "the", "websocket", "dispatching", "." ]
7cb2d3bd98e8746025764f2b933abc12041fa175
https://github.com/pgjones/quart/blob/7cb2d3bd98e8746025764f2b933abc12041fa175/quart/app.py#L1635-L1652
245,577
pgjones/quart
quart/app.py
Quart.preprocess_websocket
async def preprocess_websocket( self, websocket_context: Optional[WebsocketContext]=None, ) -> Optional[ResponseReturnValue]: """Preprocess the websocket i.e. call before_websocket functions. Arguments: websocket_context: The websocket context, optional as Flask omits this argument. """ websocket_ = (websocket_context or _websocket_ctx_stack.top).websocket blueprint = websocket_.blueprint processors = self.url_value_preprocessors[None] if blueprint is not None: processors = chain(processors, self.url_value_preprocessors[blueprint]) # type: ignore for processor in processors: processor(websocket_.endpoint, websocket_.view_args) functions = self.before_websocket_funcs[None] if blueprint is not None: functions = chain(functions, self.before_websocket_funcs[blueprint]) # type: ignore for function in functions: result = await function() if result is not None: return result return None
python
async def preprocess_websocket( self, websocket_context: Optional[WebsocketContext]=None, ) -> Optional[ResponseReturnValue]: websocket_ = (websocket_context or _websocket_ctx_stack.top).websocket blueprint = websocket_.blueprint processors = self.url_value_preprocessors[None] if blueprint is not None: processors = chain(processors, self.url_value_preprocessors[blueprint]) # type: ignore for processor in processors: processor(websocket_.endpoint, websocket_.view_args) functions = self.before_websocket_funcs[None] if blueprint is not None: functions = chain(functions, self.before_websocket_funcs[blueprint]) # type: ignore for function in functions: result = await function() if result is not None: return result return None
[ "async", "def", "preprocess_websocket", "(", "self", ",", "websocket_context", ":", "Optional", "[", "WebsocketContext", "]", "=", "None", ",", ")", "->", "Optional", "[", "ResponseReturnValue", "]", ":", "websocket_", "=", "(", "websocket_context", "or", "_webs...
Preprocess the websocket i.e. call before_websocket functions. Arguments: websocket_context: The websocket context, optional as Flask omits this argument.
[ "Preprocess", "the", "websocket", "i", ".", "e", ".", "call", "before_websocket", "functions", "." ]
7cb2d3bd98e8746025764f2b933abc12041fa175
https://github.com/pgjones/quart/blob/7cb2d3bd98e8746025764f2b933abc12041fa175/quart/app.py#L1654-L1678
245,578
pgjones/quart
quart/app.py
Quart.dispatch_websocket
async def dispatch_websocket( self, websocket_context: Optional[WebsocketContext]=None, ) -> None: """Dispatch the websocket to the view function. Arguments: websocket_context: The websocket context, optional to match the Flask convention. """ websocket_ = (websocket_context or _websocket_ctx_stack.top).websocket if websocket_.routing_exception is not None: raise websocket_.routing_exception handler = self.view_functions[websocket_.url_rule.endpoint] return await handler(**websocket_.view_args)
python
async def dispatch_websocket( self, websocket_context: Optional[WebsocketContext]=None, ) -> None: websocket_ = (websocket_context or _websocket_ctx_stack.top).websocket if websocket_.routing_exception is not None: raise websocket_.routing_exception handler = self.view_functions[websocket_.url_rule.endpoint] return await handler(**websocket_.view_args)
[ "async", "def", "dispatch_websocket", "(", "self", ",", "websocket_context", ":", "Optional", "[", "WebsocketContext", "]", "=", "None", ",", ")", "->", "None", ":", "websocket_", "=", "(", "websocket_context", "or", "_websocket_ctx_stack", ".", "top", ")", "....
Dispatch the websocket to the view function. Arguments: websocket_context: The websocket context, optional to match the Flask convention.
[ "Dispatch", "the", "websocket", "to", "the", "view", "function", "." ]
7cb2d3bd98e8746025764f2b933abc12041fa175
https://github.com/pgjones/quart/blob/7cb2d3bd98e8746025764f2b933abc12041fa175/quart/app.py#L1680-L1694
245,579
pgjones/quart
quart/app.py
Quart.postprocess_websocket
async def postprocess_websocket( self, response: Optional[Response], websocket_context: Optional[WebsocketContext]=None, ) -> Response: """Postprocess the websocket acting on the response. Arguments: response: The response after the websocket is finalized. webcoket_context: The websocket context, optional as Flask omits this argument. """ websocket_ = (websocket_context or _websocket_ctx_stack.top).websocket functions = (websocket_context or _websocket_ctx_stack.top)._after_websocket_functions blueprint = websocket_.blueprint if blueprint is not None: functions = chain(functions, self.after_websocket_funcs[blueprint]) functions = chain(functions, self.after_websocket_funcs[None]) for function in functions: response = await function(response) session_ = (websocket_context or _request_ctx_stack.top).session if not self.session_interface.is_null_session(session_): if response is None and isinstance(session_, SecureCookieSession) and session_.modified: self.logger.exception( "Secure Cookie Session modified during websocket handling. " "These modifications will be lost as a cookie cannot be set." ) else: await self.save_session(session_, response) return response
python
async def postprocess_websocket( self, response: Optional[Response], websocket_context: Optional[WebsocketContext]=None, ) -> Response: websocket_ = (websocket_context or _websocket_ctx_stack.top).websocket functions = (websocket_context or _websocket_ctx_stack.top)._after_websocket_functions blueprint = websocket_.blueprint if blueprint is not None: functions = chain(functions, self.after_websocket_funcs[blueprint]) functions = chain(functions, self.after_websocket_funcs[None]) for function in functions: response = await function(response) session_ = (websocket_context or _request_ctx_stack.top).session if not self.session_interface.is_null_session(session_): if response is None and isinstance(session_, SecureCookieSession) and session_.modified: self.logger.exception( "Secure Cookie Session modified during websocket handling. " "These modifications will be lost as a cookie cannot be set." ) else: await self.save_session(session_, response) return response
[ "async", "def", "postprocess_websocket", "(", "self", ",", "response", ":", "Optional", "[", "Response", "]", ",", "websocket_context", ":", "Optional", "[", "WebsocketContext", "]", "=", "None", ",", ")", "->", "Response", ":", "websocket_", "=", "(", "webs...
Postprocess the websocket acting on the response. Arguments: response: The response after the websocket is finalized. webcoket_context: The websocket context, optional as Flask omits this argument.
[ "Postprocess", "the", "websocket", "acting", "on", "the", "response", "." ]
7cb2d3bd98e8746025764f2b933abc12041fa175
https://github.com/pgjones/quart/blob/7cb2d3bd98e8746025764f2b933abc12041fa175/quart/app.py#L1722-L1753
245,580
pgjones/quart
quart/ctx.py
after_this_request
def after_this_request(func: Callable) -> Callable: """Schedule the func to be called after the current request. This is useful in situations whereby you want an after request function for a specific route or circumstance only, for example, .. code-block:: python def index(): @after_this_request def set_cookie(response): response.set_cookie('special', 'value') return response ... """ _request_ctx_stack.top._after_request_functions.append(func) return func
python
def after_this_request(func: Callable) -> Callable: _request_ctx_stack.top._after_request_functions.append(func) return func
[ "def", "after_this_request", "(", "func", ":", "Callable", ")", "->", "Callable", ":", "_request_ctx_stack", ".", "top", ".", "_after_request_functions", ".", "append", "(", "func", ")", "return", "func" ]
Schedule the func to be called after the current request. This is useful in situations whereby you want an after request function for a specific route or circumstance only, for example, .. code-block:: python def index(): @after_this_request def set_cookie(response): response.set_cookie('special', 'value') return response ...
[ "Schedule", "the", "func", "to", "be", "called", "after", "the", "current", "request", "." ]
7cb2d3bd98e8746025764f2b933abc12041fa175
https://github.com/pgjones/quart/blob/7cb2d3bd98e8746025764f2b933abc12041fa175/quart/ctx.py#L183-L200
245,581
pgjones/quart
quart/ctx.py
after_this_websocket
def after_this_websocket(func: Callable) -> Callable: """Schedule the func to be called after the current websocket. This is useful in situations whereby you want an after websocket function for a specific route or circumstance only, for example, .. note:: The response is an optional argument, and will only be passed if the websocket was not active (i.e. there was an error). .. code-block:: python def index(): @after_this_websocket def set_cookie(response: Optional[Response]): response.set_cookie('special', 'value') return response ... """ _websocket_ctx_stack.top._after_websocket_functions.append(func) return func
python
def after_this_websocket(func: Callable) -> Callable: _websocket_ctx_stack.top._after_websocket_functions.append(func) return func
[ "def", "after_this_websocket", "(", "func", ":", "Callable", ")", "->", "Callable", ":", "_websocket_ctx_stack", ".", "top", ".", "_after_websocket_functions", ".", "append", "(", "func", ")", "return", "func" ]
Schedule the func to be called after the current websocket. This is useful in situations whereby you want an after websocket function for a specific route or circumstance only, for example, .. note:: The response is an optional argument, and will only be passed if the websocket was not active (i.e. there was an error). .. code-block:: python def index(): @after_this_websocket def set_cookie(response: Optional[Response]): response.set_cookie('special', 'value') return response ...
[ "Schedule", "the", "func", "to", "be", "called", "after", "the", "current", "websocket", "." ]
7cb2d3bd98e8746025764f2b933abc12041fa175
https://github.com/pgjones/quart/blob/7cb2d3bd98e8746025764f2b933abc12041fa175/quart/ctx.py#L203-L226
245,582
pgjones/quart
quart/ctx.py
copy_current_app_context
def copy_current_app_context(func: Callable) -> Callable: """Share the current app context with the function decorated. The app context is local per task and hence will not be available in any other task. This decorator can be used to make the context available, .. code-block:: python @copy_current_app_context async def within_context() -> None: name = current_app.name ... """ if not has_app_context(): raise RuntimeError('Attempt to copy app context outside of a app context') app_context = _app_ctx_stack.top.copy() @wraps(func) async def wrapper(*args: Any, **kwargs: Any) -> Any: async with app_context: return await func(*args, **kwargs) return wrapper
python
def copy_current_app_context(func: Callable) -> Callable: if not has_app_context(): raise RuntimeError('Attempt to copy app context outside of a app context') app_context = _app_ctx_stack.top.copy() @wraps(func) async def wrapper(*args: Any, **kwargs: Any) -> Any: async with app_context: return await func(*args, **kwargs) return wrapper
[ "def", "copy_current_app_context", "(", "func", ":", "Callable", ")", "->", "Callable", ":", "if", "not", "has_app_context", "(", ")", ":", "raise", "RuntimeError", "(", "'Attempt to copy app context outside of a app context'", ")", "app_context", "=", "_app_ctx_stack",...
Share the current app context with the function decorated. The app context is local per task and hence will not be available in any other task. This decorator can be used to make the context available, .. code-block:: python @copy_current_app_context async def within_context() -> None: name = current_app.name ...
[ "Share", "the", "current", "app", "context", "with", "the", "function", "decorated", "." ]
7cb2d3bd98e8746025764f2b933abc12041fa175
https://github.com/pgjones/quart/blob/7cb2d3bd98e8746025764f2b933abc12041fa175/quart/ctx.py#L229-L253
245,583
pgjones/quart
quart/ctx.py
copy_current_request_context
def copy_current_request_context(func: Callable) -> Callable: """Share the current request context with the function decorated. The request context is local per task and hence will not be available in any other task. This decorator can be used to make the context available, .. code-block:: python @copy_current_request_context async def within_context() -> None: method = request.method ... """ if not has_request_context(): raise RuntimeError('Attempt to copy request context outside of a request context') request_context = _request_ctx_stack.top.copy() @wraps(func) async def wrapper(*args: Any, **kwargs: Any) -> Any: async with request_context: return await func(*args, **kwargs) return wrapper
python
def copy_current_request_context(func: Callable) -> Callable: if not has_request_context(): raise RuntimeError('Attempt to copy request context outside of a request context') request_context = _request_ctx_stack.top.copy() @wraps(func) async def wrapper(*args: Any, **kwargs: Any) -> Any: async with request_context: return await func(*args, **kwargs) return wrapper
[ "def", "copy_current_request_context", "(", "func", ":", "Callable", ")", "->", "Callable", ":", "if", "not", "has_request_context", "(", ")", ":", "raise", "RuntimeError", "(", "'Attempt to copy request context outside of a request context'", ")", "request_context", "=",...
Share the current request context with the function decorated. The request context is local per task and hence will not be available in any other task. This decorator can be used to make the context available, .. code-block:: python @copy_current_request_context async def within_context() -> None: method = request.method ...
[ "Share", "the", "current", "request", "context", "with", "the", "function", "decorated", "." ]
7cb2d3bd98e8746025764f2b933abc12041fa175
https://github.com/pgjones/quart/blob/7cb2d3bd98e8746025764f2b933abc12041fa175/quart/ctx.py#L256-L280
245,584
pgjones/quart
quart/ctx.py
copy_current_websocket_context
def copy_current_websocket_context(func: Callable) -> Callable: """Share the current websocket context with the function decorated. The websocket context is local per task and hence will not be available in any other task. This decorator can be used to make the context available, .. code-block:: python @copy_current_websocket_context async def within_context() -> None: method = websocket.method ... """ if not has_websocket_context(): raise RuntimeError('Attempt to copy websocket context outside of a websocket context') websocket_context = _websocket_ctx_stack.top.copy() @wraps(func) async def wrapper(*args: Any, **kwargs: Any) -> Any: async with websocket_context: return await func(*args, **kwargs) return wrapper
python
def copy_current_websocket_context(func: Callable) -> Callable: if not has_websocket_context(): raise RuntimeError('Attempt to copy websocket context outside of a websocket context') websocket_context = _websocket_ctx_stack.top.copy() @wraps(func) async def wrapper(*args: Any, **kwargs: Any) -> Any: async with websocket_context: return await func(*args, **kwargs) return wrapper
[ "def", "copy_current_websocket_context", "(", "func", ":", "Callable", ")", "->", "Callable", ":", "if", "not", "has_websocket_context", "(", ")", ":", "raise", "RuntimeError", "(", "'Attempt to copy websocket context outside of a websocket context'", ")", "websocket_contex...
Share the current websocket context with the function decorated. The websocket context is local per task and hence will not be available in any other task. This decorator can be used to make the context available, .. code-block:: python @copy_current_websocket_context async def within_context() -> None: method = websocket.method ...
[ "Share", "the", "current", "websocket", "context", "with", "the", "function", "decorated", "." ]
7cb2d3bd98e8746025764f2b933abc12041fa175
https://github.com/pgjones/quart/blob/7cb2d3bd98e8746025764f2b933abc12041fa175/quart/ctx.py#L283-L307
245,585
pgjones/quart
quart/ctx.py
_BaseRequestWebsocketContext.match_request
def match_request(self) -> None: """Match the request against the adapter. Override this method to configure request matching, it should set the request url_rule and view_args and optionally a routing_exception. """ try: self.request_websocket.url_rule, self.request_websocket.view_args = self.url_adapter.match() # noqa except (NotFound, MethodNotAllowed, RedirectRequired) as error: self.request_websocket.routing_exception = error
python
def match_request(self) -> None: try: self.request_websocket.url_rule, self.request_websocket.view_args = self.url_adapter.match() # noqa except (NotFound, MethodNotAllowed, RedirectRequired) as error: self.request_websocket.routing_exception = error
[ "def", "match_request", "(", "self", ")", "->", "None", ":", "try", ":", "self", ".", "request_websocket", ".", "url_rule", ",", "self", ".", "request_websocket", ".", "view_args", "=", "self", ".", "url_adapter", ".", "match", "(", ")", "# noqa", "except"...
Match the request against the adapter. Override this method to configure request matching, it should set the request url_rule and view_args and optionally a routing_exception.
[ "Match", "the", "request", "against", "the", "adapter", "." ]
7cb2d3bd98e8746025764f2b933abc12041fa175
https://github.com/pgjones/quart/blob/7cb2d3bd98e8746025764f2b933abc12041fa175/quart/ctx.py#L37-L47
245,586
pgjones/quart
quart/ctx.py
_AppCtxGlobals.get
def get(self, name: str, default: Optional[Any]=None) -> Any: """Get a named attribute of this instance, or return the default.""" return self.__dict__.get(name, default)
python
def get(self, name: str, default: Optional[Any]=None) -> Any: return self.__dict__.get(name, default)
[ "def", "get", "(", "self", ",", "name", ":", "str", ",", "default", ":", "Optional", "[", "Any", "]", "=", "None", ")", "->", "Any", ":", "return", "self", ".", "__dict__", ".", "get", "(", "name", ",", "default", ")" ]
Get a named attribute of this instance, or return the default.
[ "Get", "a", "named", "attribute", "of", "this", "instance", "or", "return", "the", "default", "." ]
7cb2d3bd98e8746025764f2b933abc12041fa175
https://github.com/pgjones/quart/blob/7cb2d3bd98e8746025764f2b933abc12041fa175/quart/ctx.py#L364-L366
245,587
pgjones/quart
quart/ctx.py
_AppCtxGlobals.pop
def pop(self, name: str, default: Any=_sentinel) -> Any: """Pop, get and remove the named attribute of this instance.""" if default is _sentinel: return self.__dict__.pop(name) else: return self.__dict__.pop(name, default)
python
def pop(self, name: str, default: Any=_sentinel) -> Any: if default is _sentinel: return self.__dict__.pop(name) else: return self.__dict__.pop(name, default)
[ "def", "pop", "(", "self", ",", "name", ":", "str", ",", "default", ":", "Any", "=", "_sentinel", ")", "->", "Any", ":", "if", "default", "is", "_sentinel", ":", "return", "self", ".", "__dict__", ".", "pop", "(", "name", ")", "else", ":", "return"...
Pop, get and remove the named attribute of this instance.
[ "Pop", "get", "and", "remove", "the", "named", "attribute", "of", "this", "instance", "." ]
7cb2d3bd98e8746025764f2b933abc12041fa175
https://github.com/pgjones/quart/blob/7cb2d3bd98e8746025764f2b933abc12041fa175/quart/ctx.py#L368-L373
245,588
pgjones/quart
quart/ctx.py
_AppCtxGlobals.setdefault
def setdefault(self, name: str, default: Any=None) -> Any: """Set an attribute with a default value.""" return self.__dict__.setdefault(name, default)
python
def setdefault(self, name: str, default: Any=None) -> Any: return self.__dict__.setdefault(name, default)
[ "def", "setdefault", "(", "self", ",", "name", ":", "str", ",", "default", ":", "Any", "=", "None", ")", "->", "Any", ":", "return", "self", ".", "__dict__", ".", "setdefault", "(", "name", ",", "default", ")" ]
Set an attribute with a default value.
[ "Set", "an", "attribute", "with", "a", "default", "value", "." ]
7cb2d3bd98e8746025764f2b933abc12041fa175
https://github.com/pgjones/quart/blob/7cb2d3bd98e8746025764f2b933abc12041fa175/quart/ctx.py#L375-L377
245,589
pgjones/quart
quart/sessions.py
SessionInterface.get_cookie_domain
def get_cookie_domain(self, app: 'Quart') -> Optional[str]: """Helper method to return the Cookie Domain for the App.""" if app.config['SESSION_COOKIE_DOMAIN'] is not None: return app.config['SESSION_COOKIE_DOMAIN'] elif app.config['SERVER_NAME'] is not None: return '.' + app.config['SERVER_NAME'].rsplit(':', 1)[0] else: return None
python
def get_cookie_domain(self, app: 'Quart') -> Optional[str]: if app.config['SESSION_COOKIE_DOMAIN'] is not None: return app.config['SESSION_COOKIE_DOMAIN'] elif app.config['SERVER_NAME'] is not None: return '.' + app.config['SERVER_NAME'].rsplit(':', 1)[0] else: return None
[ "def", "get_cookie_domain", "(", "self", ",", "app", ":", "'Quart'", ")", "->", "Optional", "[", "str", "]", ":", "if", "app", ".", "config", "[", "'SESSION_COOKIE_DOMAIN'", "]", "is", "not", "None", ":", "return", "app", ".", "config", "[", "'SESSION_CO...
Helper method to return the Cookie Domain for the App.
[ "Helper", "method", "to", "return", "the", "Cookie", "Domain", "for", "the", "App", "." ]
7cb2d3bd98e8746025764f2b933abc12041fa175
https://github.com/pgjones/quart/blob/7cb2d3bd98e8746025764f2b933abc12041fa175/quart/sessions.py#L129-L136
245,590
pgjones/quart
quart/sessions.py
SessionInterface.get_expiration_time
def get_expiration_time(self, app: 'Quart', session: SessionMixin) -> Optional[datetime]: """Helper method to return the Session expiration time. If the session is not 'permanent' it will expire as and when the browser stops accessing the app. """ if session.permanent: return datetime.utcnow() + app.permanent_session_lifetime else: return None
python
def get_expiration_time(self, app: 'Quart', session: SessionMixin) -> Optional[datetime]: if session.permanent: return datetime.utcnow() + app.permanent_session_lifetime else: return None
[ "def", "get_expiration_time", "(", "self", ",", "app", ":", "'Quart'", ",", "session", ":", "SessionMixin", ")", "->", "Optional", "[", "datetime", "]", ":", "if", "session", ".", "permanent", ":", "return", "datetime", ".", "utcnow", "(", ")", "+", "app...
Helper method to return the Session expiration time. If the session is not 'permanent' it will expire as and when the browser stops accessing the app.
[ "Helper", "method", "to", "return", "the", "Session", "expiration", "time", "." ]
7cb2d3bd98e8746025764f2b933abc12041fa175
https://github.com/pgjones/quart/blob/7cb2d3bd98e8746025764f2b933abc12041fa175/quart/sessions.py#L150-L159
245,591
pgjones/quart
quart/sessions.py
SessionInterface.should_set_cookie
def should_set_cookie(self, app: 'Quart', session: SessionMixin) -> bool: """Helper method to return if the Set Cookie header should be present. This triggers if the session is marked as modified or the app is configured to always refresh the cookie. """ if session.modified: return True save_each = app.config['SESSION_REFRESH_EACH_REQUEST'] return save_each and session.permanent
python
def should_set_cookie(self, app: 'Quart', session: SessionMixin) -> bool: if session.modified: return True save_each = app.config['SESSION_REFRESH_EACH_REQUEST'] return save_each and session.permanent
[ "def", "should_set_cookie", "(", "self", ",", "app", ":", "'Quart'", ",", "session", ":", "SessionMixin", ")", "->", "bool", ":", "if", "session", ".", "modified", ":", "return", "True", "save_each", "=", "app", ".", "config", "[", "'SESSION_REFRESH_EACH_REQ...
Helper method to return if the Set Cookie header should be present. This triggers if the session is marked as modified or the app is configured to always refresh the cookie.
[ "Helper", "method", "to", "return", "if", "the", "Set", "Cookie", "header", "should", "be", "present", "." ]
7cb2d3bd98e8746025764f2b933abc12041fa175
https://github.com/pgjones/quart/blob/7cb2d3bd98e8746025764f2b933abc12041fa175/quart/sessions.py#L161-L170
245,592
pgjones/quart
quart/sessions.py
SecureCookieSessionInterface.get_signing_serializer
def get_signing_serializer(self, app: 'Quart') -> Optional[URLSafeTimedSerializer]: """Return a serializer for the session that also signs data. This will return None if the app is not configured for secrets. """ if not app.secret_key: return None options = { 'key_derivation': self.key_derivation, 'digest_method': self.digest_method, } return URLSafeTimedSerializer( app.secret_key, salt=self.salt, serializer=self.serializer, signer_kwargs=options, )
python
def get_signing_serializer(self, app: 'Quart') -> Optional[URLSafeTimedSerializer]: if not app.secret_key: return None options = { 'key_derivation': self.key_derivation, 'digest_method': self.digest_method, } return URLSafeTimedSerializer( app.secret_key, salt=self.salt, serializer=self.serializer, signer_kwargs=options, )
[ "def", "get_signing_serializer", "(", "self", ",", "app", ":", "'Quart'", ")", "->", "Optional", "[", "URLSafeTimedSerializer", "]", ":", "if", "not", "app", ".", "secret_key", ":", "return", "None", "options", "=", "{", "'key_derivation'", ":", "self", ".",...
Return a serializer for the session that also signs data. This will return None if the app is not configured for secrets.
[ "Return", "a", "serializer", "for", "the", "session", "that", "also", "signs", "data", "." ]
7cb2d3bd98e8746025764f2b933abc12041fa175
https://github.com/pgjones/quart/blob/7cb2d3bd98e8746025764f2b933abc12041fa175/quart/sessions.py#L204-L218
245,593
pgjones/quart
quart/sessions.py
SecureCookieSessionInterface.open_session
async def open_session( self, app: 'Quart', request: BaseRequestWebsocket, ) -> Optional[SecureCookieSession]: """Open a secure cookie based session. This will return None if a signing serializer is not availabe, usually if the config SECRET_KEY is not set. """ signer = self.get_signing_serializer(app) if signer is None: return None cookie = request.cookies.get(app.session_cookie_name) if cookie is None: return self.session_class() try: data = signer.loads( cookie, max_age=app.permanent_session_lifetime.total_seconds(), ) return self.session_class(**data) except BadSignature: return self.session_class()
python
async def open_session( self, app: 'Quart', request: BaseRequestWebsocket, ) -> Optional[SecureCookieSession]: signer = self.get_signing_serializer(app) if signer is None: return None cookie = request.cookies.get(app.session_cookie_name) if cookie is None: return self.session_class() try: data = signer.loads( cookie, max_age=app.permanent_session_lifetime.total_seconds(), ) return self.session_class(**data) except BadSignature: return self.session_class()
[ "async", "def", "open_session", "(", "self", ",", "app", ":", "'Quart'", ",", "request", ":", "BaseRequestWebsocket", ",", ")", "->", "Optional", "[", "SecureCookieSession", "]", ":", "signer", "=", "self", ".", "get_signing_serializer", "(", "app", ")", "if...
Open a secure cookie based session. This will return None if a signing serializer is not availabe, usually if the config SECRET_KEY is not set.
[ "Open", "a", "secure", "cookie", "based", "session", "." ]
7cb2d3bd98e8746025764f2b933abc12041fa175
https://github.com/pgjones/quart/blob/7cb2d3bd98e8746025764f2b933abc12041fa175/quart/sessions.py#L220-L243
245,594
pgjones/quart
quart/sessions.py
SecureCookieSessionInterface.save_session
async def save_session( # type: ignore self, app: 'Quart', session: SecureCookieSession, response: Response, ) -> None: """Saves the session to the response in a secure cookie.""" domain = self.get_cookie_domain(app) path = self.get_cookie_path(app) if not session: if session.modified: response.delete_cookie(app.session_cookie_name, domain=domain, path=path) return if session.accessed: response.vary.add('Cookie') if not self.should_set_cookie(app, session): return data = self.get_signing_serializer(app).dumps(dict(session)) response.set_cookie( app.session_cookie_name, data, expires=self.get_expiration_time(app, session), httponly=self.get_cookie_httponly(app), domain=domain, path=path, secure=self.get_cookie_secure(app), )
python
async def save_session( # type: ignore self, app: 'Quart', session: SecureCookieSession, response: Response, ) -> None: domain = self.get_cookie_domain(app) path = self.get_cookie_path(app) if not session: if session.modified: response.delete_cookie(app.session_cookie_name, domain=domain, path=path) return if session.accessed: response.vary.add('Cookie') if not self.should_set_cookie(app, session): return data = self.get_signing_serializer(app).dumps(dict(session)) response.set_cookie( app.session_cookie_name, data, expires=self.get_expiration_time(app, session), httponly=self.get_cookie_httponly(app), domain=domain, path=path, secure=self.get_cookie_secure(app), )
[ "async", "def", "save_session", "(", "# type: ignore", "self", ",", "app", ":", "'Quart'", ",", "session", ":", "SecureCookieSession", ",", "response", ":", "Response", ",", ")", "->", "None", ":", "domain", "=", "self", ".", "get_cookie_domain", "(", "app",...
Saves the session to the response in a secure cookie.
[ "Saves", "the", "session", "to", "the", "response", "in", "a", "secure", "cookie", "." ]
7cb2d3bd98e8746025764f2b933abc12041fa175
https://github.com/pgjones/quart/blob/7cb2d3bd98e8746025764f2b933abc12041fa175/quart/sessions.py#L245-L271
245,595
pgjones/quart
quart/wrappers/response.py
Response.get_data
async def get_data(self, raw: bool=True) -> AnyStr: """Return the body data.""" if self.implicit_sequence_conversion: self.response = self.data_body_class(await self.response.convert_to_sequence()) result = b'' if raw else '' async with self.response as body: # type: ignore async for data in body: if raw: result += data else: result += data.decode(self.charset) return result
python
async def get_data(self, raw: bool=True) -> AnyStr: if self.implicit_sequence_conversion: self.response = self.data_body_class(await self.response.convert_to_sequence()) result = b'' if raw else '' async with self.response as body: # type: ignore async for data in body: if raw: result += data else: result += data.decode(self.charset) return result
[ "async", "def", "get_data", "(", "self", ",", "raw", ":", "bool", "=", "True", ")", "->", "AnyStr", ":", "if", "self", ".", "implicit_sequence_conversion", ":", "self", ".", "response", "=", "self", ".", "data_body_class", "(", "await", "self", ".", "res...
Return the body data.
[ "Return", "the", "body", "data", "." ]
7cb2d3bd98e8746025764f2b933abc12041fa175
https://github.com/pgjones/quart/blob/7cb2d3bd98e8746025764f2b933abc12041fa175/quart/wrappers/response.py#L272-L283
245,596
pgjones/quart
quart/wrappers/response.py
Response.set_data
def set_data(self, data: AnyStr) -> None: """Set the response data. This will encode using the :attr:`charset`. """ if isinstance(data, str): bytes_data = data.encode(self.charset) else: bytes_data = data self.response = self.data_body_class(bytes_data) if self.automatically_set_content_length: self.content_length = len(bytes_data)
python
def set_data(self, data: AnyStr) -> None: if isinstance(data, str): bytes_data = data.encode(self.charset) else: bytes_data = data self.response = self.data_body_class(bytes_data) if self.automatically_set_content_length: self.content_length = len(bytes_data)
[ "def", "set_data", "(", "self", ",", "data", ":", "AnyStr", ")", "->", "None", ":", "if", "isinstance", "(", "data", ",", "str", ")", ":", "bytes_data", "=", "data", ".", "encode", "(", "self", ".", "charset", ")", "else", ":", "bytes_data", "=", "...
Set the response data. This will encode using the :attr:`charset`.
[ "Set", "the", "response", "data", "." ]
7cb2d3bd98e8746025764f2b933abc12041fa175
https://github.com/pgjones/quart/blob/7cb2d3bd98e8746025764f2b933abc12041fa175/quart/wrappers/response.py#L285-L296
245,597
pgjones/quart
quart/wrappers/response.py
Response.make_conditional
async def make_conditional( self, request_range: Range, max_partial_size: Optional[int]=None, ) -> None: """Make the response conditional to the Arguments: request_range: The range as requested by the request. max_partial_size: The maximum length the server is willing to serve in a single response. Defaults to unlimited. """ self.accept_ranges = "bytes" # Advertise this ability if len(request_range.ranges) == 0: # Not a conditional request return if request_range.units != "bytes" or len(request_range.ranges) > 1: from ..exceptions import RequestRangeNotSatisfiable raise RequestRangeNotSatisfiable() begin, end = request_range.ranges[0] try: complete_length = await self.response.make_conditional( # type: ignore begin, end, max_partial_size, ) except AttributeError: self.response = self.data_body_class(await self.response.convert_to_sequence()) return await self.make_conditional(request_range, max_partial_size) else: self.content_length = self.response.end - self.response.begin # type: ignore if self.content_length != complete_length: self.content_range = ContentRange( request_range.units, self.response.begin, self.response.end - 1, # type: ignore complete_length, ) self.status_code = 206
python
async def make_conditional( self, request_range: Range, max_partial_size: Optional[int]=None, ) -> None: self.accept_ranges = "bytes" # Advertise this ability if len(request_range.ranges) == 0: # Not a conditional request return if request_range.units != "bytes" or len(request_range.ranges) > 1: from ..exceptions import RequestRangeNotSatisfiable raise RequestRangeNotSatisfiable() begin, end = request_range.ranges[0] try: complete_length = await self.response.make_conditional( # type: ignore begin, end, max_partial_size, ) except AttributeError: self.response = self.data_body_class(await self.response.convert_to_sequence()) return await self.make_conditional(request_range, max_partial_size) else: self.content_length = self.response.end - self.response.begin # type: ignore if self.content_length != complete_length: self.content_range = ContentRange( request_range.units, self.response.begin, self.response.end - 1, # type: ignore complete_length, ) self.status_code = 206
[ "async", "def", "make_conditional", "(", "self", ",", "request_range", ":", "Range", ",", "max_partial_size", ":", "Optional", "[", "int", "]", "=", "None", ",", ")", "->", "None", ":", "self", ".", "accept_ranges", "=", "\"bytes\"", "# Advertise this ability"...
Make the response conditional to the Arguments: request_range: The range as requested by the request. max_partial_size: The maximum length the server is willing to serve in a single response. Defaults to unlimited.
[ "Make", "the", "response", "conditional", "to", "the" ]
7cb2d3bd98e8746025764f2b933abc12041fa175
https://github.com/pgjones/quart/blob/7cb2d3bd98e8746025764f2b933abc12041fa175/quart/wrappers/response.py#L298-L335
245,598
pgjones/quart
quart/wrappers/response.py
Response.set_cookie
def set_cookie( # type: ignore self, key: str, value: AnyStr='', max_age: Optional[Union[int, timedelta]]=None, expires: Optional[datetime]=None, path: str='/', domain: Optional[str]=None, secure: bool=False, httponly: bool=False, ) -> None: """Set a cookie in the response headers. The arguments are the standard cookie morsels and this is a wrapper around the stdlib SimpleCookie code. """ if isinstance(value, bytes): value = value.decode() # type: ignore cookie = create_cookie(key, value, max_age, expires, path, domain, secure, httponly) # type: ignore # noqa: E501 self.headers.add('Set-Cookie', cookie.output(header=''))
python
def set_cookie( # type: ignore self, key: str, value: AnyStr='', max_age: Optional[Union[int, timedelta]]=None, expires: Optional[datetime]=None, path: str='/', domain: Optional[str]=None, secure: bool=False, httponly: bool=False, ) -> None: if isinstance(value, bytes): value = value.decode() # type: ignore cookie = create_cookie(key, value, max_age, expires, path, domain, secure, httponly) # type: ignore # noqa: E501 self.headers.add('Set-Cookie', cookie.output(header=''))
[ "def", "set_cookie", "(", "# type: ignore", "self", ",", "key", ":", "str", ",", "value", ":", "AnyStr", "=", "''", ",", "max_age", ":", "Optional", "[", "Union", "[", "int", ",", "timedelta", "]", "]", "=", "None", ",", "expires", ":", "Optional", "...
Set a cookie in the response headers. The arguments are the standard cookie morsels and this is a wrapper around the stdlib SimpleCookie code.
[ "Set", "a", "cookie", "in", "the", "response", "headers", "." ]
7cb2d3bd98e8746025764f2b933abc12041fa175
https://github.com/pgjones/quart/blob/7cb2d3bd98e8746025764f2b933abc12041fa175/quart/wrappers/response.py#L341-L360
245,599
pgjones/quart
quart/routing.py
Rule.match
def match(self, path: str) -> Tuple[Optional[Dict[str, Any]], bool]: """Check if the path matches this Rule. If it does it returns a dict of matched and converted values, otherwise None is returned. """ match = self._pattern.match(path) if match is not None: # If the route is a branch (not leaf) and the path is # missing a trailing slash then it needs one to be # considered a match in the strict slashes mode. needs_slash = ( self.strict_slashes and not self.is_leaf and match.groupdict()['__slash__'] != '/' ) try: converted_varaibles = { name: self._converters[name].to_python(value) for name, value in match.groupdict().items() if name != '__slash__' } except ValidationError: # Doesn't meet conversion rules, no match return None, False else: return {**self.defaults, **converted_varaibles}, needs_slash else: return None, False
python
def match(self, path: str) -> Tuple[Optional[Dict[str, Any]], bool]: match = self._pattern.match(path) if match is not None: # If the route is a branch (not leaf) and the path is # missing a trailing slash then it needs one to be # considered a match in the strict slashes mode. needs_slash = ( self.strict_slashes and not self.is_leaf and match.groupdict()['__slash__'] != '/' ) try: converted_varaibles = { name: self._converters[name].to_python(value) for name, value in match.groupdict().items() if name != '__slash__' } except ValidationError: # Doesn't meet conversion rules, no match return None, False else: return {**self.defaults, **converted_varaibles}, needs_slash else: return None, False
[ "def", "match", "(", "self", ",", "path", ":", "str", ")", "->", "Tuple", "[", "Optional", "[", "Dict", "[", "str", ",", "Any", "]", "]", ",", "bool", "]", ":", "match", "=", "self", ".", "_pattern", ".", "match", "(", "path", ")", "if", "match...
Check if the path matches this Rule. If it does it returns a dict of matched and converted values, otherwise None is returned.
[ "Check", "if", "the", "path", "matches", "this", "Rule", "." ]
7cb2d3bd98e8746025764f2b933abc12041fa175
https://github.com/pgjones/quart/blob/7cb2d3bd98e8746025764f2b933abc12041fa175/quart/routing.py#L335-L360