pyiem.webutil module#
Utility functions for iemwebfarm applications.
- class pyiem.webutil.TELEMETRY(*, timing, status_code, client_addr=None, app=None, request_uri=None, vhost=None, valid, xff='', http_agent='')[source]#
Bases:
BaseModel- Parameters:
- timing: Annotated[float, FieldInfo(annotation=NoneType, required=True, description='Request processing time in seconds')]#
- status_code: Annotated[int, FieldInfo(annotation=NoneType, required=True, description='HTTP response code')]#
- client_addr: Annotated[IPvAnyAddress | None, FieldInfo(annotation=NoneType, required=True, description='Valid IPv4/IPv6 address')]#
- app: Annotated[str | None, FieldInfo(annotation=NoneType, required=True, description='App generating this telemetry')]#
- request_uri: Annotated[str | None, FieldInfo(annotation=NoneType, required=True, description='Request URI')]#
- vhost: Annotated[str | None, FieldInfo(annotation=NoneType, required=True, description='virtual host')]#
- valid: Annotated[datetime, FieldInfo(annotation=NoneType, required=True, description='Timestamp when this telemetry record was generated')]#
- http_agent: Annotated[str, FieldInfo(annotation=NoneType, required=True, description='User-Agent string')]#
- model_config = {}#
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- class pyiem.webutil.CGIModel[source]#
Bases:
BaseModelA Pydantic model that parses CGI arguments.
- model_config = {'arbitrary_types_allowed': True, 'validate_assignment': True}#
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- pyiem.webutil.emit_to_sidedoor(payload)[source]#
Send the given payload to the rsyslog sidedoor.
- Parameters:
payload (bytes)
- Return type:
None
- pyiem.webutil.model_to_rst(model)[source]#
Convert a Pydantic model to a reStructuredText table.
- Parameters:
model (BaseModel) – The Pydantic model to convert
- Return type:
Returns: A reStructuredText table
- pyiem.webutil.ensure_list(environ, key, parse_commas=True)[source]#
Ensure that we get something that is at least an empty list.
- Parameters:
environ – the WSGI environ
key – the key to look for
parse_commas – split each found value based on commas, default True.
- Return type:
- pyiem.webutil.log_request(environ, multiplier=1)[source]#
Log the request to database for future processing.
- pyiem.webutil.compute_ts_from_string(form, key, default_tz)[source]#
Convert a string to a timestamp.
- pyiem.webutil.condition_form_for_datetimes(schema, form, default_tz)[source]#
Modify the form to account for ambiguous things in the schema.
- pyiem.webutil.condition_form_for_tz(form, kwargs)[source]#
Ensure that tz is well formed and free of known typos.
- pyiem.webutil.add_to_environ(environ, form, **kwargs)[source]#
Build out some things auto-parsed from the request.
- pyiem.webutil.ip_is_throttled(environ, throttle_secs)[source]#
Return True if the REMOTE_ADDR is throttled.
- pyiem.webutil.iemapp(**kwargs)[source]#
Opinionated middleware for WSGI apps. POST requests are rejected.
A schema field name of tz is assumed to be destined to ZoneInfo usage.
Only query string parameters are parsed; request bodies are left unread.
- kwargs:
default_tz: The default timezone to use for timestamps, the default is
America/Chicago.enable_telemetry: Enable telemetry logging, default
True.help: Default help text, default
Help not available.parse_times: Parse the form for timestamps, default
True.schema (BaseModel): A Pydantic model to parse the form with. This has some requirements about how datetime fields and tz field name has special logic. See discussion below.
memcachekey (str or callable): A memcache key to use for caching the response. If the callable returns None, no caching is done.
memcacheexpire (int or callable): The number of seconds to cache the response, defaults to 3600.
content_type (str or callable): The content type to use for the response.
allowed_as_list (list): CGI parameters that are permitted to be lists. With a schema, this also permits repeated parameters for scalar fields before their validators run.
ip_throttle_secs (float or callable): Number of seconds between requests from the same REMOTE_ADDR, 0 to disable, which is the default.
cache_control (int or callable): Seconds that clients and proxies may cache a
200response, sent asCache-Control: public, max-age=N. A callable gets theenvironafter schema parsing and may returnNoneor0to send no header for that request. ACache-Controlheader set by the application wins. The defaultNonesends nothing.
- What all this does:
Attempts to catch database connection errors and handle nicely
Updates environ with some auto-parsed values + form content.
If the wrapped function returns a str or bytes, it will be encoded and made into a list for the WSGI response.
Schema DateTime Handling#
Best practice is to use pydantic.AwareDatetime and not be ambiguous. If you have a tz CGIModel field, it must have a default and so not be optional. If you use a datetime and either have a tz defined or provided a kwargs default_tz, then magic will happen to assign in this timezone. For CGIModel fields, including nested CGIModel fields, this also applies to naive datetimes produced by before field validators, before model validators run.
With a schema, repeated parameters for scalar fields are rejected before field validators run. Repeated parameters are still passed to collection fields for validation. The historical handling of repeated
tzvalues is unchanged.Exception Raising#
The following Exception types raised within the mod_wsgi wrapped code will trigger the following HTTP status codes sent to the client.
NoDataFound or IncompleteWebRequest -> 422 Unprocessable Entity
BadWebRequest -> 422 Unprocessable Entity (also db logged…)
NewDatabaseConnectionFailure -> 503 Service Unavailable
Any other Exception -> 500 Internal Server Error