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 (float)

  • status_code (int)

  • client_addr (IPvAnyAddress | None)

  • app (str | None)

  • request_uri (str | None)

  • vhost (str | None)

  • valid (datetime)

  • xff (str)

  • http_agent (str)

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')]#
xff: Annotated[str, FieldInfo(annotation=NoneType, required=True, description='X_FORWARDED_FOR')]#
http_agent: Annotated[str, FieldInfo(annotation=NoneType, required=True, description='User-Agent string')]#
classmethod prevent_null_bytes(v)[source]#

Prevent null bytes in these fields.

model_config = {}#

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

class pyiem.webutil.CGIModel[source]#

Bases: BaseModel

A 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].

classmethod xss_protect(v)[source]#

Protect against XSS attacks.

classmethod apply_schema_timezone(v, info)[source]#

Normalize parsed datetimes before model-level validation.

Parameters:

info (ValidationInfo)

pyiem.webutil.emit_to_sidedoor(payload)[source]#

Send the given payload to the rsyslog sidedoor.

Parameters:

payload (bytes)

Return type:

None

pyiem.webutil.error_log(environ, msg)[source]#

Properly send an error log message.

Parameters:
  • environ (dict) – The mod_wsgi environment

  • msg (str) – The message to log

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:

str

Returns: A reStructuredText table

pyiem.webutil.write_telemetry(data)[source]#

Best-effort telemetry write.

Parameters:

data (TELEMETRY)

Return type:

bool

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:

list

pyiem.webutil.clean_form(form)[source]#

Opinionated cleaning of form data.

pyiem.webutil.log_request(environ, multiplier=1)[source]#

Log the request to database for future processing.

Parameters:
pyiem.webutil.compute_ts_from_string(form, key, default_tz)[source]#

Convert a string to a timestamp.

Parameters:
Return type:

datetime

pyiem.webutil.compute_ts(form, suffix, default_tz)[source]#

Figure out the timestamp.

Parameters:
  • form (dict)

  • suffix (str)

  • default_tz (str | None)

Return type:

datetime

pyiem.webutil.condition_form_for_datetimes(schema, form, default_tz)[source]#

Modify the form to account for ambiguous things in the schema.

Parameters:
  • schema (type[BaseModel])

  • form (dict)

  • default_tz (str | None)

Return type:

ZoneInfo | None

pyiem.webutil.condition_form_for_tz(form, kwargs)[source]#

Ensure that tz is well formed and free of known typos.

Parameters:
pyiem.webutil.add_to_environ(environ, form, **kwargs)[source]#

Build out some things auto-parsed from the request.

Parameters:
pyiem.webutil.ip_is_throttled(environ, throttle_secs)[source]#

Return True if the REMOTE_ADDR is throttled.

Parameters:
Return type:

bool

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 200 response, sent as Cache-Control: public, max-age=N. A callable gets the environ after schema parsing and may return None or 0 to send no header for that request. A Cache-Control header set by the application wins. The default None sends nothing.

What all this does:
  1. Attempts to catch database connection errors and handle nicely

  2. Updates environ with some auto-parsed values + form content.

  3. 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 tz values 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