logo

Poor WSGI for Python

Light WSGI connector with uri routing support.

poorwsgi

wsgi

Application

request

Args

BrokenClientConnection

EmptyForm

FieldStorage

Headers

Json

Request

results

SERVER_RETURN

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

redirect

send_file

send_json

uni

session

NoCompress

PoorSession

hidden

state

module poorwsgi link | top

Poor WSGI connector for Python

Current Contents:
    * request - Headers, Request and FieldStorage classes, which
                is used for managing requests.

    * results - default result handlers of connector like: directory index,
                send_file, SERVER_RETURN, redirect, servers errors or debug
                output handler.

    * session - self-contained cookie based session class

    * state   - constants like http status code, log levels and method types

    * wsgi    - Application callable class, which is the main point for
                poorwsgi web application.
Module dependences: poorwsgi.results , poorwsgi.wsgi , request , results , results , state , wsgi

app = __poorwsgi__ - callable Application class instance top

Short reference to application instance ( DEPRECATED )

application = __poorwsgi__ - callable Application class instance top

Application callable instance, which is need by wsgi server ( DEPRECATED )

module wsgi link | top

Application callable class, which is the main point for poorwsgi web application.
Module dependences: collections , path , poorwsgi.request , 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.

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_form (READ | WRITE) top

Automatic parsing arguments from request body.

If it is True (default) and method is POST, PUT or PATCH, 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 content type is one of json_content_types, Request object do automatic parsing request body to json variable.

debug (READ | WRITE) top

Application debug as another way how to set poor_Debug.

This setting will be rewrite by poor_Debug environment variable.

dhandlers (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.

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 unicoee word
:hex - match hexadecimal value and convert it to str
:re: - match user defined regular expression
none - match any string withount '/' character

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

handlers (READ) top

Copy of table with static handlers.

See Application.route.

json_content_types (READ) top

Copy of json content type list.

Containt list of strings as json content 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.

post (READ) top

Tuple of table with post-process handlers.

See Application.post_process.

pre (READ) top

Tuple of table with pre-process handlers.

See Application.pre_process.

rhandlers (READ) top

Copy of table with regular expression handlers.

See Application.route and Application.rroute.

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.

shandlers (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, environ, 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, environ, start_response) link | top

Profiler version of __request__.

This method is used if set_profile is used.

def __repr__(self) link | top

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

Create Request instance and return wsgi response.

This method create Request object, call handlers from Application.__pre (Application.handler_from_pre), uri handler (handler_from_table), default handler (Application.handler_from_default) or error handler (Application.error_from_table), and handlers from Application.__post.

def add_post_process(self, fn) link | top

Append post process handler.

Method for direct append function to list functions which are called after each request.
    app.add_post_process(after_each_request)

def add_pre_process(self, fn) link | top

Append pre proccess handler.

Method adds function to list functions which is call before each request.
    app.add_pre_process(before_each_request)

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(self) 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.
    poor_LogLevel = warn        # Poor WSGI variable
    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_default(self, req) link | top

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

def handler_from_pre(self, req) link | top

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

This method was call before end-point route handler.

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.

def is_route(self, uri) link | top

Check if uri have any registered record.

def is_rroute(self, r_uri) link | top

Check if regular expression uri have any registered record.

def log_debug(self, message) link | top

Logging method, which create message as LOG_DEBUG level.

def log_error(self, message, level=(3, 'E')) link | top

Logging method with the same functionality like in Request object.

But as get_options read configuration from os.environ which could not work in same wsgi servers like Apaches mod_wsgi.

This method write to stderr so messages, could not be found in servers error log!

def log_info(self, message) link | top

Logging method, which create message as LOG_INFO level.

def log_warning(self, message) link | top

Logging method, which create message as LOG_WARNING level.

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_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 pop_rroute(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 post_process(self) link | top

Append post process handler.

This decorator append function to be called after each request, if you want to use it redefined all outputs.
    @app.pre_process()
    def after_each_request(req):
        ...

def pre_process(self) link | top

Append pre process hendler.

This is decorator for function to call before each request.
    @app.pre_process()
    def before_each_request(req):
        ...

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 rroute(self, ruri, method=3) link | top

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

Both of function, rroute and set_rroute store routes to special internal table, which is another to table of static routes.
    @app.rroute(r'/user/\w+')               # simple regular expression
    def any_user(req):
        ...

    @app.rroute(r'/user/(?P<user>\w+)')     # regular expression with
    def user_detail(req, user):             # groups
        ...
Be sure with ordering of call this decorator or set_rroute function. Regular expression routes are check with the same ordering, as you create internal table of them. First match stops any other searching.

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=poorwsgi.results.uni) link | top

Create new filter or overwrite builtins.

Arguments:
name - Name of filter which is used in route or set_route
method.
regex - regular expression which used for filter
convertor - convertor function or class, which gets unicode in
input. Default is uni function, which is wrapper
to unicode string.
    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.

Arguments:
runctx - function from profiler module
dump - 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_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 set_rroute(self, r_uri, fn, method=3, convertors=()) 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.rroute documentation for details.
    app.set_rroute('/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.

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

check, if there is define filter in uri

module request link | top

Headers, Request and FieldStorage classes, which is used for managing requests.
Module dependences: Cookie , _abcoll , _io , cgi , inspect , json , os , poorwsgi.results , re , urlparse , 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

def getfirst(self, name, default=None, fce=poorwsgi.results.uni) link | top

Returns first variable value for key or default.

Arguments:
fce - function which processed value.

def getlist(self, name, fce=poorwsgi.results.uni) link | top

Returns list of variable values for key or empty list.

Arguments:
fce - function which processed value.

class BrokenClientConnection link | top

Helping class for Broken Connection Pipe detect.

def __init__(self, remote_host, remote_addr) link | top

def __str__(self) link | top

class EmptyForm link | top

Compatibility class as fallback.

This class is used when poor_AutoArgs or poor_AutoForm is set to Off.

def getfirst(self, name, default=None, fce=poorwsgi.results.uni) link | top

def getlist(self, name, fce=poorwsgi.results.uni) link | top

def getvalue(self, name, 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 - content-type of variable. All variables have internal
content-type, if that is no file, content-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 __contains__(self, key) link | top

Dictionary style __contains__ method.

def __getattr__(self, name) link | top

def __getitem__(self, key) link | top

Dictionary style indexing.

def __init__(self, req, headers=None, outerboundary='', environ={}, 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 object.
keep_blank_values - if you want to parse blank values as right
empty values.
strict_parsing - if you want to raise exception on parsing
error.
file_callback - callback for creating instance of uploading
files.

def __iter__(self) link | top

def __len__(self) link | top

Dictionary style len(x) support.

def __nonzero__(self) link | top

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, name, default=None, fce=poorwsgi.results.uni) link | top

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

Arguments:
fce - function which processed value.

def getlist(self, name, fce=poorwsgi.results.uni) link | top

Returns list of variable values for key or empty list.

Arguments:
fce - function which processed value, str is default.

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

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

def has_key(self, key) link | top

Dictionary style has_key() method.

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

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 or unicode.

def __contains__(self, key) link | top

def __delitem__(self, name) link | top

Delete item identied by lower name.

def __eq__(self, other) link | top

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 __ne__(self, other) link | top

def __repr__(self) link | top

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

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

def __subclasshook__(cls, C) link | top

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 items(self) link | top

Return tuple of headers pairs.

def iteritems(self) link | top

D.iteritems() -> an iterator over the (key, value) items of D

def iterkeys(self) link | top

D.iterkeys() -> an iterator over the keys of D

def itervalues(self) link | top

D.itervalues() -> an iterator over the values of D

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.

@staticmethod
def iso88591(value) link | top

Doing automatic conversion to iso-8859-1 strings.

In python 2.x can convert unicode to iso-8859-1 strings, or from utf-8 string to iso-8859-1 string. On python 3.x converts from utf-8 to iso-8859-1 string. That means, all input value of Headers class must be UTF-8 stings.

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

def getfirst(self, name, default=None, fce=poorwsgi.results.uni) link | top

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

Arguments:
fce - function which processed value.

def getlist(self, name, fce=poorwsgi.results.uni) link | top

Returns list of variable values for key or empty list.

Arguments:
fce - 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:
app_ - as prefix for any your application variable (not
defined)

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.

body_bytes_sent (READ) top

Internal variable to store count of bytes which are really sent.

clength (READ | WRITE) top

Property to store output content length for header.

This value was set automatically when size of output data are less then buffer size.

config (READ | WRITE) top

For config object (default None).

content_type (READ | WRITE) top

Content-Type header string, by default text/html; charset=utf-8.

Another way to set content_type is via headers_out object property.

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.

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.

environ (READ) top

Copy of table object containing request environment.

Information is get from wsgi server.

err_headers_out (READ) top

Reference to output headers object for error pages.

form (READ | WRITE) top

Dictionary like class (FieldStorage instance) of body arguments.

Arguments must be send in request body, which is typical for POST, PUT or PATCH method. 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_in (READ) top

Reference to input headers object.

headers_out (READ | WRITE) top

Reference to output headers object.

hostname (READ) top

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

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 and have XMLHttpRequest value.

json (READ) top

Json dictionary if request content type is JSON.

Json types is defined in Application.json_content_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.

logger (READ) top

DEPRECATED For special logger function (default req.log_error).

Use log_error, log_info, log_debug or logging method instead of that.

method (READ) top

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

method_number (READ) top

Method number constant from state module.

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.

secretkey (READ) top

DEPRECATED alias for secret_key.

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.

status (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.

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.

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: {_default_handler_, _directory_index_, _debug_info_ and _send_file_ }. 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 __end_of_request__(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, environ, start_response, 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 __reset_buffer__(self) link | top

Clean _buffer (*for internal server error use*).

It could be used in error pages, typical in internal_server_error. But be careful, this method not help you, when any data was sent to wsgi server.

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 document_root(self) link | top

Returns DocumentRoot setting.

def flush(self) link | top

Flushes the output buffer.

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.
        #!ini
        poor_LogLevel = warn        # Poor WSGI variable
        app_db_server = localhost   # application variable db_server
        app_templates = app/templ   # application variable templates

def get_remote_host(self) link | top

Returns REMOTE_ADDR CGI enviroment variable.

def log_debug(self, message) link | top

Logging method, which create message as LOG_DEBUG level.

def log_error(self, message, level=(3, 'E'), server=None) link | top

An interface to log error via wsgi.errors.

Arguments:
message - string with the error message
level - is one of the following flags constants:
LOG_EMERG
LOG_ALERT
LOG_CRIT
LOG_ERR (default)
LOG_WARNING
LOG_NOTICE
LOG_INFO
LOG_DEBUG
LOG_NOERRNO
server - interface only compatibility parameter

def log_info(self, message) link | top

Logging method, which create message as LOG_INFO level.

def log_warning(self, message) link | top

Logging method, which create message as LOG_WARNING level.

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 sendfile(self, path, offset=0, limit=-1) link | top

Send file defined by path to client.

Offset and len is not supported yet.
    @app.route('myfile.txt')
    def myfile(req):
        req.content_type('text/plain')
        length = req.sendfile('myfile.txt')
        req.log_error('sending myfile.txt with %d length' % length)

def set_content_lenght(self, length) link | top

DEPRECATED Use req.clength = length instead of call this method.

def write(self, data, flush=0) link | top

Write data to buffer.

If len of data is bigger then poor_BufferSize, data was be sent to client via old write method (directly). Otherwise, data was be sent at the end of request as iterable object.

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

simple regular expression for construct_url method

module results link | top

Default Poor WSGI handlers.
Module dependences: _io , inspect , json , mimetypes , operator , path , posix , sys , time , traceback

class SERVER_RETURN link | top

Compatible with mod_python.apache exception.

def __init__(self, code=500) link | top

code is one of HTTP_* status from state module

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

def redirect(req, uri, permanent=0, text=None) link | top

Redirect the browser to another location.

When permanent is true, MOVED_PERMANENTLY status 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.

This function raises SERVER_RETURN exception with a value of state.DONE to ensuring that any later phases or stacked handlers do not run.

def send_file(req, path, content_type=None) link | top

Returns file with content_type as fast as possible on wsgi.

def send_json(req, data, **kwargs) link | top

Send data as application/json.

def uni(text) link | top

Automatic conversion from str to unicode with utf-8 encoding.

default_shandlers = {400: {128: <function bad_request at 0x7f256d4afd70>, 1: <function bad_request at 0x7f256d4afd70>, 2: <function bad_request at 0x7f256d4afd70>, 4: <function bad_request at 0x7f256d4afd70>, 32: <function bad_request at ... top

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

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

module session link | top

PoorSession self-contained cookie class.
Module dependences: Cookie , __builtin__ , _hashlib , base64 , bz2 , pickle , time

class NoCompress link | top

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

If compress parameter is None, this class is use

@staticmethod
def compress(data, compresslevel=9) link | top

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

@staticmethod
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 PoorSesssion.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/python2.7/lib-dynload/bz2.x86_64-linux-gnu.so'>) link | top

Constructor.

Arguments:
req Request object
expires cookie expire time in seconds, if it 0, no expire is set
path cookie path
SID 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, req, headers_out=None) link | top

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

Returns list of cookie header pairs.

def renew(self) link | top

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

def write(self, req) 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 raw data to (en|de)crypt. Could be str, unicode or bytes
passwd password
returns string

module state link | top

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

DECLINED = 2 top

DONE = 1 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_ERROR = 3 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

LOG_ALERT = (1, 'A') top

LOG_CRIT = (2, 'C') top

LOG_DEBUG = (7, 'D') top

LOG_EMERG = (0, 'S') top

LOG_ERR = (3, 'E') top

LOG_INFO = (6, 'I') top

LOG_NOERRNO = (8, '0') top

LOG_NOTICE = (5, 'N') top

LOG_WARNING = (4, 'W') 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

OK = 0 top

levels = {'warn': (4, 'W'), 'info': (6, 'I'), 'notice': (5, 'N'), 'emerg': (0, 'S'), 'error': (3, 'E'), 'crit': (2, 'C'), 'debug': (7, 'D'), ... top

log levels which could be set with poor_LogLevel environment variable

methods = {'HEAD': 1, 'CONNECT': 128, 'TRACE': 32, 'GET': 2, 'PUT': 8, 'POST': 4, 'PATCH': 256, 'OPTIONS': 64, 'DELETE': 16} 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