core.request¶
This module implements the WSGI (Web Server Gateway Interface) layer for ViUR. This is the main entry point for incomming http requests. The main class is the :class:BrowserHandler. Each request will get it’s own instance of that class which then holds the reference to the request and response object. Additionally, this module defines the RequestValidator interface which provides a very early hook into the request processing (useful for global ratelimiting, DDoS prevention or access control).
Attributes¶
Classes¶
RequestValidators can be used to validate a request very early on. If the validate method returns a tuple, |
|
This validator examines the headers "Sec-Fetch-Site", "sec-fetch-mode" and "sec-fetch-dest" as |
|
This class accepts the requests, collect its parameters and routes the request |
Functions¶
|
Register a function to be called before each request is processed. |
|
Register a function to be called after each request has been processed. |
Module Contents¶
- core.request.TEMPLATE_STYLE_KEY = 'style'¶
- class core.request.RequestValidator¶
Bases:
abc.ABCRequestValidators can be used to validate a request very early on. If the validate method returns a tuple, the request is aborted. Can be used to block requests from bots.
To register or remove a validator, access it in main.py through :attr: viur.core.request.Router.requestValidators
- name = 'RequestValidator'¶
- static validate(request)¶
- Abstractmethod:
The function that checks the current request. If the request is valid, simply return None. If the request should be blocked, it must return a tuple of - The HTTP status code (as int) - The Description of that status code (eg “Forbidden”) - The Response Body (can be a simple string or an HTML-Page)
- Parameters:
request (BrowseHandler) – The Request instance to check
- Returns:
None on success, an Error-Tuple otherwise
- Return type:
Optional[tuple[int, str, str]]
- class core.request.FetchMetaDataValidator¶
Bases:
RequestValidatorThis validator examines the headers “Sec-Fetch-Site”, “sec-fetch-mode” and “sec-fetch-dest” as recommended by https://web.dev/fetch-metadata/
- name = 'FetchMetaDataValidator'¶
- static validate(request)¶
This validator examines the headers “sec-fetch-site”, “sec-fetch-mode” and “sec-fetch-dest” as recommended by https://web.dev/fetch-metadata/
- Parameters:
request (BrowseHandler)
- Return type:
Optional[tuple[int, str, str]]
- class core.request.Router(environ)¶
This class accepts the requests, collect its parameters and routes the request to its destination function. The basic control flow is - Setting up internal variables - Running the Request validators - Emitting the headers (especially the security related ones) - Run the TLS check (ensure it’s a secure connection or check if the URL is whitelisted) - Load or initialize a new session - Set up i18n (choosing the language etc) - Run the request preprocessor (if any) - Run before_request hooks (if any) - Normalize & sanity check the parameters - Resolve the exposed function and call it - Save the session / tear down the request - Run after_request hooks (if any) - Return the response generated
- Warning:
Don’t instantiate! Don’t subclass! DON’T TOUCH! ;)
- Parameters:
environ (dict)
- requestValidators¶
- before_request_funcs: ClassVar[list[Callable[[], None]]] = []¶
- after_request_funcs: ClassVar[list[Callable[[], None]]] = []¶
- startTime¶
- request¶
- response¶
- maxLogLevel = 10¶
- _traceID¶
- is_deferred = False¶
- path = ''¶
- path_list = ()¶
- skey_checked = False¶
- internalRequest = False¶
- disableCache = False¶
- pendingTasks = []¶
- args = ()¶
- kwargs¶
- context¶
- template_style: str | None = None¶
- cors_headers = ()¶
- method¶
- isPostRequest¶
- isSSLConnection¶
- property isDevServer: bool¶
- Return type:
bool
- _select_language(path)¶
Tries to select the best language for the current request. Depending on the value of conf.i18n.language_method, we’ll either try to load it from the session, determine it by the domain or extract it from the URL.
- Parameters:
path (str)
- Return type:
str
- _process()¶
- _route(path)¶
Does the actual work of sanitizing the parameter, determine which exposed-function to call (and with which parameters)
- Parameters:
path (str)
- Return type:
None
- _cors()¶
Set CORS headers to the HTTP response.
See also
Option
core.config.Security.cors_origins, etc. for cors settings.https://fetch.spec.whatwg.org/#http-cors-protocol
https://enable-cors.org/server.html
https://www.html5rocks.com/static/images/cors_server_flowchart.png
- Return type:
None
- saveSession()¶
- Return type:
None
- core.request.before_request(fn)¶
Register a function to be called before each request is processed.
The function is called after context variables are set (
current.request,current.session,current.request_dataare available), but a freshSessioncontainer has not been loaded yet — callcurrent.session.get().load()explicitly if you need session data.current.useris not set. Exceptions raised by the hook propagate and abort request processing. No arguments are passed; usecurrent.request.get()to access the request. The function must not return a value.Usage:
from viur.core import before_request @before_request def my_hook(): ...
- Parameters:
fn (Callable[[], None])
- Return type:
Callable[[], None]
- core.request.after_request(fn)¶
Register a function to be called after each request has been processed.
The function is called after
Router._process()completes — the response is fully generated, the session is saved, andcurrent.user.get()is still available. The call happens before CORS headers are applied. Exceptions raised by the hook propagate and abort CORS processing. No arguments are passed; usecurrent.request.get().responseto inspect the response. The function must not return a value.Usage:
from viur.core import after_request @after_request def my_hook(): ...
- Parameters:
fn (Callable[[], None])
- Return type:
Callable[[], None]