web.py documentation

General Utilities

rstrips(text, remove)
removes the string remove from the right of text
lstrips(text, remove)
removes the string remove from the left of text
strips(text, remove)
removes the string remove from the both sides of text
autoassign(self, locals)

Automatically assigns local variables to self. Generally used in __init__ methods, as in:

 def __init__(self, foo, bar, baz=1): autoassign(self, locals())
class Storage(dict)
A Storage object is like a dictionary except obj.foo can be used instead of obj['foo']. Create one by doing storage({'a':1}).
storify(mapping, *requireds, **defaults)

Creates a storage object from dictionary mapping, raising KeyError if d doesn't have all of the keys in requireds and using the default values for keys found in defaults.

For example, storify({'a':1, 'c':3}, b=2, c=0) will return the equivalent of storage({'a':1, 'b':2, 'c':3}).

class Memoize
'Memoizes' a function, caching its return values for each input.
re_subm(pat, repl, string)
Like re.sub, but returns the replacement and the match object.
group(seq, size)

Returns an iterator over a series of lists of length size from iterable.

For example, list(group([1,2,3,4], 2)) returns [[1,2],[3,4]].

class IterBetter
Returns an object that can be used as an iterator but can also be used via getitem (although it cannot go backwards -- that is, you cannot request iterbetter[0] after requesting iterbetter[1]).
dictreverse(mapping)
Takes a dictionary like {1:2, 3:4} and returns {2:1, 4:3}.
dictfind(dictionary, element)
Returns a key whose value in dictionary is element or, if none exists, None.
dictfindall(dictionary, element)
Returns the keys whose values in dictionary are element or, if none exists, [].
dictincr(dictionary, element)
Increments element in dictionary, setting it to one if it doesn't exist.
dictadd(dict_a, dict_b)
Returns a dictionary consisting of the keys in a and b. If they share a key, the value from b is used.
listget(lst, ind, default=None)
Returns lst[ind] if it exists, default otherwise.
intget(integer, default=None)
Returns integer as an int or default if it can't.
upvars(level=2)
Guido van Rossum doesn't want you to use this function.
class CaptureStdout

Captures everything func prints to stdout and returns it instead.

WARNING: Not threadsafe!

class Profile
Profiles func and returns a tuple containing its output and a string with human-readable profiling information.
tryall(context, prefix=None)

Tries a series of functions and prints their results. context is a dictionary mapping names to values; the value will only be tried if it's callable.

For example, you might have a file test/stuff.py with a series of functions testing various things in it. At the bottom, have a line:

 if __name__ == "__main__": tryall(globals())

Then you can run python test/stuff.py and get the results of all the tests.

class ThreadedDict
Takes a dictionary that maps threads to objects. When a thread tries to get or set an attribute or item of the threadeddict, it passes it on to the object for that thread in dictionary.

IP Utilities

validipaddr(address)
returns True if address is a valid IPv4 address
validipport(port)
returns True if port is a valid IPv4 port
validip(ip, defaultaddr="0.0.0.0", defaultport=8080)
returns (ip_address, port) from string ip_addr_port

URL Utilities

prefixurl(base='')
Sorry, this function is really difficult to explain. Maybe some other time.

Formatting

safemarkdown(text)

Converts text to HTML following the rules of Markdown, but blocking any outside HTML input, so that only the things supported by Markdown can be used. Also converts raw URLs to links.

(requires markdown.py)

Databases

sqlors(left, lst)

left is a SQL clause liketablename.arg = andlst` is a list of values. Returns a reparam-style pair featuring the SQL that ORs together the clause for each item in the lst.

For example:

 web.sqlors('foo =', [1,2,3])

would result in:

 foo = 1 OR foo = 2 OR foo = 3
class UnknownParamstyle(Exception)
raised for unsupported db paramstyles
Currently supported: qmark,numeric, format, pyformat
aparam()
Use in a SQL string to make a spot for a db value.
reparam(string_, dictionary)

Takes a string and a dictionary and interpolates the string using values from the dictionary. Returns a 2-tuple containing the a string with aparam()s in it and a list of the matching values.

You can pass this sort of thing as a clause in any db function. Otherwise, you can pass a dictionary to the keyword argument vars and the function will call reparam for you.

class UnknownDB(Exception)
raised for unsupported dbms
connect(dbn, **keywords)
Connects to the specified database. db currently must be "postgres" or "mysql". If DBUtils is installed, connection pooling will be used.
transact()
Start a transaction.
commit()
Commits a transaction.
rollback()
Rolls back a transaction.
query(sql_query, vars=None, processed=False)
Execute SQL query sql_query using dictionary vars to interpolate it. If processed=True, vars is a reparam-style list to use instead of interpolating.
sqllist(lst)
If a list, converts it to a comma-separated string. Otherwise, returns the string.
sqlwhere(dictionary)
Converts a dictionary like {'cust_id': 2, 'order_id':3} to an SQL WHERE clause like "cust_id = 2 AND order_id = 3". @@untested
select(tables, vars=None, what='*', where=None, order=None, group=None, limit=None, offset=None):
Selects what from tables with clauses where, order, group, limit, and `offset. Uses vars to interpolate. Otherwise, each clause can take a reparam-style list.
insert(tablename, seqname=None, **values)
Inserts values into tablename. Returns current sequence ID. Set seqname to the ID if it's not the default, or to False if there isn't one.
update(tables, where, vars=None, **values)
Update tables with clause where (interpolated using vars) and setting values.
delete(table, where, using=None, vars=None)
Deletes from table with clauses where and using.

Request Handlers

handle(mapping, fvars=None)

Call the appropriate function based on the url to function mapping in mapping. If no module for the function is specified, look up the function in fvars. If fvars is empty, using the caller's context.

mapping should be a tuple of paired regular expressions with function name substitutions. handle will import modules as necessary.

autodelegate(prefix='')

Returns a method that takes one argument and calls the method named prefix+arg, calling notfound() if there isn't one. Example:

 urls = ('/prefs/(.*)', 'prefs')

 class prefs:
     GET = autodelegate('GET_')
     def GET_password(self): pass
     def GET_privacy(self): pass

GET_password would get called for /prefs/password while GET_privacy for GET_privacy gets called for /prefs/privacy.

If a user visits /prefs/password/change then GET_password(self, '/change') is called.

HTTP Functions

httpdate(date_obj)
Formats a datetime object for use in HTTP headers.
parsehttpdate(string_)
Parses an HTTP date into a datetime object.
expires(delta)
Outputs an Expires header for delta from now. delta is a timedelta object or a number of seconds.
lastmodified(date_obj)
Outputs a Last-Modified header for datetime.
modified(date=None, etag=None)
redirect(url, status='301 Moved Permanently')
Returns a status redirect to the new URL. url is joined with the base URL so that things like `redirect("about") will work properly.
found(url)
A 302 Found redirect.
seeother(url)
A 303 See Other redirect.
tempredirect(url)
A 307 Temporary Redirect redirect.
badrequest()
Return a 400 Bad Request error.
notfound()
Returns a 404 Not Found error.
nomethod(cls)
Returns a 405 Method Not Allowed error for cls.
gone()
Returns a 410 Gone error.
internalerror()
Returns a 500 Internal Server error.
djangoerror()
debugerror()

A replacement for internalerror that presents a nice page with lots of debug information for the programmer.

(Based on the beautiful 500 page from Django, designed by Wilson Miner.)

Requires Cheetah.

Rendering

htmlquote(text)
Encodes text for raw use in HTML.
websafe(val)

Converts val so that it's safe for use in HTML.

HTML metacharacters are encoded, None becomes the empty string, and unicode is converted to UTF-8.

render(template, terms=None, asTemplate=False, base=None, isString=False):

Renders a template, caching where it can.

template is the name of a file containing the a template in the templates/ folder, unless isString, in which case it's the template itself.

terms is a dictionary used to fill the template. If it's None, then the caller's local variables are used instead, plus context, if it's not already set, is set to context.

If asTemplate is False, it outputs the template directly. Otherwise, it returns the template object.

If the template is a potential base template (that is, something other templates) can extend, then base should be a string with the name of the template. The template will be cached and made available for future calls to render.

Requires Cheetah.

Input Forms

input(*requireds, **defaults)
Returns a storage object with the GET and POST arguments. See storify for how requireds and defaults work.
data()
Returns the data sent with the request.

Cookies

setcookie(name, value, expires="", domain=None)
Sets a cookie.
cookies(*requireds, **defaults)
Returns a storage object with all the cookies in it. See storify for how requireds and defaults work.

WSGI Sugar

header(hdr, value)
Adds the header hdr: value with the response.
output(string_)
Appends string_ to the response.
write(cgi_response)
Converts a standard CGI-style string response into header and output calls.
webpyfunc(inp, fvars=None, autoreload=False)
If inp is a url mapping, returns a function that calls handle.
wsgifunc(func, *middleware)
Returns a WSGI-compatible function from a webpy-function.
run(inp, *middleware)

Starts handling requests. If called in a CGI or FastCGI context, it will follow that protocol. If called from the command line, it will start an HTTP server on the port named in the first command line argument, or, if there is no argument, on port 8080.

input is a callable, then it's called with no arguments. Otherwise, it's a mapping object to be passed to handle(...).

Caveat: So that reloader will work correctly, input has to be a variable, it can't be a tuple passed in directly.

middleware is a list of WSGI middleware which is applied to the resulting WSGI function.

runwsgi(func)
Runs a WSGI-compatible function using FCGI, SCGI, or a simple web server, as appropriate.
runsimple(func, server_address=("0.0.0.0", 8080))

Runs a simple HTTP server hosting WSGI app func. The directory static/ is hosted statically.

Based on WsgiServer from Colin Stewart.

makeserver(wsgi_server)
Updates a flup-style WSGIServer with web.py-style error support.
runfcgi(func)
Runs a WSGI-function with a FastCGI server.
runscgi(func)
Runs a WSGI-function with an SCGI server.

Debugging

debug(*args)
Prints a prettyprinted version of args to stderr.
debugwrite(x)
writes debug data to error stream
class Reloader
Before every request, checks to see if any loaded modules have changed on disk and, if so, reloads them.
profiler(app)
Outputs basic profiling information at the bottom of each response.

Context

load()

Loads a new context for the thread.

You can ask for a function to be run at loadtime by adding it to the dictionary loadhooks.

unload()

Unloads the context for the thread.

You can ask for a function to be run at loadtime by adding it ot the dictionary unloadhooks.

ctx

A storage object containing various information about the request:

environ (aka env)
A dictionary containing the standard WSGI environment variables.
host
The domain (Host header) requested by the user.
home
The base path for the application.
ip
The IP address of the requester.
method
The HTTP method used.
path
The path request.
fullpath
The full path requested, including query arguments.

Response Data

status (default: "200 OK")
The status code to be used in the response.
headers
A list of 2-tuples to be used in the response.
output
A string to be used as the response.

Comments? Questions? Suggestions? Requests? Email webpy@aaronsw.com.