5.7.9. vlcp.utils.http

Note

This document is generated from the source file.

View Source on GitHub

Created on 2015/11/10

author:hubo
class vlcp.utils.http.Dispatcher(scheduler=None, daemon=False, vhost='')
__init__(scheduler=None, daemon=False, vhost='')

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

classmethod expand(match, expand)

If use expand directly, the url-decoded context will be decoded again, which create a security issue. Hack expand to quote the text before expanding

redirect(path, expand, status=302, host=None, vhost=None, method=[b'GET', b'HEAD'], keepquery=True)

Automatically redirect a request to another location

rewrite(path, expand, newmethod=None, host=None, vhost=None, method=[b'GET', b'HEAD'], keepquery=True)

Automatically rewrite a request to another location

route(path, routinemethod, container=None, host=None, vhost=None, method=[b'GET', b'HEAD'])

Route specified path to a WSGI-styled routine factory

Parameters:
  • path – path to match, can be a regular expression
  • routinemethod – factory function routinemethod(env), env is an Environment object see also utils.http.Environment
  • container – routine container
  • host – if specified, only response to request to specified host
  • vhost – if specified, only response to request to specified vhost. If not specified, response to dispatcher default vhost.
  • method – if specified, response to specified methods
routeargs(path, routinemethod, container=None, host=None, vhost=None, method=[b'POST'], tostr=True, matchargs=(), fileargs=(), queryargs=(), cookieargs=(), sessionargs=(), csrfcheck=False, csrfarg='_csrf', formlimit=67108864)

Convenient way to route a processor with arguments. Automatically parse arguments and pass them to the corresponding handler arguments. If required arguments are missing, HttpInputException is thrown which creates a 400 Bad Request response. If optional arguments are missing, they are replaced with default values just as normal Python call does. If handler accepts keyword arguments, extra arguments are sent with kwargs. If not, they are safely ignored.

Parameters:
  • path – path to match, can be a regular expression
  • routinemethod – factory function routinemethod(env, arga, argb, argc…). env is an Environment object. form or querystring arguments ‘arga’, ‘argb’, ‘argc’ are passed to arga, argb, argc.
  • container – routine container
  • host – if specified, only response to request to specified host
  • vhost – if specified, only response to request to specified vhost. If not specified, response to dispatcher default vhost.
  • method – methods allowed. With POST method, arguments are extracted from form by default; With GET or HEAD method, arguments are extracted from querystring(args).
  • tostr – In Python3, convert bytes to str before sending arguments to handler.
  • matchargs – Instead of using form or args, extract arguments from path match. matchargs is a sequence of matcher group names. If specified a group name by number, the argument is used as positional arguments; if specified a group name by name(str), the argument is used as a keyword argument.
  • fileargs – Instead of using form or args, extract specified arguments from files.
  • queryargs – Instead of using form, extract specified arguments from args. Notice that when GET is allowed, the arguments are always extracted from args by default.
  • cookieargs – Instead of using form or args, extract specified arguments from cookies.
  • sessionargs – Instead of using form or args, extract specified arguments from session. Notice that if sessionargs is not empty, env.sessionstart() is called, so vlcp.service.utils.session.Session module must be loaded.
  • csrfcheck – If True, check <csrfarg> in input arguments against <csrfarg> in session. Notice that csrfcheck=True cause env.sessionstart() to be called, so vlcp.service.utils.session.Session module must be loaded.
  • csrfarg – argument name to check, default to “_csrf”
  • formlimit – limit on parseform, default to 64MB. None to no limit.

For example, if using:

async def handler(env, target, arga, argb, argc):
   ...

dispatcher.routeargs(b'/do/(.*)', handler, matchargs=(1,), queryargs=('argc'))

And there is a HTTP POST:

POST /do/mytarget?argc=1 HTTP/1.1
Host: ...
...

arga=test&argb=test2

then handler accepts arguments: target=”mytarget”, arga=”test”, argb=”test2”, argc=”1”

routeevent(path, routinemethod, container=None, host=None, vhost=None, method=[b'GET', b'HEAD'])

Route specified path to a routine factory

Parameters:
  • path – path to match, can be a regular expression
  • routinemethod – factory function routinemethod(event), event is the HttpRequestEvent
  • container – routine container. If None, default to self for bound method, or event.connection if not
  • host – if specified, only response to request to specified host
  • vhost – if specified, only response to request to specified vhost. If not specified, response to dispatcher default vhost.
  • method – if specified, response to specified methods
class vlcp.utils.http.Environment(event, container=None, defaultencoding='utf-8')

Environment object used in HTTP handlers

__init__(event, container=None, defaultencoding='utf-8')

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

__repr__(*args, **kwargs)

Return repr(self).

argstostr()

Query string arguments are bytes in Python3. This function Convert bytes to string with env.encoding(default to utf-8).

basicauth(realm=b'all', nofail=False)

Try to get the basic authorize info, return (username, password) if succeeded, return 401 otherwise

basicauthfail(realm=b'all')

Return 401 for authentication failure. This will end the handler.

bufferoutput()

Buffer the whole output until write EOF or flushed.

close()

Close this request, send all data. You can still run other operations in the handler.

cookietostr()

Cookie values are bytes in Python3. This function Convert bytes to string with env.encoding(default to utf-8).

createcsrf(csrfarg='_csrf')

Create a anti-CSRF token in the session

error(status=500, allowredirect=True, close=True, showerror=None, headers=[])

Show default error response

escape(text, quote=True)

Escape special characters in HTML

exit(output=b'')

Exit current HTTP processing

flush(eof=False)

Flush the current output stream buffer

getrealpath(root, path)

Return the real path on disk from the query path, from a root path. The input path from URL might be absolute ‘/abc’, or point to parent ‘../test’, or even with UNC or drive ‘testbc’, ‘c: est.abc’, which creates security issues when accessing file contents with the path. With getrealpath, these paths cannot point to files beyond the root path.

Parameters:
  • root – root path of disk files, any query is limited in root directory.
  • path – query path from URL.
header(key, value, replace=True)

Send a new header

nl2br(text)
Replace ‘

‘ with ‘<br/>n’

output(stream, disabletransferencoding=None)

Set output stream and send response immediately

outputdata(data)

Send output with fixed length data

outputjson(obj)

Serialize obj with JSON and output to the client

parseform(limit=67108864, tostr=True, safename=True)

Parse form-data with multipart/form-data or application/x-www-form-urlencoded In Python3, the keys of form and files are unicode, but values are bytes If the key ends with ‘[]’, it is considered to be a list: a=1&b=2&b=3 => {‘a’:1,’b’:3} a[]=1&b[]=2&b[]=3 => {‘a’:[1],’b’:[2,3]} :param limit: limit total input size, default to 64MB. None = no limit. Note that all the form data is stored in memory (including upload files), so it is dangerous to accept a very large input. :param tostr: convert values to str in Python3. Only apply to form, files data are always bytes :param safename: if True, extra security checks are performed on filenames to reduce known security risks.

rawheader(kv, replace=True)

Add a header with “<Header>: Value” string

redirect(path, status=302)

Redirect this request with 3xx status

rewrite(path, method=None, keepresponse=True)

Rewrite this request to another processor. Must be called before header sent

sessiondestroy()

Destroy current session. The session object is discarded and can no longer be used in other requests.

sessionstart()

Start session. Must start service.utils.session.Session to use this method

setcookie(key, value, max_age=None, expires=None, path='/', domain=None, secure=None, httponly=False)

Add a new cookie

startResponse(status=200, headers=[], clearheaders=True, disabletransferencoding=False)

Start to send response

start_response(status=200, headers=[], clearheaders=True, disabletransferencoding=False)

Start to send response

write(data, eof=False, buffering=True)

Write output to current output stream

writelines(lines, eof=False, buffering=True)

Write lines to current output stream

exception vlcp.utils.http.HttpExitException
class vlcp.utils.http.HttpHandler(scheduler=None, daemon=False, vhost='')
__init__(scheduler=None, daemon=False, vhost='')

Create the routine container.

Parameters:
  • scheduler – The scheduler. This must be set; if None is used, it must be set with container.bind(scheduler) before using.
  • daemon – If daemon = True, the main routine container.main is set to be a daemon routine. A daemon routine does not stop the scheduler from quitting; if all non-daemon routines are quit, the scheduler stops.
close()

Same as terminate()

static routeargs(path, host=None, vhost=None, method=[b'POST'], **kwargs)

For extra arguments, see Dispatcher.routeargs. They must be specified by keyword arguments

start(asyncStart=False)

Start container.main as the main routine.

Parameters:asyncStart – if True, start the routine in background. By default, the routine starts in foreground, which means it is executed to the first yield statement before returning. If the started routine raises an exception, the exception is re-raised to the caller of start
exception vlcp.utils.http.HttpInputException
exception vlcp.utils.http.HttpRewriteLoopException
vlcp.utils.http.http(container=None)

wrap a WSGI-style class method to a HTTPRequest event handler

vlcp.utils.http.statichttp(container=None)

wrap a WSGI-style function to a HTTPRequest event handler