logo

Poor WSGI for Python

Light WSGI connector with uri routing support.

poorwsgi

wsgi

Application

to_response

request

Args

CachedInput

EmptyForm

FieldStorage

JsonDict

JsonList

Request

SimpleRequest

parse_json_request

response

BaseResponse

Declined

EmptyResponse

FileObjResponse

FileResponse

GeneratorResponse

HTTPException

IBytesIO

JSONGeneratorResponse

JSONResponse

NoContentResponse

NotModifiedResponse

PartialResponse

RedirectResponse

Response

ResponseError

StrGeneratorResponse

TextResponse

abort

make_response

redirect

results

bad_request

debug_info

directory_index

forbidden

handlers_view

hbytes

html_escape

human_methods_

internal_server_error

method_not_allowed

not_found

not_implemented

not_modified

unauthorized

session

NoCompress

PoorSession

SessionError

check_token

get_token

hidden

digest

PasswordMap

check_credentials

check_digest

check_response

get_re_type

hexdigest

main

state

deprecated

openapi_wrapper

OpenAPIRequest

OpenAPIResponse

module poorwsgi link | top

Poor WSGI connector for Python

Current Contents:

Module dependences: headers, poorwsgi.wsgi, request, response, response, results, session, state, wsgi

module wsgi link | top

Application callable class, which is the main point for wsgi application.

Classes:

Application

Functions:

to_response

Module dependences: _hashlib, collections, logging, path, poorwsgi.request, poorwsgi.response, poorwsgi.results, poorwsgi.state, posix, re, time, uuid

class Application link | top

Poor WSGI application which is called by WSGI server.

Working of is describe in PEP 333. This object store route dispatch table, and have methods for it's using and of course __call__ method for use as WSGI application.

after (READ) top

Tuple of table with after-response handlers.

See Application.after_response.

auth_algorithm (READ | WRITE) top

Authorization algorithm.

Algorithm depends on authorization type and client support. Supported:

Digest:

MD5 | MD5-sess | SHA256 | SHA256-sess

default:

MD5-sess

auth_hash (READ) top

Return authorization hash function.

Function can be changed by auth_algorithm property.

default:

md5

auth_qop (READ | WRITE) top

Authorization quality of protection.

This is use for Digest authorization only. When browsers supports only auth or empty value, PoorWSGI supports the same.

default:

auth

auth_timeout (READ | WRITE) top

Digest Authorization timeout of nonce value in seconds.

In fact, timeout will be between timeout and 2*timeout, because time alignment is used. If timeout is None or 0, no timeout is used.

default:

300 (5min)

auth_type (READ | WRITE) top

Authorization type.

Only Digest type is supported now.

auto_args (READ | WRITE) top

Automatic parsing request arguments from uri.

If it is True (default), Request object do automatic parsing request uri to its args variable.

auto_cookies (READ | WRITE) top

Automatic parsing cookies from request headers.

If it is True (default) and Cookie request header was set, SimpleCookie object was parsed to Request property cookies.

auto_data (READ | WRITE) top

Enabling Request.data property for smaller requests.

Default value is True.

auto_form (READ | WRITE) top

Automatic parsing arguments from request body.

If it is True (default) and method is POST, PUT or PATCH, and request mime type is one of form_mime_types, Request object do automatic parsing request body to its form variable.

auto_json (READ | WRITE) top

Automatic parsing JSON from request body.

If it is True (default), method is POST, PUT or PATCH and request mime type is one of json_mime_types, Request object do automatic parsing request body to json variable.

before (READ) top

Tuple of table with before-response handlers.

See Application.before_response.

cached_size (READ | WRITE) top

Enabling cached_size for faster POST request.

Default value is 65365.

data_size (READ | WRITE) top

Size limit for Request.data property.

This value is which is compare to request Content-Type. Default value is 32768 as 30Kb.

debug (READ | WRITE) top

Application debug as another way how to set poor_Debug.

This setting will be rewrite by poor_Debug environment variable.

defaults (READ) top

Copy of table with default handlers.

See Application.set_default

document_index (READ | WRITE) top

Application document_root as another way how to set poor_DocumentRoot.

This setting will be rewrite by poor_DocumentRoot environ variable.

document_root (READ | WRITE) top

Application document_root as another way how to set poor_DocumentRoot.

This setting will be rewrite by poor_DocumentRoot environ variable.

errors (READ) top

Copy of table with exception handlers.

See Application.error_handler

file_callback (READ | WRITE) top

File callback use as parameter when parsing request body.

Default is None. Values could be a class or factory which got filename from request body and have file compatible interface.

filters (READ) top

Copy of filter table.

Filter table contains regular expressions and convert functions, see Application.set_filter and Application.route.

Default filters are:

:int match number and convert it to int

:float match number and convert it to float

:word match one string word

:hex match hexadecimal value and convert it to str

:re: match user defined regular expression

none match any string without '/' character

For more details see /debug-info page of your application, where you see all filters with regular expression definition.

form_mime_types (READ) top

Copy of form mime type list.

Contains list of strings as form mime types, which is use for testing, when automatics Form object is create from request body.

json_mime_types (READ) top

Copy of json mime type list.

Contains list of strings as json mime types, which is use for testing, when automatics Json object is create from request body.

keep_blank_values (READ | WRITE) top

Keep blank values in request arguments.

If it is 1 (0 is default), automatic parsing request uri or body keep blank values as empty string.

name (READ) top

Return application name.

read_timeout (READ | WRITE) top

Gets a timeout (in seconds) used for file receiving

regular_routes (READ) top

Copy of table with regular expression handlers.

See Application.route and Application.regular_route.

routes (READ) top

Copy of table with static handlers.

See Application.route.

secret_key (READ | WRITE) top

Application secret_key could be replace by poor_SecretKey in request.

Secret key is used by PoorSession class. It is generate from some server variables, and the best way is set to your own long key.

states (READ) top

Copy of table with http state handlers.

See Application.http_state

strict_parsing (READ | WRITE) top

Strict parse request arguments.

If it is 1 (0 is default), automatic parsing request uri or body raise with exception on parsing error.

def __call__(self, env, start_response) link | top

Callable define for Application instance.

This method run __request__ method.

def __init__(self, name='__main__') link | top

Application class is per name singleton.

That means, there could be exist only one instance with same name.

def __profile_request__(self, env, start_response) link | top

Profiler version of __request__.

This method is used if set_profile is used.

def __repr__(self) link | top

Return repr(self).

def __request__(self, env, start_response) link | top

Create Request instance and return wsgi response.

This method create Request object, call handlers from Application.before, uri handler (handler_from_table), default handler (Application.defaults) or error handler (Application.state_from_table), and handlers from Application.after.

def add_after_request(self, fun: Callable) link | top

Deprecated, use add_after_response instead.

def add_after_response(self, fun: Callable) link | top

Append handler to call after each response.

Method for direct append function to list functions which are called after each response.

def after_each_response(request, response):
    print("Response out")
    return response

app.add_after_response(after_each_response)

def add_before_request(self, fun: Callable) link | top

Deprecated, use add_before_response instead.

def add_before_response(self, fun: Callable) link | top

Append handler to call before each response.

Method adds function to list functions which is call before each response.

def before_each_response(req):
    print("Response coming")

app.add_before_response(before_each_response)

def after_request(self) link | top

Deprecated, use after_response instead.

def after_response(self) link | top

Append handler to call after each response.

This decorator append function to be called after each response, if you want to use it redefined all outputs.

@app.after_response()
def after_each_response(request, response):
    print("Response out")
    return response

def before_request(self) link | top

Deprecated, use before_request instead.

def before_response(self) link | top

Append handler to call before each response.

This is decorator for function to call before each response.

@app.before_response()
def before_each_response(req):
    print("Response coming")

def default(self, method: int = 3) link | top

Set default handler.

This is decorator for default handler for http method (called before error_not_found).

@app.default(METHOD_GET_POST)
def default_get_post(req):
    # this function will be called if no uri match in internal
    # uri table with method. It's similar like not_found error,
    # but without error
    ...

def del_profile(self) link | top

Remove profiler from application.

def error_from_table(self, req: poorwsgi.request.SimpleRequest, error: Exception, **kwargs) link | top

Internal method, which is called when exception was raised.

def error_handler(self, error: Type[Exception], method: int = 7) link | top

Wrap function to handle exceptions.

@app.error_handler(ValueError)
def value_error(req):
    return "Values %s are not correct." % req.args, "text/plain"

def get_options() link | top

Returns dictionary with application variables from system environment.

Application variables start with app_ prefix, but in returned dictionary is set without this prefix.

app_db_server = localhost   # application variable db_server
app_templates = app/templ   # application variable templates

This method works like Request.get_options, but work with os.environ, so it works only with wsgi servers, which set not only request environ, but os.environ too. Apaches mod_wsgi don't do that, uWsgi and PoorHTTP do that.

def handler_from_before(self, req: poorwsgi.request.SimpleRequest) link | top

Internal method, which run all before (pre_proccess) handlers.

This method was call before end-point route handler.

def handler_from_default(self, req: poorwsgi.request.SimpleRequest) link | top

Internal method, which is called if no handler is found.

def handler_from_table(self, req: poorwsgi.request.Request) link | top

Call right handler from handlers table (fill with route function).

If no handler is fined, try to find directory or file if Document Root, resp. Document Index is set. Then try to call default handler for right method or call handler for status code 404 - not found.

def http_state(self, status_code: int, method: int = 7) link | top

Wrap function to handle http status codes.

@app.http_state(state.HTTP_NOT_FOUND)
def page_not_found(req):
    return "Your page %s was not found." % req.path, "text/plain"

def is_regular_route(self, r_uri) link | top

Check if regular expression uri have any registered record.

def is_route(self, uri: str) link | top

Check if uri have any registered record.

def pop_after_request(self, fun: Callable) link | top

Deprecated, use pop_after_response instead.

def pop_after_response(self, fun: Callable) link | top

Remove handler added by add_after_response or after_response.

def pop_before_request(self, fun: Callable) link | top

Deprecated, use pop_before_response instead.

def pop_before_response(self, fun: Callable) link | top

Remove handler added by add_before_response or before_response.

def pop_default(self, method: int) link | top

Pop default handler for method.

def pop_error_handler(self, error: Type[Exception], method: int) link | top

Pop handler for http state and method.

As Application.pop_route, for pop multi-method handler, you must call pop_http_state for each method.

def pop_http_state(self, status_code: int, method: int) link | top

Pop handler for http state and method.

As Application.pop_route, for pop multi-method handler, you must call pop_http_state for each method.

def pop_regular_route(self, uri: str, method: int) link | top

Pop handler and converters for uri and method from handlers table.

For more details see Application.pop_route.

def pop_route(self, uri: str, method: int) link | top

Pop handler for uri and method from handers table.

Method must be define unique, so METHOD_GET_POST could not be use. If you want to remove handler for both methods, you must call pop route for each method state.

def regular_route(self, ruri: str, method: int = 3) link | top

Wrap function to be handler for uri defined by regular expression.

Both of function, regular_route and set_regular_route store routes to special internal table, which is another to table of static routes.

# simple regular expression
@app.regular_route(r'/user/\w+')
def any_user(req):
    ...

# regular expression with
@app.regular_route(r'/user/(?P<user>\w+)')
def user_detail(req, user):             # named path args
    ...

Be sure with ordering of call this decorator or set_regular_route function. Regular expression routes are check with the same ordering, as you create internal table of them. First match stops any other searching.

def route(self, uri: str, method: int = 3) link | top

Wrap function to be handler for uri and specified method.

You can define uri as static path or as groups which are hand to handler as next parameters.

# static uri
@app.route('/user/post', method=METHOD_POST)
def user_create(req):
    ...

# group regular expression
@app.route('/user/<name>')
def user_detail(req, name):
    ...

# group regular expression with filter
@app.route('/<surname:word>/<age:int>')
def surnames_by_age(req, surname, age):
    ...

# group with own regular expression filter
@app.route('/<car:re:\w+>/<color:re:#[\da-fA-F]+>')
def car(req, car, color):
    ...

If you can use some name of group which is python keyword, like class, you can use **kwargs syntax:

@app.route('/<class>/<len:int>')
def classes(req, **kwargs):
    return ("'%s' class is %d lenght." %
            (kwargs['class'], kwargs['len']))

Be sure with ordering of call this decorator or set_route function with groups regular expression. Regular expression routes are check with the same ordering, as you create internal table of them. First match stops any other searching. In fact, if groups are detect, they will be transfer to normal regular expression, and will be add to second internal table.

def set_default(self, fun: Callable, method: int = 3) link | top

Set default handler.

Set fun default handler for http method called before error_not_found.

app.set_default(default_get_post, METHOD_GET_POST)

def set_error_handler(self, error: Type[Exception], fun: Callable, method: int = 7) link | top

Set function as handler for exception and method.

def set_filter(self, name: str, regex: str, converter: Callable = <class 'str'>) link | top

Create new filter or overwrite built-ins.

name: str

Name of filter which is used in route or set_route method.

regex: str

Regular expression which used for filter.

converter: function

Converter function or class, which gets string in input. Default is str function, which call __str__ method on input object.

app.set_filter('uint', r'\d+', int)

def set_http_state(self, status_code: int, fun: Callable, method: int = 7) link | top

Set function as handler for http state code and method.

def set_profile(self, runctx, dump) link | top

Set profiler for __call__ function.

runctx: function

function from profiler module

dump: str

path and prefix for .profile files

Typical usage:

import cProfile

cProfile.runctx('from simple import *', globals(), locals(),
                filename="log/init.profile")
app.set_profile(cProfile.runctx, 'log/req')

def set_regular_route(self, uri: str, fun: Callable, method: int = 3, converters=(), rule: Optional[str] = None) link | top

Set handler for uri defined by regular expression.

Another way to add fn as handler for uri defined by regular expression. See Application.regular_route documentation for details.

app.set_regular_route('/use/\w+/post', user_create, METHOD_POST)

This method is internally use, when groups are found in static route, adding by route or set_route method.

def set_route(self, uri: str, fun: Callable, method: int = 3) link | top

Set handler for uri and method.

Another way to add fun as handler for uri. See Application.route documentation for details.

app.set_route('/use/post', user_create, METHOD_POST)

def state_from_table(self, req: poorwsgi.request.SimpleRequest, status_code: int, **kwargs) link | top

Internal method, which is called if another http state has occurred.

If status code is in Application.shandlers (fill with http_state function), call this handler.

def to_response(response) link | top

handler response to application response.

AUTH_DIGEST_ALGORITHMS = {'MD5': <built-in function openssl_md5>, 'MD5-sess': <built-in function openssl_md5>, 'SHA-256': <built-in function openssl_sha256>, 'SHA-256-sess': <built-in function openssl_sha256>} top

Supported authorization algorithms

log = <Logger poorwsgi (WARNING)> top

re_filter = (<(\w+)(:[^>]+)?>, 32) top

check, if there is define filter in uri

module request link | top

Classes, which is used for managing requests.

Classes:

Headers, Request, EmptyForm, Args, Json, FieldStorage

Functions:

parse_negotiation

Module dependences: _io, cgi, http.cookies, json, logging, os, poorwsgi.headers, poorwsgi.response, re, tempfile, time, typing, urllib.parse, warnings

class Args link | top

Compatibility class for read values from QUERY_STRING.

Class is based on dictionary. It has getfirst and getlist methods, which can call function on values.

def __init__(self, req: request.Request, keep_blank_values=0, strict_parsing=0) link | top

Initialize self. See help(type(self)) for accurate signature.

def getfirst(self, key: str, default: Union[List, Tuple, NoneType] = None, fce: Callable = <class 'str'>) link | top

Returns first variable value for key or default.

fce: convertor (str)

function which processed value.

def getlist(self, key: str, default: Optional[Iterable] = None, fce: Callable = <class 'str'>) link | top

Returns list of variable values for key or empty list.

fce: convertor (str)

function which processed value.

default: list

Default value, when argument was not set.

class CachedInput link | top

Wrapper around wsgi.input file, which reads data block by block.

timeout: float

how long to wait for new bytes in seconds

def __init__(self, file, size, block_size=32768, timeout: Optional[float] = 10.0) link | top

Initialize self. See help(type(self)) for accurate signature.

def read(self, size=-1) link | top

Compatible file read which works with internal buffer.

def readline(self, size=-1) link | top

Compatible file read which works with internal buffer.

class EmptyForm link | top

Compatibility class as fallback.

def getfirst(key: str, default: Any = None, fce: Callable = <class 'str'>) link | top

Just return fce(default) if default is not None.

def getlist(key: str, default: Any = None, fce: Callable = <class 'str'>) link | top

Just yield fce(default) or iter default.

def getvalue(key: str, default: Any = None) link | top

Just return default.

class FieldStorage link | top

Class based of cgi.FieldStorage.

Instead of FieldStorage from cgi module, can have better getfirst and getlist methods which can call function on values and can set file_callback.

Constructor post special environment to base class, which do POST emulation for any request, because base cgi.FieldStorage know only GET, HEAD and POST methods an read from all variables, which we don't want.

There are some usable variables, which you can use, if you want to test what variable it is:

name:

variable name, the same name from input attribute.

type:

mime-type of variable. All variables have internal mime-type, if that is no file, mime-type is text/plain.

filename:

if variable is file, filename is its name from form.

file:

file type instance, from you can read variable. This instance could be TemporaryFile as default for files, StringIO for normal variables or instance of your own file type class, create from file_callback.

lists:

if variable is list of variables, this contains instances of FieldStorage.

def __bool__(self) link | top

Bool operator.

def __contains__(self, key: str) link | top

Dictionary like in operator.

def __del__(self) link | top

def __enter__(self) link | top

def __exit__(self, *args) link | top

def __getattr__(self, name) link | top

def __getitem__(self, key: str) link | top

Dictionary like [] operator.

def __init__(self, req, headers=None, outerboundary=b'', environ=None, keep_blank_values=0, strict_parsing=0, limit=None, encoding='utf-8', errors='replace', max_num_fields=None, separator='&', file_callback=None) link | top

Constructor of FieldStorage.

Many of input parameters are need only for next internal use, because FieldStorage parse variables recursive. You need add only:

req: Request

Input request.

keep_blank_values: int (0)

If you want to parse blank values as right empty values.

strict_parsing: int (0)

If you want to raise exception on parsing error.

file_callback: callback

Callback for creating instance of uploading files.

def __iter__(self) link | top

def __len__(self) link | top

Dictionary style len(x) support.

def __repr__(self) link | top

Return a printable representation.

def get(self, key: str, default: Any = None) link | top

Compatibility methods with dict, alias for getvalue.

def getfirst(self, key: str, default: Any = None, fce: Callable = <class 'str'>) link | top

Returns first variable value for key or default, if key not exist.

Arguments:
key: str

key name

default: None

default value if key not found

fce: convertor (str)

Function or class which processed value.

def getlist(self, key: str, default: Optional[List] = None, fce: Callable = <class 'str'>) link | top

Returns list of variable values for key or empty list.

Arguments:
key: str

key name

default: list

List of values when key was not sent.

fce: convertor (str)

Function or class which processed value.

def getvalue(self, key, default=None) link | top

Dictionary style get() method, including 'value' lookup.

def keys(self) link | top

Dictionary like keys() method.

def make_file(self) link | top

Return readable and writable temporary file.

def read_binary(self) link | top

Internal: read binary data.

def read_lines(self) link | top

Internal: read lines until EOF or outerboundary.

def read_lines_to_eof(self) link | top

Internal: read lines until EOF.

def read_lines_to_outerboundary(self) link | top

Internal: read lines until outerboundary. Data is read as bytes: boundaries and line ends must be converted to bytes for comparisons.

def read_multi(self, environ, keep_blank_values, strict_parsing) link | top

Internal: read a part that is itself multipart.

def read_single(self) link | top

Internal: read an atomic part.

def read_urlencoded(self) link | top

Internal: read data in query string format.

def skip_lines(self) link | top

Internal: skip lines until outer boundary if defined.

class JsonDict link | top

Compatibility class for read values from JSON POST, PUT or PATCH request.

It has getfirst and getlist methods, which can call function on values.

def __init__(self, *args, **kwargs) link | top

Initialize self. See help(type(self)) for accurate signature.

def getfirst(self, key: str, default: Any = None, fce: Callable = <class 'str'>) link | top

Returns first variable value for key or default, if key not exist.

default: any

Default value if key not exists.

fce: convertor

Function which processed value.

def getlist(self, key: str, default: Optional[Iterable] = None, fce: Callable = <class 'str'>) link | top

Returns generator of variable values for key.

default: list

Default value, when value not set.

fce: convertor (str)

Function which processed value.

class JsonList link | top

Compatibility class for read values from JSON POST, PUT or PATCH request.

It has getfirst and getlist methods, which can call function on values.

def getfirst(self, key: Optional[str] = None, default: Any = None, fce: Callable = <class 'str'>) link | top

Returns first variable value or default, if no one exist.

key: None

Compatibility parametr is ignored.

default: any

Default value if key not exists.

fce: convertor

Function which processed value.

def getlist(self, key: Optional[str] = None, default: Optional[Iterable] = None, fce: Callable = <class 'str'>) link | top

Returns generator of values.

key: None

Compatibility parametr is ignored.

fce: convertor (str)

Function which processed value.

default: list

Default value when self is empty.

def getvalue(self, key=None, default: Any = None) link | top

Returns first item or defualt if no exists.

key: None

Compatibility parametr is ignored.

default: any

Default value if key not exists.

class Request link | top

HTTP request object with all server elements.

It could be compatible as soon as possible with mod_python.apache.request. Special variables for user use are prefixed with app_.

accept (READ) top

Tuple of client supported mime types from Accept header.

accept_charset (READ) top

Tuple of client supported charset from Accept-Charset header.

accept_encoding (READ) top

Tuple of client supported charset from Accept-Encoding header.

accept_html (READ) top

Return true if text/html mime type is in accept negotiations values.

accept_json (READ) top

Return true if application/json mime type is in accept negotiations values.

accept_language (READ) top

List of client supported languages from Accept-Language header.

accept_xhtml (READ) top

Return true if text/xhtml mime type is in accept negotiations values.

api (READ | WRITE) top

For api request object, could be used for OpenAPIRequest.

app (READ) top

Return Application object which was created Request.

args (READ | WRITE) top

Extended dictionary (Args instance) of request arguments.

Argument are parsed from QUERY_STRING, which is typical, but not only for GET method. Arguments are parsed when Application.auto_args is set which is default.

This property could be set only once.

authorization (READ) top

Return Authorization header parsed to dictionary.

charset (READ) top

Request Content-Type charset header string, utf-8 if not set.

content_length (READ) top

Request Content-Length header value, -1 if not set.

cookies (READ) top

SimpleCookie iterable object of all cookies from Cookie header.

This property was set if Application.auto_cookies is set to true, which is default. Otherwise cookies was empty tuple.

data (READ) top

Returns input data from wsgi.input file.

This works only, when auto_data configuration and Content-Length of request are lower then input_cache configuration value. Other requests like big file data uploads increase memory and time system requests.

debug (READ) top

Value of poor_Debug variable.

document_index (READ) top

Value of poor_DocumentIndex variable.

Variable is used to generate index html page, when poor_DocumentRoot is set.

document_root (READ) top

Returns DocumentRoot setting.

end_time (READ) top

Return timestamp when Request was created (end of __init__).

environ (READ) top

Copy of table object containing request environment.

Information is get from wsgi server.

error_handler (READ | WRITE) top

This property is set only when error handler was called.

It was set by Application object when error handler is known before calling.

form (READ | WRITE) top

Dictionary like class (FieldStorage instance) of body arguments.

Arguments must be send in request body with mime type one of Application.form_mime_types. Method must be POST, PUT or PATCH. Request body is parsed when Application.auto_form is set, which default and when method is POST, PUT or PATCH.

This property could be set only once.

forwarded_for (READ) top

X-Forward-For http header if exists.

forwarded_host (READ) top

X-Forward-Host http header without port if exists.

forwarded_port (READ) top

Port from X-Forward-Host or X-Forward-Proto header.

forwarded_proto (READ) top

X-Forward-Proto http header if exists.

full_path (READ) top

Path with query, if it exist, from url.

headers (READ) top

Reference to input headers object.

host_port (READ) top

Port, as set by full URI or Host.

hostname (READ) top

Host, as set by full URI or Host: header without port.

input (READ) top

Return input file, for internal use in FieldStorage

is_body_request (READ) top

True if has set Content-Length more than zero.

is_chunked (READ) top

True if has set Transfer-Encoding is chunked.

is_chunked_request (READ) top

Compatibility alias for is_chunked.

is_xhr (READ) top

If X-Requested-With header is set with XMLHttpRequest value.

json (READ) top

Json dictionary if request mime type is JSON.

Json types is defined in Application.json_mime_types, typical is application/json and request method must be POST, PUT or PATCH and Application.auto_json must be set to true (default). Otherwise json is EmptyForm.

When request data is present, that will by parsed with parse_json_request function.

method (READ) top

String containing the method, GET, HEAD, POST, etc.

method_number (READ) top

Method number constant from state module.

mime_type (READ) top

Request Content-Type header or empty string if not set.

path (READ) top

Path part of url.

path_args (READ | WRITE) top

Dictionary arguments from path of regual expression rule.

poor_environ (READ) top

Environ with poor_ variables.

It is environ from request, or os.environ

port (READ) top

Alias for server_port property.

protocol (READ) top

Alias for server_protocol property

query (READ) top

The QUERY_STRING environment variable.

referer (READ) top

Request referer if is available or None.

remote_addr (READ) top

Remote address.

remote_host (READ) top

Remote hostname.

scheme (READ) top

Alias for server_scheme property.

secret_key (READ) top

Value of poor_SecretKey variable.

Secret key is used by PoorSession class. It is generate from some server variables, and the best way is set programmatically by Application.secret_key from random data.

server_admin (READ) top

Server admin if set, or webmaster@hostname.

server_hostname (READ) top

Server name variable.

server_port (READ) top

Server port.

server_protocol (READ) top

Server protocol, as given by the client.

In HTTP/0.9. cgi SERVER_PROTOCOL value.

server_scheme (READ) top

Request scheme, typical http or https.

server_software (READ) top

Server software.

start_time (READ) top

Return timestamp when http request starts.

uri (READ) top

Deprecated alias for path of the URI.

uri_handler (READ | WRITE) top

This property is set at the same point as uri_rule.

It was set by Application object when end point handler is known before calling all pre handlers. Typical use case is set some special attribute to handler, and read them in pre handler.

Property was set when any route is found for request uri. Sending file internaly when document_root is set, or by Error handlers leave uri_handler None.

uri_rule (READ | WRITE) top

Rule from one of application handler table.

This property could be set once, and that do Application object. There are some internal uri_rules which is set typical if some internal handler was called. There are: /* for default, directory and file handler and /debug-info for debug handler. In other case, there be url or regex.

user (READ | WRITE) top

For user object, who is login for example (default None).

user_agent (READ) top

Browser user agent string.

def __del__(self) link | top

def __init__(self, environ, app) link | top

Object was created automatically in wsgi module.

It's input parameters are the same, which Application object gets from WSGI server plus file callback for auto request body parsing.

def construct_url(self, uri: str) link | top

This function returns a fully qualified URI string.

Url is create from the path specified by uri, using the information stored in the request to determine the scheme, server host name and port. The port number is not included in the string if it is the same as the default port 80.

def get_options(self) link | top

Returns dictionary with application variables from environment.

Application variables start with app_ prefix, but in returned dictionary is set without this prefix.

poor_Debug = on             # Poor WSGI variable
app_db_server = localhost   # application variable db_server
app_templates = app/templ   # application variable templates

def read(self, length=-1) link | top

Read data from client (typical for XHR2 data POST).

If length is not set, or if is lower then zero, Content-Length was be use.

def read_chunk(self) link | top

Read chunk when Transfer-Encoding is chunked .

Method read line with chunk size first, then read chunk and return it, or raise ValueError when chunk size is in bad format.

Be sure that wsgi server allow readline from wsgi.input. For examples uWSGI has extra API https://uwsgi-docs.readthedocs.io/en/latest/Chunked.html

class SimpleRequest link | top

Request proxy properties implementation - for internal use only.

app (READ) top

Return Application object which was created Request.

debug (READ) top

Value of poor_Debug variable.

document_index (READ) top

Value of poor_DocumentIndex variable.

Variable is used to generate index html page, when poor_DocumentRoot is set.

document_root (READ) top

Returns DocumentRoot setting.

end_time (READ) top

Return timestamp when Request was created (end of __init__).

environ (READ) top

Copy of table object containing request environment.

Information is get from wsgi server.

error_handler (READ | WRITE) top

This property is set only when error handler was called.

It was set by Application object when error handler is known before calling.

forwarded_for (READ) top

X-Forward-For http header if exists.

forwarded_host (READ) top

X-Forward-Host http header without port if exists.

forwarded_port (READ) top

Port from X-Forward-Host or X-Forward-Proto header.

forwarded_proto (READ) top

X-Forward-Proto http header if exists.

full_path (READ) top

Path with query, if it exist, from url.

host_port (READ) top

Port, as set by full URI or Host.

hostname (READ) top

Host, as set by full URI or Host: header without port.

method (READ) top

String containing the method, GET, HEAD, POST, etc.

method_number (READ) top

Method number constant from state module.

path (READ) top

Path part of url.

poor_environ (READ) top

Environ with poor_ variables.

It is environ from request, or os.environ

port (READ) top

Alias for server_port property.

protocol (READ) top

Alias for server_protocol property

query (READ) top

The QUERY_STRING environment variable.

referer (READ) top

Request referer if is available or None.

remote_addr (READ) top

Remote address.

remote_host (READ) top

Remote hostname.

scheme (READ) top

Alias for server_scheme property.

secret_key (READ) top

Value of poor_SecretKey variable.

Secret key is used by PoorSession class. It is generate from some server variables, and the best way is set programmatically by Application.secret_key from random data.

server_admin (READ) top

Server admin if set, or webmaster@hostname.

server_hostname (READ) top

Server name variable.

server_port (READ) top

Server port.

server_protocol (READ) top

Server protocol, as given by the client.

In HTTP/0.9. cgi SERVER_PROTOCOL value.

server_scheme (READ) top

Request scheme, typical http or https.

server_software (READ) top

Server software.

start_time (READ) top

Return timestamp when http request starts.

uri (READ) top

Deprecated alias for path of the URI.

uri_handler (READ | WRITE) top

This property is set at the same point as uri_rule.

It was set by Application object when end point handler is known before calling all pre handlers. Typical use case is set some special attribute to handler, and read them in pre handler.

Property was set when any route is found for request uri. Sending file internaly when document_root is set, or by Error handlers leave uri_handler None.

uri_rule (READ | WRITE) top

Rule from one of application handler table.

This property could be set once, and that do Application object. There are some internal uri_rules which is set typical if some internal handler was called. There are: /* for default, directory and file handler and /debug-info for debug handler. In other case, there be url or regex.

user_agent (READ) top

Browser user agent string.

def __init__(self, environ, app) link | top

Initialize self. See help(type(self)) for accurate signature.

def construct_url(self, uri: str) link | top

This function returns a fully qualified URI string.

Url is create from the path specified by uri, using the information stored in the request to determine the scheme, server host name and port. The port number is not included in the string if it is the same as the default port 80.

def get_options(self) link | top

Returns dictionary with application variables from environment.

Application variables start with app_ prefix, but in returned dictionary is set without this prefix.

poor_Debug = on             # Poor WSGI variable
app_db_server = localhost   # application variable db_server
app_templates = app/templ   # application variable templates

def parse_json_request(raw: bytes, charset: str = 'utf-8') link | top

Try to parse request data.

Returned type could be:

  • JsonDict when dictionary is parsed.

  • JsonList when list is parsed.

  • Other based types from json.loads function like str, int, float, bool or None.

  • None when parsing of JSON fails. That is logged with WARNING log level.

RE_AUTHORIZATION = ((\w+\*?)[=] ?("[^"]+"|[\w\-\'%]+), 32) top

RE_HTTPURLPATTERN = (^(http|https):\/\/, 32) top

simple regular expression for construct_url method

log = <Logger poorwsgi (WARNING)> top

module response link | top

Module dependences: _io, datetime, genericpath, inspect, io, json, logging, mimetypes, poorwsgi.headers, poorwsgi.state, posix, simplejson.encoder, typing

class BaseResponse link | top

Base class for response.

content_length (READ) top

Return content_length of response.

That is size of internal buffer.

data (READ) top

Return data content.

headers (READ | WRITE) top

Reference to output headers object.

ranges (READ) top

Tuple of ranges set in make_partial method.

reason (READ) top

HTTP response is set automatically with setting status_code.

Setting response message is not good idea, but you can create own class based on Response, when you can override status_code setter.

status_code (READ | WRITE) top

Http status code, which is state.HTTP_OK (200) by default.

If you want to set this variable (which is very good idea in http_state handlers), it is good solution to use some of HTTP_ constant from state module.

def __call__(self, start_response: Callable) link | top

Call self as a function.

def __end_of_response__(self) link | top

Method for internal use only!.

This method was called from Application object at the end of request for returning right value to wsgi server.

def __init__(self, content_type: str = '', headers: Union[poorwsgi.headers.Headers, List, Tuple, set, dict, NoneType] = None, status_code: int = 200) link | top

Initialize self. See help(type(self)) for accurate signature.

def __start_response__(self, start_response: Callable) link | top

def add_header(self, name: str, value: str, **kwargs) link | top

Call Headers.add_header on headers object.

def make_partial(self, ranges: Optional[List[Tuple[Optional[int], Optional[int]]]] = None, units='bytes') link | top

Make response partial.

It adds Accept-Ranges headers with units value and set range to new value. If range is defined, and response support seek in buffer, or skip generator, it returns right range response.

Inconsistent ranges are skipped!

Response status_code MUST be HTTP_OK (200 OK). Only one range is supported at this moment. Other behaviour, like If-Range conditions depends on response or programmers support.

see https://www.rfc-editor.org/rfc/rfc9110.html#name-range-requests

>>> res = BaseResponse()
>>> res.make_partial([(0, 100)])
>>> res.ranges
((0, 100),)
>>> res.make_partial([(50, 100), (60, 20), (150, None), (None, 200)])
>>> res.ranges
((50, 100), (150, None), (None, 200))

def make_range(self, ranges: List[Tuple[Optional[int], Optional[int]]], units='bytes', full='*') link | top

Just set Content-Range header values and units attribute.

Content-Range is set in __start_response__ method for HTTP_OK status. This method is need, when you want to make partial response by yourself. This method needs response with HTTP_PARTIAL_CONTENT status.

class Declined link | top

For situation without answer.

This response is returned, when state.DECLINED was returned.

content_length (READ) top

Return content_length of response.

That is size of internal buffer.

data (READ) top

Return data content.

headers (READ | WRITE) top

Declined response don't have headers.

ranges (READ) top

Tuple of ranges set in make_partial method.

reason (READ) top

HTTP response is set automatically with setting status_code.

Setting response message is not good idea, but you can create own class based on Response, when you can override status_code setter.

status_code (READ | WRITE) top

Http status code, which is state.HTTP_OK (200) by default.

If you want to set this variable (which is very good idea in http_state handlers), it is good solution to use some of HTTP_ constant from state module.

def __call__(self, start_response: Callable) link | top

Call self as a function.

def __end_of_response__(self) link | top

Method for internal use only!.

This method was called from Application object at the end of request for returning right value to wsgi server.

def __init__(self, status_code: int = 200) link | top

Initialize self. See help(type(self)) for accurate signature.

def __start_response__(self, start_response: Callable) link | top

def add_header(self, *args, **kwargs) link | top

Declined response don't have headers

def make_partial(self, ranges: Optional[List[Tuple[Optional[int], Optional[int]]]] = None, units='bytes') link | top

Make response partial.

It adds Accept-Ranges headers with units value and set range to new value. If range is defined, and response support seek in buffer, or skip generator, it returns right range response.

Inconsistent ranges are skipped!

Response status_code MUST be HTTP_OK (200 OK). Only one range is supported at this moment. Other behaviour, like If-Range conditions depends on response or programmers support.

see https://www.rfc-editor.org/rfc/rfc9110.html#name-range-requests

>>> res = BaseResponse()
>>> res.make_partial([(0, 100)])
>>> res.ranges
((0, 100),)
>>> res.make_partial([(50, 100), (60, 20), (150, None), (None, 200)])
>>> res.ranges
((50, 100), (150, None), (None, 200))

def make_range(self, ranges: List[Tuple[Optional[int], Optional[int]]], units='bytes', full='*') link | top

Just set Content-Range header values and units attribute.

Content-Range is set in __start_response__ method for HTTP_OK status. This method is need, when you want to make partial response by yourself. This method needs response with HTTP_PARTIAL_CONTENT status.

class EmptyResponse link | top

Compatibility response

content_length (READ) top

Return content_length of response.

That is size of internal buffer.

data (READ) top

Return data content.

headers (READ | WRITE) top

Reference to output headers object.

ranges (READ) top

Tuple of ranges set in make_partial method.

reason (READ) top

HTTP response is set automatically with setting status_code.

Setting response message is not good idea, but you can create own class based on Response, when you can override status_code setter.

status_code (READ | WRITE) top

Http status code, which is state.HTTP_OK (200) by default.

If you want to set this variable (which is very good idea in http_state handlers), it is good solution to use some of HTTP_ constant from state module.

def __call__(self, start_response: Callable) link | top

Call self as a function.

def __end_of_response__(self) link | top

Method for internal use only!.

This method was called from Application object at the end of request for returning right value to wsgi server.

def __init__(self, status_code: int = 204) link | top

Initialize self. See help(type(self)) for accurate signature.

def __start_response__(self, start_response: Callable) link | top

def add_header(self, name: str, value: str, **kwargs) link | top

Call Headers.add_header on headers object.

def make_partial(self, ranges: Optional[List[Tuple[Optional[int], Optional[int]]]] = None, units='bytes') link | top

Make response partial.

It adds Accept-Ranges headers with units value and set range to new value. If range is defined, and response support seek in buffer, or skip generator, it returns right range response.

Inconsistent ranges are skipped!

Response status_code MUST be HTTP_OK (200 OK). Only one range is supported at this moment. Other behaviour, like If-Range conditions depends on response or programmers support.

see https://www.rfc-editor.org/rfc/rfc9110.html#name-range-requests

>>> res = BaseResponse()
>>> res.make_partial([(0, 100)])
>>> res.ranges
((0, 100),)
>>> res.make_partial([(50, 100), (60, 20), (150, None), (None, 200)])
>>> res.ranges
((50, 100), (150, None), (None, 200))

def make_range(self, ranges: List[Tuple[Optional[int], Optional[int]]], units='bytes', full='*') link | top

Just set Content-Range header values and units attribute.

Content-Range is set in __start_response__ method for HTTP_OK status. This method is need, when you want to make partial response by yourself. This method needs response with HTTP_PARTIAL_CONTENT status.

class FileObjResponse link | top

FileResponse returns file object direct to WSGI server.

This means, that sendfile UNIX system call can be used.

Be careful not to use a single FileReponse instance multiple times! WSGI server closes file, which is returned by this response. So just like Response, instance of FileResponse can be used only once!

File content is returned from current position. So Content-Length is set from file system or from buffer, but minus position.

content_length (READ) top

Return content_length of response.

That is size of internal buffer.

data (READ) top

Return data content.

This property works only if file_obj is seekable.

headers (READ | WRITE) top

Reference to output headers object.

ranges (READ) top

Tuple of ranges set in make_partial method.

reason (READ) top

HTTP response is set automatically with setting status_code.

Setting response message is not good idea, but you can create own class based on Response, when you can override status_code setter.

status_code (READ | WRITE) top

Http status code, which is state.HTTP_OK (200) by default.

If you want to set this variable (which is very good idea in http_state handlers), it is good solution to use some of HTTP_ constant from state module.

def __call__(self, start_response: Callable) link | top

Call self as a function.

def __end_of_response__(self) link | top

Method for internal use only!.

This method was called from Application object at the end of request for returning right value to wsgi server.

def __init__(self, file_obj: Union[io.IOBase, BinaryIO], content_type: Optional[str] = None, headers: Union[poorwsgi.headers.Headers, List, Tuple, set, dict, NoneType] = None, status_code: int = 200) link | top

Initialize self. See help(type(self)) for accurate signature.

def __start_response__(self, start_response: Callable) link | top

def add_header(self, name: str, value: str, **kwargs) link | top

Call Headers.add_header on headers object.

def make_partial(self, ranges: Optional[List[Tuple[Optional[int], Optional[int]]]] = None, units='bytes') link | top

Make response partial.

It adds Accept-Ranges headers with units value and set range to new value. If range is defined, and response support seek in buffer, or skip generator, it returns right range response.

Inconsistent ranges are skipped!

Response status_code MUST be HTTP_OK (200 OK). Only one range is supported at this moment. Other behaviour, like If-Range conditions depends on response or programmers support.

see https://www.rfc-editor.org/rfc/rfc9110.html#name-range-requests

>>> res = BaseResponse()
>>> res.make_partial([(0, 100)])
>>> res.ranges
((0, 100),)
>>> res.make_partial([(50, 100), (60, 20), (150, None), (None, 200)])
>>> res.ranges
((50, 100), (150, None), (None, 200))

def make_range(self, ranges: List[Tuple[Optional[int], Optional[int]]], units='bytes', full='*') link | top

Just set Content-Range header values and units attribute.

Content-Range is set in __start_response__ method for HTTP_OK status. This method is need, when you want to make partial response by yourself. This method needs response with HTTP_PARTIAL_CONTENT status.

class FileResponse link | top

FileResponse returns opened file direct to WSGI server.

This means, that sendfile UNIX system call can be used.

Be careful not to use a single FileReponse instance multiple times! WSGI server closes file, which is returned by this response. So just like Response, instance of FileResponse can be used only once!

This object adds Last-Modified header, if is not set.

content_length (READ) top

Return content_length of response.

That is size of internal buffer.

data (READ) top

Return data content.

This property works only if file_obj is seekable.

headers (READ | WRITE) top

Reference to output headers object.

ranges (READ) top

Tuple of ranges set in make_partial method.

reason (READ) top

HTTP response is set automatically with setting status_code.

Setting response message is not good idea, but you can create own class based on Response, when you can override status_code setter.

status_code (READ | WRITE) top

Http status code, which is state.HTTP_OK (200) by default.

If you want to set this variable (which is very good idea in http_state handlers), it is good solution to use some of HTTP_ constant from state module.

def __call__(self, start_response: Callable) link | top

Call self as a function.

def __end_of_response__(self) link | top

Method for internal use only!.

This method was called from Application object at the end of request for returning right value to wsgi server.

def __init__(self, path: str, content_type: Optional[str] = None, headers: Union[poorwsgi.headers.Headers, List, Tuple, set, dict, NoneType] = None, status_code: int = 200) link | top

Initialize self. See help(type(self)) for accurate signature.

def __start_response__(self, start_response: Callable) link | top

def add_header(self, name: str, value: str, **kwargs) link | top

Call Headers.add_header on headers object.

def make_partial(self, ranges: Optional[List[Tuple[Optional[int], Optional[int]]]] = None, units='bytes') link | top

Make response partial.

It adds Accept-Ranges headers with units value and set range to new value. If range is defined, and response support seek in buffer, or skip generator, it returns right range response.

Inconsistent ranges are skipped!

Response status_code MUST be HTTP_OK (200 OK). Only one range is supported at this moment. Other behaviour, like If-Range conditions depends on response or programmers support.

see https://www.rfc-editor.org/rfc/rfc9110.html#name-range-requests

>>> res = BaseResponse()
>>> res.make_partial([(0, 100)])
>>> res.ranges
((0, 100),)
>>> res.make_partial([(50, 100), (60, 20), (150, None), (None, 200)])
>>> res.ranges
((50, 100), (150, None), (None, 200))

def make_range(self, ranges: List[Tuple[Optional[int], Optional[int]]], units='bytes', full='*') link | top

Just set Content-Range header values and units attribute.

Content-Range is set in __start_response__ method for HTTP_OK status. This method is need, when you want to make partial response by yourself. This method needs response with HTTP_PARTIAL_CONTENT status.

class GeneratorResponse link | top

For response, which use generator as returned value.

Even though you can figure out iterating your generator more times, just like Response, instance of GeneratorResponse can be used only once!

content_length (READ) top

Return content_length of response.

That is size of internal buffer.

data (READ) top

Return data content.

headers (READ | WRITE) top

Reference to output headers object.

ranges (READ) top

Tuple of ranges set in make_partial method.

reason (READ) top

HTTP response is set automatically with setting status_code.

Setting response message is not good idea, but you can create own class based on Response, when you can override status_code setter.

status_code (READ | WRITE) top

Http status code, which is state.HTTP_OK (200) by default.

If you want to set this variable (which is very good idea in http_state handlers), it is good solution to use some of HTTP_ constant from state module.

def __call__(self, start_response: Callable) link | top

Call self as a function.

def __end_of_response__(self) link | top

Method for internal use only!.

This method was called from Application object at the end of request for returning right value to wsgi server.

def __init__(self, generator: Iterable[bytes], content_type: str = 'text/html; charset=utf-8', headers: Union[poorwsgi.headers.Headers, List, Tuple, set, dict, NoneType] = None, status_code: int = 200, content_length: int = 0) link | top

Initialize self. See help(type(self)) for accurate signature.

def __range_generator__(self) link | top

def __start_response__(self, start_response: Callable) link | top

def add_header(self, name: str, value: str, **kwargs) link | top

Call Headers.add_header on headers object.

def make_partial(self, ranges: Optional[List[Tuple[Optional[int], Optional[int]]]] = None, units='bytes') link | top

Make response partial.

It adds Accept-Ranges headers with units value and set range to new value. If range is defined, and response support seek in buffer, or skip generator, it returns right range response.

Inconsistent ranges are skipped!

Response status_code MUST be HTTP_OK (200 OK). Only one range is supported at this moment. Other behaviour, like If-Range conditions depends on response or programmers support.

see https://www.rfc-editor.org/rfc/rfc9110.html#name-range-requests

>>> res = BaseResponse()
>>> res.make_partial([(0, 100)])
>>> res.ranges
((0, 100),)
>>> res.make_partial([(50, 100), (60, 20), (150, None), (None, 200)])
>>> res.ranges
((50, 100), (150, None), (None, 200))

def make_range(self, ranges: List[Tuple[Optional[int], Optional[int]]], units='bytes', full='*') link | top

Just set Content-Range header values and units attribute.

Content-Range is set in __start_response__ method for HTTP_OK status. This method is need, when you want to make partial response by yourself. This method needs response with HTTP_PARTIAL_CONTENT status.

class HTTPException link | top

HTTP Exception to fast stop work.

Simple error exception:

>>> HTTPException(404)  # doctest: +ELLIPSIS
HTTPException(404, {}...)

Exception with response:

>>> HTTPException(Response(data=b'Created', status_code=201))
...                     # doctest: +ELLIPSIS
HTTPException(<poorwsgi.response.Response object at 0x...>...)

Attributes:

>>> HTTPException(401, stale=True)  # doctest: +ELLIPSIS
HTTPException(401, {'stale': True}...)

response (READ) top

Return response if it was set.

def __init__(self, arg: Union[int, response.Response], **kwargs) link | top

status_code is one of HTTP_* status code from state module.

If response is set, that will use, otherwise the handler from Application will be call.

def make_response(self) link | top

Return or make a response if is possible.

class IBytesIO link | top

Class for returning bytes when is iterate.

def __iter__(self) link | top

Iterate object by 1024 bytes.

def read_kilo(self) link | top

Read 1024 bytes from buffer.

class JSONGeneratorResponse link | top

JSON Response for data from generator.

Data will be processed in generator way, so they need to be buffered. This class need simplejson module.

** kwargs from constructor are serialized to json structure.

content_length (READ) top

Return content_length of response.

That is size of internal buffer.

data (READ) top

Return data content.

headers (READ | WRITE) top

Reference to output headers object.

ranges (READ) top

Tuple of ranges set in make_partial method.

reason (READ) top

HTTP response is set automatically with setting status_code.

Setting response message is not good idea, but you can create own class based on Response, when you can override status_code setter.

status_code (READ | WRITE) top

Http status code, which is state.HTTP_OK (200) by default.

If you want to set this variable (which is very good idea in http_state handlers), it is good solution to use some of HTTP_ constant from state module.

def __call__(self, start_response: Callable) link | top

Call self as a function.

def __end_of_response__(self) link | top

Method for internal use only!.

This method was called from Application object at the end of request for returning right value to wsgi server.

def __init__(self, charset: str = 'utf-8', headers: Union[poorwsgi.headers.Headers, List, Tuple, set, dict, NoneType] = None, status_code: int = 200, **kwargs) link | top

Initialize self. See help(type(self)) for accurate signature.

def __range_generator__(self) link | top

def __start_response__(self, start_response: Callable) link | top

def add_header(self, name: str, value: str, **kwargs) link | top

Call Headers.add_header on headers object.

def make_partial(self, ranges: Optional[List[Tuple[Optional[int], Optional[int]]]] = None, units='bytes') link | top

Make response partial.

It adds Accept-Ranges headers with units value and set range to new value. If range is defined, and response support seek in buffer, or skip generator, it returns right range response.

Inconsistent ranges are skipped!

Response status_code MUST be HTTP_OK (200 OK). Only one range is supported at this moment. Other behaviour, like If-Range conditions depends on response or programmers support.

see https://www.rfc-editor.org/rfc/rfc9110.html#name-range-requests

>>> res = BaseResponse()
>>> res.make_partial([(0, 100)])
>>> res.ranges
((0, 100),)
>>> res.make_partial([(50, 100), (60, 20), (150, None), (None, 200)])
>>> res.ranges
((50, 100), (150, None), (None, 200))

def make_range(self, ranges: List[Tuple[Optional[int], Optional[int]]], units='bytes', full='*') link | top

Just set Content-Range header values and units attribute.

Content-Range is set in __start_response__ method for HTTP_OK status. This method is need, when you want to make partial response by yourself. This method needs response with HTTP_PARTIAL_CONTENT status.

class JSONResponse link | top

Simple application/json response.

Arguments:
data_: Any

Alternative way to add any data to json response.

charset: str

charset value for Content-Type header. utf-8 by default.

headers: Headers

Response headers.

status_code: int

HTTP Status response code, 200 (HTTP_OK) by default.

encoder_kwargs: dict

Keyword arguments for json.dumps function.

kwargs: keywords arguments

Other keys and values are serialized to JSON structure.

>>> res = JSONResponse(msg="Čeština",
...                    encoder_kwargs={"ensure_ascii": False})
>>> res.data
b'{"msg": "Čeština"}'

content_length (READ) top

Return content_length of response.

That is size of internal buffer.

data (READ) top

Return data content.

headers (READ | WRITE) top

Reference to output headers object.

ranges (READ) top

Tuple of ranges set in make_partial method.

reason (READ) top

HTTP response is set automatically with setting status_code.

Setting response message is not good idea, but you can create own class based on Response, when you can override status_code setter.

status_code (READ | WRITE) top

Http status code, which is state.HTTP_OK (200) by default.

If you want to set this variable (which is very good idea in http_state handlers), it is good solution to use some of HTTP_ constant from state module.

def __call__(self, start_response: Callable) link | top

Call self as a function.

def __end_of_response__(self) link | top

Method for internal use only!.

This method was called from Application object at the end of request for returning right value to wsgi server.

def __init__(self, data_=None, charset: str = 'utf-8', headers: Union[poorwsgi.headers.Headers, List, Tuple, set, dict, NoneType] = None, status_code: int = 200, encoder_kwargs=None, **kwargs) link | top

Initialize self. See help(type(self)) for accurate signature.

def __start_response__(self, start_response: Callable) link | top

def add_header(self, name: str, value: str, **kwargs) link | top

Call Headers.add_header on headers object.

def make_partial(self, ranges: Optional[List[Tuple[Optional[int], Optional[int]]]] = None, units='bytes') link | top

Make response partial.

It adds Accept-Ranges headers with units value and set range to new value. If range is defined, and response support seek in buffer, or skip generator, it returns right range response.

Inconsistent ranges are skipped!

Response status_code MUST be HTTP_OK (200 OK). Only one range is supported at this moment. Other behaviour, like If-Range conditions depends on response or programmers support.

see https://www.rfc-editor.org/rfc/rfc9110.html#name-range-requests

>>> res = BaseResponse()
>>> res.make_partial([(0, 100)])
>>> res.ranges
((0, 100),)
>>> res.make_partial([(50, 100), (60, 20), (150, None), (None, 200)])
>>> res.ranges
((50, 100), (150, None), (None, 200))

def make_range(self, ranges: List[Tuple[Optional[int], Optional[int]]], units='bytes', full='*') link | top

Just set Content-Range header values and units attribute.

Content-Range is set in __start_response__ method for HTTP_OK status. This method is need, when you want to make partial response by yourself. This method needs response with HTTP_PARTIAL_CONTENT status.

def write(self, data: Union[str, bytes]) link | top

Write data to internal buffer.

class NoContentResponse link | top

For situation, where only state is returned.

content_length (READ) top

Return content_length of response.

That is size of internal buffer.

data (READ) top

Return data content.

headers (READ | WRITE) top

Reference to output headers object.

ranges (READ) top

Tuple of ranges set in make_partial method.

reason (READ) top

HTTP response is set automatically with setting status_code.

Setting response message is not good idea, but you can create own class based on Response, when you can override status_code setter.

status_code (READ | WRITE) top

Http status code, which is state.HTTP_OK (200) by default.

If you want to set this variable (which is very good idea in http_state handlers), it is good solution to use some of HTTP_ constant from state module.

def __call__(self, start_response: Callable) link | top

Call self as a function.

def __end_of_response__(self) link | top

Method for internal use only!.

This method was called from Application object at the end of request for returning right value to wsgi server.

def __init__(self, headers: Union[poorwsgi.headers.Headers, List, Tuple, set, dict, NoneType] = None, status_code: int = 204) link | top

Initialize self. See help(type(self)) for accurate signature.

def __start_response__(self, start_response: Callable) link | top

def add_header(self, name: str, value: str, **kwargs) link | top

Call Headers.add_header on headers object.

def make_partial(self, ranges: Optional[List[Tuple[Optional[int], Optional[int]]]] = None, units='bytes') link | top

Make response partial.

It adds Accept-Ranges headers with units value and set range to new value. If range is defined, and response support seek in buffer, or skip generator, it returns right range response.

Inconsistent ranges are skipped!

Response status_code MUST be HTTP_OK (200 OK). Only one range is supported at this moment. Other behaviour, like If-Range conditions depends on response or programmers support.

see https://www.rfc-editor.org/rfc/rfc9110.html#name-range-requests

>>> res = BaseResponse()
>>> res.make_partial([(0, 100)])
>>> res.ranges
((0, 100),)
>>> res.make_partial([(50, 100), (60, 20), (150, None), (None, 200)])
>>> res.ranges
((50, 100), (150, None), (None, 200))

def make_range(self, ranges: List[Tuple[Optional[int], Optional[int]]], units='bytes', full='*') link | top

Just set Content-Range header values and units attribute.

Content-Range is set in __start_response__ method for HTTP_OK status. This method is need, when you want to make partial response by yourself. This method needs response with HTTP_PARTIAL_CONTENT status.

class NotModifiedResponse link | top

Not Modified Response.

content_length (READ) top

Return content_length of response.

That is size of internal buffer.

data (READ) top

Return data content.

headers (READ | WRITE) top

Reference to output headers object.

ranges (READ) top

Tuple of ranges set in make_partial method.

reason (READ) top

HTTP response is set automatically with setting status_code.

Setting response message is not good idea, but you can create own class based on Response, when you can override status_code setter.

status_code (READ | WRITE) top

Http status code, which is state.HTTP_OK (200) by default.

If you want to set this variable (which is very good idea in http_state handlers), it is good solution to use some of HTTP_ constant from state module.

def __call__(self, start_response: Callable) link | top

Call self as a function.

def __end_of_response__(self) link | top

Method for internal use only!.

This method was called from Application object at the end of request for returning right value to wsgi server.

def __init__(self, headers: Union[poorwsgi.headers.Headers, List, Tuple, set, dict, NoneType] = None, etag: Optional[str] = None, content_location: Optional[str] = None, date: Union[str, int, datetime.datetime, NoneType] = None, vary: Optional[str] = None) link | top

Initialize self. See help(type(self)) for accurate signature.

def __start_response__(self, start_response: Callable) link | top

def add_header(self, name: str, value: str, **kwargs) link | top

Call Headers.add_header on headers object.

def make_partial(self, ranges: Optional[List[Tuple[Optional[int], Optional[int]]]] = None, units='bytes') link | top

Make response partial.

It adds Accept-Ranges headers with units value and set range to new value. If range is defined, and response support seek in buffer, or skip generator, it returns right range response.

Inconsistent ranges are skipped!

Response status_code MUST be HTTP_OK (200 OK). Only one range is supported at this moment. Other behaviour, like If-Range conditions depends on response or programmers support.

see https://www.rfc-editor.org/rfc/rfc9110.html#name-range-requests

>>> res = BaseResponse()
>>> res.make_partial([(0, 100)])
>>> res.ranges
((0, 100),)
>>> res.make_partial([(50, 100), (60, 20), (150, None), (None, 200)])
>>> res.ranges
((50, 100), (150, None), (None, 200))

def make_range(self, ranges: List[Tuple[Optional[int], Optional[int]]], units='bytes', full='*') link | top

Just set Content-Range header values and units attribute.

Content-Range is set in __start_response__ method for HTTP_OK status. This method is need, when you want to make partial response by yourself. This method needs response with HTTP_PARTIAL_CONTENT status.

class PartialResponse link | top

Partial Response object which only compute Content-Range header.

This is for special cases, when you can know how to return right range, for example, when you want to return another unit.

>>> res = PartialResponse()
>>> res.make_range([(1, 3)], "blocks")
>>> res.headers
Headers("...('Content-Range', 'blocks 1-3/*'))")
>>> res.make_range([(1, 3)], "blocks", 10)
>>> res.headers
Headers("...('Content-Range', 'blocks 1-3/10'))")

content_length (READ) top

Return content_length of response.

That is size of internal buffer.

data (READ) top

Return data content.

headers (READ | WRITE) top

Reference to output headers object.

ranges (READ) top

Tuple of ranges set in make_partial method.

reason (READ) top

HTTP response is set automatically with setting status_code.

Setting response message is not good idea, but you can create own class based on Response, when you can override status_code setter.

status_code (READ | WRITE) top

Http status code, which is state.HTTP_OK (200) by default.

If you want to set this variable (which is very good idea in http_state handlers), it is good solution to use some of HTTP_ constant from state module.

def __call__(self, start_response: Callable) link | top

Call self as a function.

def __end_of_response__(self) link | top

Method for internal use only!.

This method was called from Application object at the end of request for returning right value to wsgi server.

def __init__(self, data: Union[str, bytes] = b'', content_type: str = 'text/html; charset=utf-8', headers: Union[poorwsgi.headers.Headers, List, Tuple, set, dict, NoneType] = None) link | top

Initialize self. See help(type(self)) for accurate signature.

def __start_response__(self, start_response: Callable) link | top

def add_header(self, name: str, value: str, **kwargs) link | top

Call Headers.add_header on headers object.

def make_partial(self, ranges: Optional[List[Tuple[Optional[int], Optional[int]]]] = None, units='bytes') link | top

This mathod do nothing.

For creating Content-Range header, use special make_range method.

def make_range(self, ranges: List[Tuple[Optional[int], Optional[int]]], units='bytes', full='*') link | top

Just set Content-Range header values and units attribute.

Content-Range is set in __start_response__ method for HTTP_OK status. This method is need, when you want to make partial response by yourself. This method needs response with HTTP_PARTIAL_CONTENT status.

def write(self, data: Union[str, bytes]) link | top

Write data to internal buffer.

class RedirectResponse link | top

Redirect the browser to another location.

A short text is sent to the browser informing that the document has moved (for those rare browsers that do not support redirection); this text can be overridden by supplying a text string (message).

When permanent or status_code is true, MOVED_PERMANENTLY status code will be sent to the client, otherwise it will be MOVED_TEMPORARILY. Argument ``permanent`` and ``status_code`` as boolean is deprecated. Use real status_code instead.

content_length (READ) top

Return content_length of response.

That is size of internal buffer.

data (READ) top

Return data content.

headers (READ | WRITE) top

Reference to output headers object.

ranges (READ) top

Tuple of ranges set in make_partial method.

reason (READ) top

HTTP response is set automatically with setting status_code.

Setting response message is not good idea, but you can create own class based on Response, when you can override status_code setter.

status_code (READ | WRITE) top

Http status code, which is state.HTTP_OK (200) by default.

If you want to set this variable (which is very good idea in http_state handlers), it is good solution to use some of HTTP_ constant from state module.

def __call__(self, start_response: Callable) link | top

Call self as a function.

def __end_of_response__(self) link | top

Method for internal use only!.

This method was called from Application object at the end of request for returning right value to wsgi server.

def __init__(self, location: str, status_code: Union[int, bool] = 302, message: Union[str, bytes] = b'', headers: Union[poorwsgi.headers.Headers, List, Tuple, set, dict, NoneType] = None, permanent: bool = False) link | top

Initialize self. See help(type(self)) for accurate signature.

def __start_response__(self, start_response: Callable) link | top

def add_header(self, name: str, value: str, **kwargs) link | top

Call Headers.add_header on headers object.

def make_partial(self, ranges: Optional[List[Tuple[Optional[int], Optional[int]]]] = None, units='bytes') link | top

Make response partial.

It adds Accept-Ranges headers with units value and set range to new value. If range is defined, and response support seek in buffer, or skip generator, it returns right range response.

Inconsistent ranges are skipped!

Response status_code MUST be HTTP_OK (200 OK). Only one range is supported at this moment. Other behaviour, like If-Range conditions depends on response or programmers support.

see https://www.rfc-editor.org/rfc/rfc9110.html#name-range-requests

>>> res = BaseResponse()
>>> res.make_partial([(0, 100)])
>>> res.ranges
((0, 100),)
>>> res.make_partial([(50, 100), (60, 20), (150, None), (None, 200)])
>>> res.ranges
((50, 100), (150, None), (None, 200))

def make_range(self, ranges: List[Tuple[Optional[int], Optional[int]]], units='bytes', full='*') link | top

Just set Content-Range header values and units attribute.

Content-Range is set in __start_response__ method for HTTP_OK status. This method is need, when you want to make partial response by yourself. This method needs response with HTTP_PARTIAL_CONTENT status.

def write(self, data: Union[str, bytes]) link | top

Write data to internal buffer.

class Response link | top

HTTP Response object.

This is base Response object which is process with PoorWSGI application.

As Response uses BytesIO as internal cache, which is closed by WSGI server, response can be used only once!.

content_length (READ) top

Return content_length of response.

That is size of internal buffer.

data (READ) top

Return data content.

headers (READ | WRITE) top

Reference to output headers object.

ranges (READ) top

Tuple of ranges set in make_partial method.

reason (READ) top

HTTP response is set automatically with setting status_code.

Setting response message is not good idea, but you can create own class based on Response, when you can override status_code setter.

status_code (READ | WRITE) top

Http status code, which is state.HTTP_OK (200) by default.

If you want to set this variable (which is very good idea in http_state handlers), it is good solution to use some of HTTP_ constant from state module.

def __call__(self, start_response: Callable) link | top

Call self as a function.

def __end_of_response__(self) link | top

Method for internal use only!.

This method was called from Application object at the end of request for returning right value to wsgi server.

def __init__(self, data: Union[str, bytes] = b'', content_type: str = 'text/html; charset=utf-8', headers: Union[poorwsgi.headers.Headers, List, Tuple, set, dict, NoneType] = None, status_code: int = 200) link | top

Initialize self. See help(type(self)) for accurate signature.

def __start_response__(self, start_response: Callable) link | top

def add_header(self, name: str, value: str, **kwargs) link | top

Call Headers.add_header on headers object.

def make_partial(self, ranges: Optional[List[Tuple[Optional[int], Optional[int]]]] = None, units='bytes') link | top

Make response partial.

It adds Accept-Ranges headers with units value and set range to new value. If range is defined, and response support seek in buffer, or skip generator, it returns right range response.

Inconsistent ranges are skipped!

Response status_code MUST be HTTP_OK (200 OK). Only one range is supported at this moment. Other behaviour, like If-Range conditions depends on response or programmers support.

see https://www.rfc-editor.org/rfc/rfc9110.html#name-range-requests

>>> res = BaseResponse()
>>> res.make_partial([(0, 100)])
>>> res.ranges
((0, 100),)
>>> res.make_partial([(50, 100), (60, 20), (150, None), (None, 200)])
>>> res.ranges
((50, 100), (150, None), (None, 200))

def make_range(self, ranges: List[Tuple[Optional[int], Optional[int]]], units='bytes', full='*') link | top

Just set Content-Range header values and units attribute.

Content-Range is set in __start_response__ method for HTTP_OK status. This method is need, when you want to make partial response by yourself. This method needs response with HTTP_PARTIAL_CONTENT status.

def write(self, data: Union[str, bytes]) link | top

Write data to internal buffer.

class ResponseError link | top

Exception for bad response values.

class StrGeneratorResponse link | top

Generator response where generator returns str.

content_length (READ) top

Return content_length of response.

That is size of internal buffer.

data (READ) top

Return data content.

headers (READ | WRITE) top

Reference to output headers object.

ranges (READ) top

Tuple of ranges set in make_partial method.

reason (READ) top

HTTP response is set automatically with setting status_code.

Setting response message is not good idea, but you can create own class based on Response, when you can override status_code setter.

status_code (READ | WRITE) top

Http status code, which is state.HTTP_OK (200) by default.

If you want to set this variable (which is very good idea in http_state handlers), it is good solution to use some of HTTP_ constant from state module.

def __call__(self, start_response: Callable) link | top

Call self as a function.

def __end_of_response__(self) link | top

Method for internal use only!.

This method was called from Application object at the end of request for returning right value to wsgi server.

def __init__(self, generator: Iterable[str], content_type: str = 'text/html; charset=utf-8', headers: Union[poorwsgi.headers.Headers, List, Tuple, set, dict, NoneType] = None, status_code: int = 200) link | top

Initialize self. See help(type(self)) for accurate signature.

def __range_generator__(self) link | top

def __start_response__(self, start_response: Callable) link | top

def add_header(self, name: str, value: str, **kwargs) link | top

Call Headers.add_header on headers object.

def make_partial(self, ranges: Optional[List[Tuple[Optional[int], Optional[int]]]] = None, units='bytes') link | top

Make response partial.

It adds Accept-Ranges headers with units value and set range to new value. If range is defined, and response support seek in buffer, or skip generator, it returns right range response.

Inconsistent ranges are skipped!

Response status_code MUST be HTTP_OK (200 OK). Only one range is supported at this moment. Other behaviour, like If-Range conditions depends on response or programmers support.

see https://www.rfc-editor.org/rfc/rfc9110.html#name-range-requests

>>> res = BaseResponse()
>>> res.make_partial([(0, 100)])
>>> res.ranges
((0, 100),)
>>> res.make_partial([(50, 100), (60, 20), (150, None), (None, 200)])
>>> res.ranges
((50, 100), (150, None), (None, 200))

def make_range(self, ranges: List[Tuple[Optional[int], Optional[int]]], units='bytes', full='*') link | top

Just set Content-Range header values and units attribute.

Content-Range is set in __start_response__ method for HTTP_OK status. This method is need, when you want to make partial response by yourself. This method needs response with HTTP_PARTIAL_CONTENT status.

class TextResponse link | top

Simple text/plain response.

content_length (READ) top

Return content_length of response.

That is size of internal buffer.

data (READ) top

Return data content.

headers (READ | WRITE) top

Reference to output headers object.

ranges (READ) top

Tuple of ranges set in make_partial method.

reason (READ) top

HTTP response is set automatically with setting status_code.

Setting response message is not good idea, but you can create own class based on Response, when you can override status_code setter.

status_code (READ | WRITE) top

Http status code, which is state.HTTP_OK (200) by default.

If you want to set this variable (which is very good idea in http_state handlers), it is good solution to use some of HTTP_ constant from state module.

def __call__(self, start_response: Callable) link | top

Call self as a function.

def __end_of_response__(self) link | top

Method for internal use only!.

This method was called from Application object at the end of request for returning right value to wsgi server.

def __init__(self, text: str, charset: str = 'utf-8', headers: Union[poorwsgi.headers.Headers, List, Tuple, set, dict, NoneType] = None, status_code: int = 200) link | top

Initialize self. See help(type(self)) for accurate signature.

def __start_response__(self, start_response: Callable) link | top

def add_header(self, name: str, value: str, **kwargs) link | top

Call Headers.add_header on headers object.

def make_partial(self, ranges: Optional[List[Tuple[Optional[int], Optional[int]]]] = None, units='bytes') link | top

Make response partial.

It adds Accept-Ranges headers with units value and set range to new value. If range is defined, and response support seek in buffer, or skip generator, it returns right range response.

Inconsistent ranges are skipped!

Response status_code MUST be HTTP_OK (200 OK). Only one range is supported at this moment. Other behaviour, like If-Range conditions depends on response or programmers support.

see https://www.rfc-editor.org/rfc/rfc9110.html#name-range-requests

>>> res = BaseResponse()
>>> res.make_partial([(0, 100)])
>>> res.ranges
((0, 100),)
>>> res.make_partial([(50, 100), (60, 20), (150, None), (None, 200)])
>>> res.ranges
((50, 100), (150, None), (None, 200))

def make_range(self, ranges: List[Tuple[Optional[int], Optional[int]]], units='bytes', full='*') link | top

Just set Content-Range header values and units attribute.

Content-Range is set in __start_response__ method for HTTP_OK status. This method is need, when you want to make partial response by yourself. This method needs response with HTTP_PARTIAL_CONTENT status.

def write(self, data: Union[str, bytes]) link | top

Write data to internal buffer.

def abort(arg: Union[int, response.Response]) link | top

Raise HTTPException with arg.

Raise simple error exception:

>>> abort(404)
Traceback (most recent call last):
...
poorwsgi.response.HTTPException: (404, {})

Raise exception with response:

>>> abort(Response(data=b'Created', status_code=201))
Traceback (most recent call last):
...
poorwsgi.response.HTTPException:
(<poorwsgi.response.Response object at 0x...>, {})

def make_response(data: Union[str, bytes], content_type: str = 'text/html; charset=utf-8', headers: Union[poorwsgi.headers.Headers, List, Tuple, set, dict, NoneType] = None, status_code: int = 200) link | top

Create response from values.

Data could be string, bytes, or bytes returns iterable object like file.

def redirect(location: str, status_code: Union[int, bool] = 302, message: Union[str, bytes] = b'', headers: Union[poorwsgi.headers.Headers, List, Tuple, set, dict, NoneType] = None, permanent: bool = False) link | top

Raise HTTPException with RedirectResponse response.

See RedirectResponse, with same interface for more information about response.

NOT_MODIFIED_DENY = {'Content-Language', 'Content-Length', 'Content-Range', 'Content-Encoding', 'Content-MD5', 'Content-Type'} top

NOT_MODIFIED_ONE_OF_REQUIRED = {'Content-Location', 'Vary', 'ETag', 'Date'} top

log = <Logger poorwsgi (WARNING)> top

module results link | top

Module dependences: _hashlib, genericpath, inspect, logging, mimetypes, operator, os, poorwsgi.headers, poorwsgi.response, poorwsgi.session, sys, time, traceback

def bad_request(req, error=None) link | top

400 Bad Request server error handler.

def debug_info(req, app) link | top

Return debug page.

When Application.debug is enable, this handler is used for /debug-info.

def directory_index(req, path) link | top

Returns directory index as html page.

def forbidden(req, error=None) link | top

403 - Forbidden Access server error handler.

def handlers_view(handlers, sort=True) link | top

Returns sorted handlers list.

def hbytes(val: float) link | top

Return pair value and unit.

>>> hbytes(2000000)
(1.9..., 'M')
>>> hbytes(1024.0)
(1.0, 'k')

def html_escape(s) link | top

Escape to html entities.

def human_methods_(m) link | top

Return methods in text.

def internal_server_error(req, **kwargs) link | top

More debug 500 Internal Server Error server handler.

It was be called automatically when no handlers are not defined in dispatch_table.errors. If poor_Debug variable is to On, Tracaback will be generated.

def method_not_allowed(req, error=None) link | top

405 Method Not Allowed server error handler.

def not_found(req, error=None) link | top

404 - Page Not Found server error handler.

def not_implemented(req, code=None, error=None) link | top

501 Not Implemented server error handler.

def not_modified(req) link | top

Return NotModifiedResponse.

Headers E-Tag, Content-Location is return from request. Date header will be set.

def unauthorized(req, realm=None, stale='', error=None) link | top

Return 401 Unauthorized response.

HTML_ESCAPE_TABLE = {'&': '&amp;', '"': '&quot;', "'": '&apos;', '>': '&gt;', '<': '&lt;'} top

log = <Logger poorwsgi (WARNING)> top

module session link | top

PoorSession self-contained cookie class.

Classes:

NoCompress, PoorSession

Functions:

hidden, get_token, check_token

Module dependences: _hashlib, base64, bz2, http.cookies, json, logging, poorwsgi.headers, poorwsgi.request, poorwsgi.response, time, typing

class NoCompress link | top

Fake compress class/module whith two static method for PoorSession.

If compress parameter is None, this class is use.

def compress(data, compresslevel=0) link | top

Get two params, data, and compresslevel. Method only return data.

def decompress(data) link | top

Get one parameter data, which returns.

class PoorSession link | top

Self-contained cookie with session data.

You cat store or read data from object via PoorSession.data variable which must be dictionary. Data is stored to cookie by pickle dump, and next hidden with app.secret_key. So it must be set on Application object or with poor_SecretKey environment variable. Be careful with stored object. You can add object with little python trick:

sess = PoorSession(app.secret_key)

sess.data['class'] = obj.__class__          # write to cookie
sess.data['dict'] = obj.__dict__.copy()

obj = sess.data['class']()                  # read from cookie
obj.__dict__ = sess.data['dict'].copy()

Or for beter solution, you can create export and import methods for you object like that:

class Obj(object):
    def import(self, d):
        self.attr1 = d['attr1']
        self.attr2 = d['attr2']

    def export(self):
        d = {'attr1': self.attr1, 'attr2': self.attr2}
        return d

obj = Obj()
sess = PoorSession(app.secret_key)

sess.data['class'] = obj.__class__          # write to cookie
sess.data['dict'] = obj.export()

obj = sess.data['class']()                  # read from cookie
obj.import(sess.data['dict'])

def __init__(self, secret_key: Union[poorwsgi.request.Request, str, bytes], expires: int = 0, max_age: Optional[int] = None, domain: str = '', path: str = '/', secure: bool = False, same_site: bool = False, compress=<module 'bz2' from...) link | top

Constructor.

Arguments:
expires: int

Cookie Expires time in seconds, if it 0, no expire is set

max_age: int

Cookie Max-Age attribute. If both expires and max-age are set, max_age has precedence.

domain: str

Cookie Host to which the cookie will be sent.

path: str

Cookie Path that must exist in the requested URL.

secure: bool

If Secure cookie attribute will be sent.

same_site: str

The SameSite attribute. When is set could be one of Strict|Lax|None. By default attribute is not set which is Lax by browser.

compress: compress module or class.

Could be bz2, gzip.zlib, or any other, which have standard compress and decompress methods. Or it could be None to not use any compressing method.

sid: str

Cookie key name.

session_config = {
    'expires': 3600,  # one hour
    'max_age': 3600,
    'domain': 'example.net',
    'path': '/application',
    ̈́'secure': True,
    'same_site': True,
    'compress': gzip,
    'sid': 'MYSID'
}

session = PostSession(app.secret_key, **config)
try:
    session.load(req.cookies)
except SessionError as err:
    log.error("Invalid session: %s", str(err))

Changed in version 2.4.x: use app.secret_key in constructor, and than call load method.

def destroy(self) link | top

Destroy session. In fact, set cookie expires value to past (-1).

Be sure, that data can't be changed: https://stackoverflow.com/a/5285982/8379994

def header(self, headers: Union[poorwsgi.headers.Headers, poorwsgi.response.Response, NoneType] = None) link | top

Generate cookie headers and append it to headers if it set.

Returns list of cookie header pairs.

headers: Headers or Response

Object, which is used to write header directly.

def load(self, cookies: Union[http.cookies.SimpleCookie, tuple]) link | top

Load session from request's cookie

def write(self) link | top

Store data to cookie value.

This method is called automatically in header method.

class SessionError link | top

Base Exception for Session

def check_token(token: str, secret: str, client: str, timeout: Optional[int] = None) link | top

Check token, if it is right.

Arguments secret, client and expired must be same, when token was generated. If expired is set, than token must be younger than 2*expired.

def get_token(secret: str, client: str, timeout: Optional[int] = None, expired: int = 0) link | top

Create token from secret, and client string.

If timeout is set, token contains time align with twice of this value. Twice, because time of creating can be so near to computed time.

def hidden(text: Union[str, bytes], passwd: Union[str, bytes]) -> bytes link | top

(en|de)crypt text with sha hash of passwd via xor.

Arguments:
text: str or bytes

raw data to (en|de)crypt

passwd: str or bytes

password

log = <Logger poorwsgi (WARNING)> top

module digest link | top

HTTP Authenticate Digest method.

This file could be used as known htdigest tool.

python3 -m poorwsgi.digest --help

# adding / updating user password
python3 -m poorwsgi.digest -c auth.digest 'Secret Zone' user
Module dependences: _hashlib, argparse, collections, functools, genericpath, getpass, logging, poorwsgi.response, poorwsgi.session, state, sys, traceback, urllib.parse

class PasswordMap link | top

Simple memory object to store user password.

Attributes:
pathname: str

Full path to password file, must be set for PasswordMap.write and PasswordMap.load methods.

def __init__(self, pathname=None) link | top

Initialize self. See help(type(self)) for accurate signature.

def delete(self, realm, username) link | top

Delete username from realm.

def find(self, realm, username) link | top

Return digest for username in realm if exist.

def load(self) link | top

Load map from file.

def set(self, realm, username, digest) link | top

Add username to realm.

def verify(self, realm, username, digest) link | top

Check digest in password map.

def write(self) link | top

Write memory map dump.

def check_credentials(req, realm, username=None) link | top

Check Digest authorization credentials.

Return True if Authorization header is valid for realm. Username is checked too, if it is set.

def check_digest(realm, username=None) link | top

Check HTTP Digest Authenticate.

Allow only valid HTTP Digest authorization for realm. Username is checked too, if it is set. When no, HTTP_UNAUTHORIZED response was raised with realm and stale value if is need.

When user is valid, req.user attribute is set to username.

app.auth_type = 'Digest'

@app.route('/admin')
@check_digest('Admin Zone')
def admin_zone(req):
    return "This is only for Admins, just like you %s." % req.user


@app.route('/user-looser')
@check_digest('Users', looser)
def looser_only(req):
    return "You are the right looser user."

def check_response(req, password) link | top

Check digest response value.

Return True if response value is right.

def get_re_type() link | top

Get password from stdin with re-type .

def hexdigest(username, realm, password, algorithm=<built-in function openssl_md5>) link | top

Return digest hash value for user password.

Return algorithm(username:realm:password).hexdigest()

def main() link | top

Main function for manipulation with passwordfile.

log = <Logger poorwsgi (WARNING)> top

module state link | top

Constants like http status code and method types.
Module dependences: functools, operator, warnings

def deprecated(reason='') link | top

Deprecated decorator.

DECLINED = 0 top

HTTP_ACCEPTED = 202 top

HTTP_ALREADY_REPORTED = 208 top

HTTP_BAD_GATEWAY = 502 top

HTTP_BAD_REQUEST = 400 top

Client Error

HTTP_CLIENT_CLOSED_REQUEST = 499 top

HTTP_CONFLICT = 409 top

HTTP_CONNECTION_CLOSED_WITHOUT_RESPONSE = 444 top

HTTP_CONTINUE = 100 top

Informational

HTTP_CREATED = 201 top

HTTP_EXPECTATION_FAILED = 417 top

HTTP_FAILED_DEPENDENCY = 424 top

HTTP_FORBIDDEN = 403 top

HTTP_GATEWAY_TIME_OUT = 504 top

HTTP_GONE = 410 top

HTTP_IM_USED = 226 top

HTTP_INSUFFICIENT_STORAGE = 507 top

HTTP_INTERNAL_SERVER_ERROR = 500 top

Server Error

HTTP_I_AM_A_TEAPOT = 418 top

HTTP_LENGTH_REQUIRED = 411 top

HTTP_LOCKED = 423 top

HTTP_LOOP_DETECTED = 508 top

HTTP_METHOD_NOT_ALLOWED = 405 top

HTTP_MOVED_PERMANENTLY = 301 top

HTTP_MOVED_TEMPORARILY = 302 top

HTTP_MULTIPLE_CHOICES = 300 top

Redirection

HTTP_MULTI_STATUS = 207 top

HTTP_NETWORK_AUTHENTICATION_REQUIRED = 511 top

HTTP_NETWORK_CONNECT_TIMEOUT_ERROR = 599 top

HTTP_NON_AUTHORITATIVE = 203 top

HTTP_NOT_ACCEPTABLE = 406 top

HTTP_NOT_EXTENDED = 510 top

HTTP_NOT_FOUND = 404 top

HTTP_NOT_IMPLEMENTED = 501 top

HTTP_NOT_MODIFIED = 304 top

HTTP_NO_CONTENT = 204 top

HTTP_OK = 200 top

Success

HTTP_PARTIAL_CONTENT = 206 top

HTTP_PAYMENT_REQUIRED = 402 top

HTTP_PERMANENT_REDIRECT = 308 top

HTTP_PRECONDITION_FAILED = 412 top

HTTP_PRECONDITION_REQUIRED = 428 top

HTTP_PROCESSING = 102 top

HTTP_PROXY_AUTHENTICATION_REQUIRED = 407 top

HTTP_RANGE_NOT_SATISFIABLE = 416 top

HTTP_REQUEST_ENTITY_TOO_LARGE = 413 top

HTTP_REQUEST_HEADER_FIELDS_TOO_LARGE = 431 top

HTTP_REQUEST_TIME_OUT = 408 top

HTTP_REQUEST_URI_TOO_LARGE = 414 top

HTTP_RESET_CONTENT = 205 top

HTTP_SEE_OTHER = 303 top

HTTP_SERVICE_UNAVAILABLE = 503 top

HTTP_SWITCHING_PROTOCOLS = 101 top

HTTP_TEMPORARY_REDIRECT = 307 top

HTTP_TOO_MANY_REQUESTS = 429 top

HTTP_UNAUTHORIZED = 401 top

HTTP_UNAVAILABLE_FOR_LEGAL_REASONS = 451 top

HTTP_UNPROCESSABLE_ENTITY = 422 top

HTTP_UNSUPPORTED_MEDIA_TYPE = 415 top

HTTP_UPGRADE_REQUIRED = 426 top

HTTP_USE_PROXY = 305 top

HTTP_VARIANT_ALSO_VARIES = 506 top

HTTP_VERSION_NOT_SUPPORTED = 505 top

METHOD_ALL = 511 top

short constants for set all method types METHOD_HEAD | ... | METHOD_PATCH

METHOD_CONNECT = 128 top

METHOD_DELETE = 16 top

METHOD_GET = 2 top

METHOD_GET_POST = 7 top

short constant for set METHOD_HEAD | METHOD_GET | METHOD_POST

METHOD_HEAD = 1 top

METHOD_OPTIONS = 64 top

METHOD_PATCH = 256 top

METHOD_POST = 4 top

METHOD_PUT = 8 top

METHOD_TRACE = 32 top

methods = {'HEAD': 1, 'GET': 2, 'POST': 4, 'PUT': 8, 'DELETE': 16, 'TRACE': 32, 'OPTIONS': 64, 'CONNECT': 128, 'PATCH': 256} top

know method types

sorted_methods = [('HEAD', 1), ('GET', 2), ('POST', 4), ('PUT', 8), ('DELETE', 16), ('TRACE', 32), ('OPTIONS', 64), ('CONNECT', 128), ('PATCH', 256)] top

module openapi_wrapper link | top

OpenAPI core wrappers module.

This module, and only this module requires openapi_core python module from https://github.com/p1c2u/openapi-core with version 0.13.0 or higher.

Classes:

OpenAPIRequest, OpenAPIResponse

Module dependences: collections, openapi_core.datatypes, re

class OpenAPIRequest link | top

Wrapper of PoorWSGI request to OpenAPIRequest.

Be careful with testing of big incoming request body property, which returns Request.data depend on auto_data and data_size configuration properties. Request.data is available only when request Content-Length is available.

body (READ) top

Return request data for validator.

full_url_pattern (READ) top

Return full_url_pattern for validator.

host_url (READ) top

Return host_url for validator.

method (READ) top

Return method in lower case for validator.

mimetype (READ) top

Return request mime_type for validator.

parameters (READ) top

Return RequestParameters object for validator.

path (READ) top

Return method path

def __init__(self, request) link | top

Initialize self. See help(type(self)) for accurate signature.

class OpenAPIResponse link | top

Wrapper of PoorWSGI request to OpenAPIResponse.

data (READ) top

Return response data for validator.

Warning! This will not work for generator responses"

headers (READ) top

Return response headers for validator.

mimetype (READ) top

Return response mime_type for validator.

status_code (READ) top

Return response status_code for validator.

def __init__(self, response) link | top

Initialize self. See help(type(self)) for accurate signature.