logo

Poor WSGI for Python

Light WSGI connector with uri routing support.

poorwsgi

wsgi

Application

to_response

request

Args

EmptyForm

FieldStorage

Headers

Json

Request

parse_negotiation

response

EmptyResponse

FileResponse

GeneratorResponse

HTTPException

RedirectResponse

Response

StrGeneratorResponse

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

session

NoCompress

PoorSession

hidden

state

openapi_wrapper

OpenAPIRequest

OpenAPIResponse

module poorwsgi link | top

Poor WSGI connector for Python

Current Contents:

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

module wsgi link | top

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

Classes:

Application

Functions:

to_response

Module dependences: collections, logging, path, poorwsgi.request, poorwsgi.response, poorwsgi.results, posix, re

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-request handlers.

See Application.after_request.

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 paresed 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-request handlers.

See Application.before_request.

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.

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's filename from request body and have file compatibile 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.

Containt 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.

Containt 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.

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 aka error 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.error_from_table), and handlers from Application.after.

def add_after_request(self, fn) link | top

Append handler to call after each request.

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

def after_each_request(request, response):
    print("Request out")
    return response

app.add_after_request(after_each_request)

def add_before_request(self, fn) link | top

Append handler to call before each request.

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

def def before_each_request(req):
    print("Request coming")

app.add_before(before_each_request)

def after_request(self) link | top

Append handler to call after each request.

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

@app.after_each_request()
def after_each_request(request, response):
    print("Request out")
    return response

def before_request(self) link | top

Append hendler to call before each request.

This is decorator for function to call before each request.

@app.before_request()
def before_each_request(req):
    print("Request coming")

def default(self, method=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, code) link | top

Internal method, which is called if error was accured.

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

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) 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) link | top

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

def handler_from_table(self, req) 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, code, method=7) link | top

Wrap function to handle http status codes like http errors.

@app.http_state(state.HTTP_NOT_FOUND)
def page_not_found(req):
    return "Your request %s not found." % req.uri, "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) link | top

Check if uri have any registered record.

def pop_after_request(self, fn) link | top

Remove handler added by add_before_request or before_request.

def pop_before_request(self, fn) link | top

Remove handler added by add_before_request or before_request.

def pop_default(self, method) link | top

Pop default handler for method.

def pop_http_state(self, code, method) link | top

Pop handerl for http state and method.

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

def pop_regular_route(self, r_uri, method) link | top

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

For mor details see Application.pop_route.

def pop_route(self, uri, method) 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, method=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, method=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, fn, method=3) link | top

Set default handler.

Set fn default handler for http method called befor error_not_found.

app.set_default(default_get_post, METHOD_GET_POST)

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

Create new filter or overwrite builtins.

name: str

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

regex: str

Regular expression which used for filter.

convertor: function

Convertor 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, code, fn, method=7) link | top

Set fn 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, r_uri, fn, method=3, convertors=(), rule=None) link | top

Set hanlder 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, fn, method=3) link | top

Set handler for uri and method.

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

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

def to_response(response) link | top

handler response to application response.

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, collections.abc, http.cookies, json, logging, os, re, urllib.parse, wsgiref.headers

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, keep_blank_values=0, strict_parsing=0) link | top

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

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

Returns first variable value for key or default.

fce: convertor (str)

function which processed value.

def getlist(self, key, fce=<class 'str'>) link | top

Returns list of variable values for key or empty list.

fce: convertor (str)

function which processed value.

class EmptyForm link | top

Compatibility class as fallback.

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

def getlist(self, key, fce=<class 'str'>) link | top

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

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

def __contains__(self, key) link | top

Dictionary style __contains__ method.

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) link | top

Dictionary style indexing.

def __init__(self, req, headers=None, outerboundary=b'', environ=None, keep_blank_values=0, strict_parsing=0, limit=None, encoding='utf-8', errors='replace', 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, default=None) link | top

Compatibility methods with dict, alias for getvalue.

def getfirst(self, key, default=None, fce=<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, fce=<class 'str'>) link | top

Returns list of variable values for key or empty list.

Arguments:
key: str

key name

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 style keys() method.

def make_file(self, binary=None) link | top

Return readable and writable temporary file.

Arguments:
binary: None

Unused. Here is only for backward compatibility

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 Headers link | top

Class inherited from collections.Mapping.

As PEP 333, resp. RFC 2616 says, all headers names must be only US-ASCII character except control characters or separators. And headers values must be store in string encoded in ISO-8859-1. This class methods Headers.add and Headers.add_header do auto convert values from UTF-8 to ISO-8859-1 encoding if it is possible. So on every modification methods must be use UTF-8 string.

def __contains__(self, key) link | top

def __delitem__(self, name) link | top

Delete item identied by lower name.

def __eq__(self, other) link | top

Return self==value.

def __getitem__(self, name) link | top

Return header item identified by lower name.

def __init__(self, headers=[], strict=True) link | top

Headers constructor.

Headers object could be create from list, set or tuple of pairs name, value. Or from dictionary. All names or values must be iso-8859-1 encodable. If not, AssertionError will be raised.

If strict is False, headers names and values are not encoded to iso-8859-1. This is for input headers using only!

def __iter__(self) link | top

def __len__(self) link | top

Return len of header items.

def __repr__(self) link | top

Return repr(self).

def __setitem__(self, name, value) link | top

Delete item if exist and set it's new value.

def add(self, name, value) link | top

Set header name to value.

Duplicate names are not allowed instead of Set-Cookie.

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

Extended header setting.

name is the header field to add. kwargs arguments can be used to set additional parameters for the header field, with underscores converted to dashes. Normally the parameter will be added as name="value" unless value is None, in which case only the name will be added.

h.add_header('Content-Disposition', 'attachment',
             filename='image.png')

All names must be US-ASCII string except control characters or separators.

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

D.get(k[,d]) -> D[k] if k in D, else d. d defaults to None.

def get_all(self, name) link | top

Return tuple of all values of header identifed by lower name.

def iso88591(value) link | top

Doing automatic conversion to iso-8859-1 strings.

Converts from utf-8 to iso-8859-1 string. That means, all input value of Headers class must be UTF-8 stings.

def items(self) link | top

Return tuple of headers pairs.

def keys(self) link | top

Alias for names method.

def names(self) link | top

Return tuple of headers names.

def setdefault(self, name, value) link | top

Set header value if not exist, and return it's value.

def values(self) link | top

Return tuple of headers values.

class Json 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, req, charset) link | top

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

def getfirst(self, key, default=None, fce=<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, fce=<class 'str'>) link | top

Returns generoator of variable values for key.

fce: convertor (str)

Function which processed value.

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 neogetions values.

accept_json (READ) top

Return true if application/json mime type is in accept neogetions 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 neogetions values.

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.

charset (READ) top

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

config (READ | WRITE) top

For config object (default None).

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.

environ (READ) top

Copy of table object containing request environment.

Information is get from wsgi server.

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 if exists.

forwarded_proto (READ) top

X-Forward-Proto http header if exists.

headers (READ) top

Reference to input headers object.

hostname (READ) top

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

input (READ) top

Return input file, for internal use in FieldStorage

is_body_request (READ) top

True if request is body request type, so it is PATCH, POST or PUT.

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.

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 string.

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

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.

uri (READ) top

The path portion 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_config) 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) 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 parse_negotiation(value) link | top

Parse Content Negotiation headers to list of value, quality tuples.

log = <Logger poorwsgi (WARNING)> top

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

simple regular expression for construct_url method

module response link | top

Module dependences: _io, logging, mimetypes, poorwsgi.request, posix

class EmptyResponse link | top

For situation, where only state could be return.

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.

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) 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=200) link | top

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

def __start_response__(self, start_response) link | top

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

Call Headers.add_header on headers object.

def write(self, data) link | top

Write data to internal buffer.

class FileResponse link | top

Instead of send_file methods.

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.

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) 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, content_type=None, headers=None, status_code=200) link | top

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

def __start_response__(self, start_response) link | top

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

Call Headers.add_header on headers object.

def write(self, data) link | top

Write data to internal buffer.

class GeneratorResponse link | top

For response, which use generator as returned value.

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.

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) 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, content_type='text/html; charset=utf-8', headers=None, status_code=200) link | top

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

def __start_response__(self, start_response) link | top

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

Call Headers.add_header on headers object.

def write(self, data) link | top

Write data to internal buffer.

class HTTPException link | top

HTTP Exception to fast stop work.

def __init__(self, arg) 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.

class RedirectResponse link | top

Redirect the browser to another location.

When permanent is true, MOVED_PERMANENTLY status code is sent to the client, otherwise it is MOVED_TEMPORARILY. 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.

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.

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) 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, permanent=False, message=b'', headers=None) link | top

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

def __start_response__(self, start_response) link | top

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

Call Headers.add_header on headers object.

def write(self, data) link | top

Write data to internal buffer.

class Response link | top

HTTP Response object.

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

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.

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) 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=b'', content_type='text/html; charset=utf-8', headers=None, status_code=200) link | top

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

def __start_response__(self, start_response) link | top

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

Call Headers.add_header on headers object.

def write(self, data) link | top

Write data to internal buffer.

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.

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) 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, content_type='text/html; charset=utf-8', headers=None, status_code=200) link | top

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

def __start_response__(self, start_response) link | top

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

Call Headers.add_header on headers object.

def write(self, data) link | top

Write data to internal buffer.

def abort(arg) link | top

Raise HTTPException with arg.

def make_response(data, content_type='text/html; character=utf-8', headers=None, status_code=200) link | top

Create response from simple values.

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

def redirect(location, permanent=False, message=b'', headers=None) link | top

log = <Logger poorwsgi (WARNING)> top

module results link | top

Module dependences: genericpath, inspect, logging, mimetypes, operator, poorwsgi.response, posix, sys, time, traceback

def bad_request(req) link | top

400 Bad Request server error handler.

def debug_info(req, app) link | top

def directory_index(req, path) link | top

Returns directory index as html page.

def forbidden(req) link | top

403 - Forbidden Access server error handler.

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

Returns sorted handlers list.

def hbytes(val) link | top

Return pair value and unit.

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) 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) link | top

405 Method Not Allowed server error handler.

def not_found(req) link | top

404 - Page Not Found server error handler.

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

501 Not Implemented server error handler.

def not_modified(req) link | top

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

default_states = {304: {1: <function not_modified at 0x7ff22161c4d0>, 2: <function not_modified at 0x7ff22161c4d0>, 4: <function not_modified at 0x7ff22161c4d0>, 8: <function not_modified at 0x7ff22161c4d0>, 16: <function not_modified at... top

http state handlers, which is called if programmer don't defined his own

log = <Logger poorwsgi (WARNING)> top

module session link | top

PoorSession self-contained cookie class.

Classes:

NoCompress, PoorSession

Functions:

hidden

Module dependences: _hashlib, _pickle, base64, bz2, http.cookies, log, time

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. Be careful with stored object. You can add object with litle python trick:

sess = PoorSession(req)

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

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, req, expires=0, path='/', SID='SESSID', compress=<module 'bz2' from '/usr/lib/python3.7/bz2.py'>) link | top

Constructor.

Arguments:
expires: int

cookie expire time in seconds, if it 0, no expire is set

path: str

cookie path

SID: str

cookie key name

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.

def destroy(self) link | top

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

def header(self, headers=None) link | top

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

Returns list of cookie header pairs.

headers headers is Headers or Response object, which is used

to write header directly.

def renew(self) link | top

Renew cookie, in fact set expires to next time if it set.

def write(self) link | top

Store data to cookie value.

This method is called automatically in header method.

def hidden(text, passwd) link | top

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

Arguments:
text: str

raw data to (en|de)crypt. Could be str, or bytes

passwd: str

password

module state link | top

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

DECLINED = 0 top

HTTP_ACCEPTED = 202 top

HTTP_BAD_GATEWAY = 502 top

HTTP_BAD_REQUEST = 400 top

HTTP_CONFLICT = 409 top

HTTP_CONTINUE = 100 top

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_INSUFFICIENT_STORAGE = 507 top

HTTP_INTERNAL_SERVER_ERROR = 500 top

HTTP_LENGTH_REQUIRED = 411 top

HTTP_LOCKED = 423 top

HTTP_METHOD_NOT_ALLOWED = 405 top

HTTP_MOVED_PERMANENTLY = 301 top

HTTP_MOVED_TEMPORARILY = 302 top

HTTP_MULTIPLE_CHOICES = 300 top

HTTP_MULTI_STATUS = 207 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

HTTP_PARTIAL_CONTENT = 206 top

HTTP_PAYMENT_REQUIRED = 402 top

HTTP_PRECONDITION_FAILED = 412 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_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_UNAUTHORIZED = 401 top

HTTP_UNPROCESSABLE_ENTITY = 422 top

HTTP_UNSUPPORTED_MEDIA_TYPE = 415 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.

Classes:

OpenAPIRequest, OpenAPIResponse

Module dependences: openapi_core.wrappers.base, 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.

body (READ) top

full_url_pattern (READ) top

host_url (READ) top

method (READ) top

mimetype (READ) top

parameters (READ) top

path (READ) top

path_pattern (READ) top

def __init__(self, request) link | top

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

def get_body(self, spec) link | top

def get_parameters(self, spec) link | top

class OpenAPIResponse link | top

data (READ) top

mimetype (READ) top

status_code (READ) top

def __init__(self, response) link | top

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