INSTRUCTION stringlengths 1 46.3k | RESPONSE stringlengths 75 80.2k |
|---|---|
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. | 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 handle... |
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. | 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.
... |
Handle an uncaught exception.
By default this switches the error response to a 500 internal
server error. | async def handle_exception(self, error: Exception) -> Response:
"""Handle an uncaught exception.
By default this switches the error response to a 500 internal
server error.
"""
await got_request_exception.send(self, exception=error)
self.log_exception(sys.exc_info())
... |
Handle an uncaught exception.
By default this logs the exception and then re-raises it. | async def handle_websocket_exception(self, error: Exception) -> Optional[Response]:
"""Handle an uncaught exception.
By default this logs the exception and then re-raises it.
"""
await got_websocket_exception.send(self, exception=error)
self.log_exception(sys.exc_info())
... |
Log a exception to the :attr:`logger`.
By default this is only invoked for unhandled exceptions. | def log_exception(self, exception_info: Tuple[type, BaseException, TracebackType]) -> None:
"""Log a exception to the :attr:`logger`.
By default this is only invoked for unhandled exceptions.
"""
if has_request_context():
request_ = _request_ctx_stack.top.request
... |
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 blueprin... | 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():
...
Argum... |
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 bl... | 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():
...
... |
Add a before **first** request function.
This is designed to be used as a decorator. An example usage,
.. code-block:: python
@app.before_first_request
def func():
...
Arguments:
func: The before first request function itself.
n... | def before_first_request(self, func: Callable, name: AppOrBlueprintKey=None) -> Callable:
"""Add a before **first** request function.
This is designed to be used as a decorator. An example usage,
.. code-block:: python
@app.before_first_request
def 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():... | 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:... |
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:... | 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 respo... |
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.
... | 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... |
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():
... | 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:: pytho... |
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 bl... | 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():
...
... |
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: Optio... | 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():
...
... |
Add a teardown app (context) function.
This is designed to be used as a decorator. An example usage,
.. code-block:: python
@app.teardown_appcontext
def func():
...
Arguments:
func: The teardown function itself.
name: Optional b... | def teardown_appcontext(self, func: Callable) -> Callable:
"""Add a teardown app (context) function.
This is designed to be used as a decorator. An example usage,
.. code-block:: python
@app.teardown_appcontext
def func():
...
Arguments:
... |
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. | 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.
... |
Open and return a Session using the request. | 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) |
Saves the session to the response. | 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) |
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. | 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 reques... |
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. | 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 th... |
Teardown the app (context), calling the teardown functions. | async def do_teardown_appcontext(self, exc: Optional[BaseException]) -> None:
"""Teardown the app (context), calling the teardown functions."""
for function in self.teardown_appcontext_funcs:
await function(exc)
await appcontext_tearing_down.send(self, exc=exc) |
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... | 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,
... |
Trigger the before first request methods. | 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.tear... |
This is the default route function for OPTIONS requests. | 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)}) |
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 R... | 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 Respons... |
Adds pre and post processing to the request dispatching.
Arguments:
request_context: The request context, optional as Flask
omits this argument. | 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.
"""
... |
Preprocess the request i.e. call before_request functions.
Arguments:
request_context: The request context, optional as Flask
omits this argument. | 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 arg... |
Dispatch the request to the view function.
Arguments:
request_context: The request context, optional as Flask
omits this argument. | 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.
"""
r... |
Turns the view response return value into a response.
Arguments:
result: The result of the request to finalize into a response.
request_context: The request context, optional as Flask
omits this argument. | async def finalize_request(
self,
result: ResponseReturnValue,
request_context: Optional[RequestContext]=None,
from_error_handler: bool=False,
) -> Response:
"""Turns the view response return value into a response.
Arguments:
result: The result of the req... |
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. | 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: ... |
Adds pre and post processing to the websocket dispatching.
Arguments:
websocket_context: The websocket context, optional to match
the Flask convention. | 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 co... |
Preprocess the websocket i.e. call before_websocket functions.
Arguments:
websocket_context: The websocket context, optional as Flask
omits this argument. | 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
... |
Dispatch the websocket to the view function.
Arguments:
websocket_context: The websocket context, optional to match
the Flask convention. | 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.
"""
web... |
Turns the view response return value into a response.
Arguments:
result: The result of the websocket to finalize into a response.
websocket_context: The websocket context, optional as Flask
omits this argument. | async def finalize_websocket(
self,
result: ResponseReturnValue,
websocket_context: Optional[WebsocketContext]=None,
from_error_handler: bool=False,
) -> Optional[Response]:
"""Turns the view response return value into a response.
Arguments:
result: The r... |
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. | 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.
... |
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):
... | 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():
@aft... |
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 act... | 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,... |
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... | 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
@co... |
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_conte... | 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
... |
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... | 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:: p... |
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. | 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.... |
Get a named attribute of this instance, or return the default. | 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) |
Pop, get and remove the named attribute of this instance. | 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) |
Set an attribute with a default value. | def setdefault(self, name: str, default: Any=None) -> Any:
"""Set an attribute with a default value."""
return self.__dict__.setdefault(name, default) |
Helper method to return the Cookie Domain for the App. | 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 '.' +... |
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. | 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:
... |
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. | 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 a serializer for the session that also signs data.
This will return None if the app is not configured for secrets. | 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 = {
... |
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. | 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 se... |
Saves the session to the response in a secure cookie. | 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:
... |
Return the body 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
... |
Set the response data.
This will encode using the :attr:`charset`. | 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... |
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. | 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... |
Set a cookie in the response headers.
The arguments are the standard cookie morsels and this is a
wrapper around the stdlib SimpleCookie code. | 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,
ht... |
Delete a cookie (set to expire immediately). | def delete_cookie(self, key: str, path: str='/', domain: Optional[str]=None) -> None:
"""Delete a cookie (set to expire immediately)."""
self.set_cookie(key, expires=datetime.utcnow(), max_age=0, path=path, domain=domain) |
Check if the path matches this Rule.
If it does it returns a dict of matched and converted values,
otherwise None is returned. | 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:
... |
Returns true if this rule provides defaults for the argument and values. | def provides_defaults_for(self, rule: 'Rule', **values: Any) -> bool:
"""Returns true if this rule provides defaults for the argument and values."""
defaults_match = all(
values[key] == self.defaults[key] for key in self.defaults if key in values # noqa: S101, E501
)
return ... |
Build this rule into a path using the values given. | def build(self, **values: Any) -> str:
"""Build this rule into a path using the values given."""
converted_values = {
key: self._converters[key].to_url(value)
for key, value in values.items()
if key in self._converters
}
result = self._builder.format(*... |
Return True if this rule can build with the values and method. | def buildable(self, values: Optional[dict]=None, method: Optional[str]=None) -> bool:
"""Return True if this rule can build with the values and method."""
if method is not None and method not in self.methods:
return False
defaults_match = all(
values[key] == self.defaults... |
Bind the Rule to a Map and compile it. | def bind(self, map: Map) -> None:
"""Bind the Rule to a Map and compile it."""
if self.map is not None:
raise RuntimeError(f"{self!r} is already bound to {self.map!r}")
self.map = map
pattern = ''
builder = ''
full_rule = "{}\\|{}".format(self.host or '', se... |
A Key to sort the rules by weight for matching.
The key leads to ordering:
- By first order by defaults as they are simple rules without
conversions.
- Then on the complexity of the rule, i.e. does it have any
converted parts. This is as simple rules are quick to match
... | def match_key(self) -> Tuple[bool, bool, int, List[WeightedPart]]:
"""A Key to sort the rules by weight for matching.
The key leads to ordering:
- By first order by defaults as they are simple rules without
conversions.
- Then on the complexity of the rule, i.e. does it ha... |
Returns a crop of `img` based on a sequence number `tile_number`.
:param int tile_number: Number of the tile between 0 and `max_tiles`^2.
:raises TileOutOfBoundsError: When `tile_number` exceeds `max_tiles`^2
:rtype PIL.Image: | def get_tile(tile_number):
"""
Returns a crop of `img` based on a sequence number `tile_number`.
:param int tile_number: Number of the tile between 0 and `max_tiles`^2.
:raises TileOutOfBoundsError: When `tile_number` exceeds `max_tiles`^2
:rtype PIL.Image:
"""
tile_number = int(tile_number... |
A Key to sort the rules by weight for building.
The key leads to ordering:
- By routes with defaults first, as these must be evaulated
for building before ones without.
- Then the more complex routes (most converted parts). | def build_key(self) -> Tuple[bool, int]:
"""A Key to sort the rules by weight for building.
The key leads to ordering:
- By routes with defaults first, as these must be evaulated
for building before ones without.
- Then the more complex routes (most converted parts).
... |
Handles GET requests for a tile number.
:param int tile_number: Number of the tile between 0 and `max_tiles`^2.
:raises HTTPError: 404 if tile exceeds `max_tiles`^2. | async def tile(tile_number):
"""
Handles GET requests for a tile number.
:param int tile_number: Number of the tile between 0 and `max_tiles`^2.
:raises HTTPError: 404 if tile exceeds `max_tiles`^2.
"""
try:
tile = get_tile(tile_number)
except TileOutOfBoundsError:
abort(404... |
Returns True if the content_type is json like. | def is_json(self) -> bool:
"""Returns True if the content_type is json like."""
content_type = self.mimetype
if content_type == 'application/json' or (
content_type.startswith('application/') and content_type.endswith('+json')
):
return True
else:
... |
Parses the body data as JSON and returns it.
Arguments:
force: Force JSON parsing even if the mimetype is not JSON.
silent: Do not trigger error handling if parsing fails, without
this the :meth:`on_json_loading_failed` will be called on
error.
... | async def get_json(
self, force: bool=False, silent: bool=False, cache: bool=True,
) -> Any:
"""Parses the body data as JSON and returns it.
Arguments:
force: Force JSON parsing even if the mimetype is not JSON.
silent: Do not trigger error handling if parsing fails,... |
Set the mimetype to the value. | def mimetype(self, value: str) -> None:
"""Set the mimetype to the value."""
if (
value.startswith('text/') or value == 'application/xml' or
(value.startswith('application/') and value.endswith('+xml'))
):
mimetype = f"{value}; charset={self.charset}"
... |
Returns the blueprint the matched endpoint belongs to.
This can be None if the request has not been matched or the
endpoint is not in a blueprint. | def blueprint(self) -> Optional[str]:
"""Returns the blueprint the matched endpoint belongs to.
This can be None if the request has not been matched or the
endpoint is not in a blueprint.
"""
if self.endpoint is not None and '.' in self.endpoint:
return self.endpoint... |
Returns the base url without query string or fragments. | def base_url(self) -> str:
"""Returns the base url without query string or fragments."""
return urlunparse(ParseResult(self.scheme, self.host, self.path, '', '', '')) |
Returns the full url requested. | def url(self) -> str:
"""Returns the full url requested."""
return urlunparse(
ParseResult(
self.scheme, self.host, self.path, '', self.query_string.decode('ascii'), '',
),
) |
The parsed cookies attached to this request. | def cookies(self) -> Dict[str, str]:
"""The parsed cookies attached to this request."""
cookies = SimpleCookie()
cookies.load(self.headers.get('Cookie', ''))
return {key: cookie.value for key, cookie in cookies.items()} |
Load the configuration from a location specified in the environment.
This will load a cfg file using :meth:`from_pyfile` from the
location specified in the environment, for example the two blocks
below are equivalent.
.. code-block:: python
app.config.from_envvar('CONFIG')... | def from_envvar(self, variable_name: str, silent: bool=False) -> None:
"""Load the configuration from a location specified in the environment.
This will load a cfg file using :meth:`from_pyfile` from the
location specified in the environment, for example the two blocks
below are equival... |
Load the configuration from a Python cfg or py file.
See Python's ConfigParser docs for details on the cfg format.
It is a common practice to load the defaults from the source
using the :meth:`from_object` and then override with a cfg or
py file, for example
.. code-block:: pyt... | def from_pyfile(self, filename: str, silent: bool=False) -> None:
"""Load the configuration from a Python cfg or py file.
See Python's ConfigParser docs for details on the cfg format.
It is a common practice to load the defaults from the source
using the :meth:`from_object` and then ove... |
Load the configuration from a Python object.
This can be used to reference modules or objects within
modules for example,
.. code-block:: python
app.config.from_object('module')
app.config.from_object('module.instance')
from module import instance
... | def from_object(self, instance: Union[object, str]) -> None:
"""Load the configuration from a Python object.
This can be used to reference modules or objects within
modules for example,
.. code-block:: python
app.config.from_object('module')
app.config.from_obj... |
Load the configuration values from a JSON formatted file.
This allows configuration to be loaded as so
.. code-block:: python
app.config.from_json('config.json')
Arguments:
filename: The filename which when appended to
:attr:`root_path` gives the path ... | def from_json(self, filename: str, silent: bool=False) -> None:
"""Load the configuration values from a JSON formatted file.
This allows configuration to be loaded as so
.. code-block:: python
app.config.from_json('config.json')
Arguments:
filename: The filena... |
Load the configuration values from a mapping.
This allows either a mapping to be directly passed or as
keyword arguments, for example,
.. code-block:: python
config = {'FOO': 'bar'}
app.config.from_mapping(config)
app.config.form_mapping(FOO='bar')
... | def from_mapping(self, mapping: Optional[Mapping[str, Any]]=None, **kwargs: Any) -> None:
"""Load the configuration values from a mapping.
This allows either a mapping to be directly passed or as
keyword arguments, for example,
.. code-block:: python
config = {'FOO': 'bar'... |
Return a dictionary of keys within a namespace.
A namespace is considered to be a key prefix, for example the
keys ``FOO_A, FOO_BAR, FOO_B`` are all within the ``FOO``
namespace. This method would return a dictionary with these
keys and values present.
.. code-block:: python
... | def get_namespace(
self,
namespace: str,
lowercase: bool=True,
trim_namespace: bool=True,
) -> Dict[str, Any]:
"""Return a dictionary of keys within a namespace.
A namespace is considered to be a key prefix, for example the
keys ``FOO_A, FOO_B... |
Create a response, a simple wrapper function.
This is most useful when you want to alter a Response before
returning it, for example
.. code-block:: python
response = make_response(render_template('index.html'))
response.headers['X-Header'] = 'Something' | async def make_response(*args: Any) -> Response:
"""Create a response, a simple wrapper function.
This is most useful when you want to alter a Response before
returning it, for example
.. code-block:: python
response = make_response(render_template('index.html'))
response.headers['X-H... |
Retrieve the flashed messages stored in the session.
This is mostly useful in templates where it is exposed as a global
function, for example
.. code-block:: html+jinja
<ul>
{% for message in get_flashed_messages() %}
<li>{{ message }}</li>
{% endfor %}
</ul>
... | def get_flashed_messages(
with_categories: bool=False,
category_filter: List[str]=[],
) -> Union[List[str], List[Tuple[str, str]]]:
"""Retrieve the flashed messages stored in the session.
This is mostly useful in templates where it is exposed as a global
function, for example
.. code-b... |
Return the url for a specific endpoint.
This is most useful in templates and redirects to create a URL
that can be used in the browser.
Arguments:
endpoint: The endpoint to build a url for, if prefixed with
``.`` it targets endpoint's in the current blueprint.
_anchor: Addition... | def url_for(
endpoint: str,
*,
_anchor: Optional[str]=None,
_external: Optional[bool]=None,
_method: Optional[str]=None,
_scheme: Optional[str]=None,
**values: Any,
) -> str:
"""Return the url for a specific endpoint.
This is most useful in templates and ... |
Share the current request context with a generator.
This allows the request context to be accessed within a streaming
generator, for example,
.. code-block:: python
@app.route('/')
def index() -> AsyncGenerator[bytes, None]:
@stream_with_context
async def generator... | def stream_with_context(func: Callable) -> Callable:
"""Share the current request context with a generator.
This allows the request context to be accessed within a streaming
generator, for example,
.. code-block:: python
@app.route('/')
def index() -> AsyncGenerator[bytes, None]:
... |
Finds packages install prefix (or None) and it's containing Folder | def find_package(name: str) -> Tuple[Optional[Path], Path]:
"""Finds packages install prefix (or None) and it's containing Folder
"""
module = name.split(".")[0]
loader = pkgutil.get_loader(module)
if name == "__main__" or loader is None:
package_path = Path.cwd()
else:
if hasatt... |
Safely join the paths to the known directory to return a full path.
Raises:
NotFound: if the full path does not share a commonprefix with
the directory. | def safe_join(directory: FilePath, *paths: FilePath) -> Path:
"""Safely join the paths to the known directory to return a full path.
Raises:
NotFound: if the full path does not share a commonprefix with
the directory.
"""
try:
safe_path = file_path_to_path(directory).resolve(str... |
Send a file from a given directory.
Arguments:
directory: Directory that when combined with file_name gives
the file path.
file_name: File name that when combined with directory gives
the file path.
See :func:`send_file` for the other arguments. | async def send_from_directory(
directory: FilePath,
file_name: str,
*,
mimetype: Optional[str]=None,
as_attachment: bool=False,
attachment_filename: Optional[str]=None,
add_etags: bool=True,
cache_timeout: Optional[int]=None,
conditional: bool=True... |
Return a Reponse to send the filename given.
Arguments:
filename: The filename (path) to send, remember to use
:func:`safe_join`.
mimetype: Mimetype to use, by default it will be guessed or
revert to the DEFAULT_MIMETYPE.
as_attachment: If true use the attachment fil... | async def send_file(
filename: FilePath,
mimetype: Optional[str]=None,
as_attachment: bool=False,
attachment_filename: Optional[str]=None,
add_etags: bool=True,
cache_timeout: Optional[int]=None,
conditional: bool=False,
last_modified: Optional[datetime]=N... |
Open a file for reading.
Use as
.. code-block:: python
with app.open_resouce(path) as file_:
file_.read() | def open_resource(self, path: FilePath, mode: str='rb') -> IO[AnyStr]:
"""Open a file for reading.
Use as
.. code-block:: python
with app.open_resouce(path) as file_:
file_.read()
"""
if mode not in {'r', 'rb'}:
raise ValueError('Files c... |
Setter for spinner property.
Parameters
----------
spinner : dict, str
Defines the spinner value with frame and interval | def spinner(self, spinner=None):
"""Setter for spinner property.
Parameters
----------
spinner : dict, str
Defines the spinner value with frame and interval
"""
self._spinner = self._get_spinner(spinner)
self._frame_index = 0
self._text_index ... |
Setter for placement property.
Parameters
----------
placement: str
Defines the placement of the spinner | def placement(self, placement):
"""Setter for placement property.
Parameters
----------
placement: str
Defines the placement of the spinner
"""
if placement not in self.SPINNER_PLACEMENTS:
raise ValueError(
"Unknown spinner placemen... |
Setter for animation property.
Parameters
----------
animation: str
Defines the animation of the spinner | def animation(self, animation):
"""Setter for animation property.
Parameters
----------
animation: str
Defines the animation of the spinner
"""
self._animation = animation
self._text = self._get_text(self._text['original']) |
Extracts spinner value from options and returns value
containing spinner frames and interval, defaults to 'dots' spinner.
Parameters
----------
spinner : dict, str
Contains spinner value or type of spinner to be used
Returns
-------
dict
Co... | def _get_spinner(self, spinner):
"""Extracts spinner value from options and returns value
containing spinner frames and interval, defaults to 'dots' spinner.
Parameters
----------
spinner : dict, str
Contains spinner value or type of spinner to be used
Returns... |
Creates frames based on the selected animation
Returns
-------
self | def _get_text(self, text):
"""Creates frames based on the selected animation
Returns
-------
self
"""
animation = self._animation
stripped_text = text.strip()
# Check which frame of the animation is the widest
max_spinner_length = max([len(i) for ... |
Clears the line and returns cursor to the start.
of line
Returns
-------
self | def clear(self):
"""Clears the line and returns cursor to the start.
of line
Returns
-------
self
"""
if not self._enabled:
return self
self._stream.write('\r')
self._stream.write(self.CLEAR_LINE)
return self |
Renders the frame on the line after clearing it. | def _render_frame(self):
"""Renders the frame on the line after clearing it.
"""
frame = self.frame()
output = '\r{0}'.format(frame)
self.clear()
try:
self._stream.write(output)
except UnicodeEncodeError:
self._stream.write(encode_utf_8_tex... |
Runs the render until thread flag is set.
Returns
-------
self | def render(self):
"""Runs the render until thread flag is set.
Returns
-------
self
"""
while not self._stop_spinner.is_set():
self._render_frame()
time.sleep(0.001 * self._interval)
return self |
Builds and returns the frame to be rendered
Returns
-------
self | def frame(self):
"""Builds and returns the frame to be rendered
Returns
-------
self
"""
frames = self._spinner['frames']
frame = frames[self._frame_index]
if self._color:
frame = colored_frame(frame, self._color)
self._frame_index +=... |
Builds and returns the text frame to be rendered
Returns
-------
self | def text_frame(self):
"""Builds and returns the text frame to be rendered
Returns
-------
self
"""
if len(self._text['frames']) == 1:
if self._text_color:
return colored_frame(self._text['frames'][0], self._text_color)
# Return fir... |
Starts the spinner on a separate thread.
Parameters
----------
text : None, optional
Text to be used alongside spinner
Returns
-------
self | def start(self, text=None):
"""Starts the spinner on a separate thread.
Parameters
----------
text : None, optional
Text to be used alongside spinner
Returns
-------
self
"""
if text is not None:
self.text = text
if... |
Stops the spinner and clears the line.
Returns
-------
self | def stop(self):
"""Stops the spinner and clears the line.
Returns
-------
self
"""
if not self._enabled:
return self
if self._spinner_thread:
self._stop_spinner.set()
self._spinner_thread.join()
self._frame_index = 0
... |
Shows and persists success symbol and text and exits.
Parameters
----------
text : None, optional
Text to be shown alongside success symbol.
Returns
-------
self | def succeed(self, text=None):
"""Shows and persists success symbol and text and exits.
Parameters
----------
text : None, optional
Text to be shown alongside success symbol.
Returns
-------
self
"""
return self.stop_and_persist(symbol=L... |
Shows and persists fail symbol and text and exits.
Parameters
----------
text : None, optional
Text to be shown alongside fail symbol.
Returns
-------
self | def fail(self, text=None):
"""Shows and persists fail symbol and text and exits.
Parameters
----------
text : None, optional
Text to be shown alongside fail symbol.
Returns
-------
self
"""
return self.stop_and_persist(symbol=LogSymbols... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.