home > api docs

api docs

module web.application

Web application (from web.py)

class application(self, mapping=(), fvars={}, autoreload=None)

Application to delegate requests based on path.

>>> urls = ("/hello", "hello")
>>> app = application(urls, globals())
>>> class hello:
...     def GET(self): return "hello"
>>>
>>> app.request("/hello").data
'hello'

method add_mapping(self, pattern, classname)

method add_processor(self, processor)

Adds a processor to the application.

>>> urls = ("/(.*)", "echo")
>>> app = application(urls, globals())
>>> class echo:
...     def GET(self, name): return name
...
>>>
>>> def hello(handler): return "hello, " +  handler()
...
>>> app.add_processor(hello)
>>> app.request("/web.py").data
'hello, web.py'

method browser(self)

method cgirun(self, *middleware)

Return a CGI handler. This is mostly useful with Google App Engine. There you can just do:

main = app.cgirun()

method get_parent_app(self)

method handle(self)

method handle_with_processors(self)

method init_mapping(self, mapping)

method internalerror(self)

Returns HTTPError with '500 internal error' message

method load(self, env)

Initializes ctx using env.

method notfound(self)

Returns HTTPError with '404 not found' message

method request(self, localpart='/', method='GET', data=None, host='0.0.0.0:8080', headers=None, https=False, **kw)

Makes request to this application for the specified path and method. Response will be a storage object with data, status and headers.

>>> urls = ("/hello", "hello")
>>> app = application(urls, globals())
>>> class hello:
...     def GET(self): 
...         web.header('Content-Type', 'text/plain')
...         return "hello"
...
>>> response = app.request("/hello")
>>> response.data
'hello'
>>> response.status
'200 OK'
>>> response.headers['Content-Type']
'text/plain'

To use https, use https=True.

>>> urls = ("/redirect", "redirect")
>>> app = application(urls, globals())
>>> class redirect:
...     def GET(self): raise web.seeother("/foo")
...
>>> response = app.request("/redirect")
>>> response.headers['Location']
'http://0.0.0.0:8080/foo'
>>> response = app.request("/redirect", https=True)
>>> response.headers['Location']
'https://0.0.0.0:8080/foo'

The headers argument specifies HTTP headers as a mapping object such as a dict.

>>> urls = ('/ua', 'uaprinter')
>>> class uaprinter:
...     def GET(self):
...         return 'your user-agent is ' + web.ctx.env['HTTP_USER_AGENT']
... 
>>> app = application(urls, globals())
>>> app.request('/ua', headers = {
...      'User-Agent': 'a small jumping bean/1.0 (compatible)'
... }).data
'your user-agent is a small jumping bean/1.0 (compatible)'

method run(self, *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.

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

method wsgifunc(self, *middleware)

Returns a WSGI-compatible function for this application.

class auto_application(self)

Application similar to application but urls are constructed automatiacally using metaclass.

>>> app = auto_application()
>>> class hello(app.page):
...     def GET(self): return "hello, world"
...
>>> class foo(app.page):
...     path = '/foo/.*'
...     def GET(self): return "foo"
>>> app.request("/hello").data
'hello, world'
>>> app.request('/foo/bar').data
'foo'

method add_mapping(self, pattern, classname)

method add_processor(self, processor)

Adds a processor to the application.

>>> urls = ("/(.*)", "echo")
>>> app = application(urls, globals())
>>> class echo:
...     def GET(self, name): return name
...
>>>
>>> def hello(handler): return "hello, " +  handler()
...
>>> app.add_processor(hello)
>>> app.request("/web.py").data
'hello, web.py'

method browser(self)

method cgirun(self, *middleware)

Return a CGI handler. This is mostly useful with Google App Engine. There you can just do:

main = app.cgirun()

method get_parent_app(self)

method handle(self)

method handle_with_processors(self)

method init_mapping(self, mapping)

method internalerror(self)

Returns HTTPError with '500 internal error' message

method load(self, env)

Initializes ctx using env.

method notfound(self)

Returns HTTPError with '404 not found' message

method request(self, localpart='/', method='GET', data=None, host='0.0.0.0:8080', headers=None, https=False, **kw)

Makes request to this application for the specified path and method. Response will be a storage object with data, status and headers.

>>> urls = ("/hello", "hello")
>>> app = application(urls, globals())
>>> class hello:
...     def GET(self): 
...         web.header('Content-Type', 'text/plain')
...         return "hello"
...
>>> response = app.request("/hello")
>>> response.data
'hello'
>>> response.status
'200 OK'
>>> response.headers['Content-Type']
'text/plain'

To use https, use https=True.

>>> urls = ("/redirect", "redirect")
>>> app = application(urls, globals())
>>> class redirect:
...     def GET(self): raise web.seeother("/foo")
...
>>> response = app.request("/redirect")
>>> response.headers['Location']
'http://0.0.0.0:8080/foo'
>>> response = app.request("/redirect", https=True)
>>> response.headers['Location']
'https://0.0.0.0:8080/foo'

The headers argument specifies HTTP headers as a mapping object such as a dict.

>>> urls = ('/ua', 'uaprinter')
>>> class uaprinter:
...     def GET(self):
...         return 'your user-agent is ' + web.ctx.env['HTTP_USER_AGENT']
... 
>>> app = application(urls, globals())
>>> app.request('/ua', headers = {
...      'User-Agent': 'a small jumping bean/1.0 (compatible)'
... }).data
'your user-agent is a small jumping bean/1.0 (compatible)'

method run(self, *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.

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

method wsgifunc(self, *middleware)

Returns a WSGI-compatible function for this application.

class subdir_application(self, mapping=(), fvars={}, autoreload=None)

Application to delegate requests based on path.

>>> urls = ("/hello", "hello")
>>> app = application(urls, globals())
>>> class hello:
...     def GET(self): return "hello"
>>>
>>> app.request("/hello").data
'hello'

method add_mapping(self, pattern, classname)

method add_processor(self, processor)

Adds a processor to the application.

>>> urls = ("/(.*)", "echo")
>>> app = application(urls, globals())
>>> class echo:
...     def GET(self, name): return name
...
>>>
>>> def hello(handler): return "hello, " +  handler()
...
>>> app.add_processor(hello)
>>> app.request("/web.py").data
'hello, web.py'

method browser(self)

method cgirun(self, *middleware)

Return a CGI handler. This is mostly useful with Google App Engine. There you can just do:

main = app.cgirun()

method get_parent_app(self)

method handle(self)

method handle_with_processors(self)

method init_mapping(self, mapping)

method internalerror(self)

Returns HTTPError with '500 internal error' message

method load(self, env)

Initializes ctx using env.

method notfound(self)

Returns HTTPError with '404 not found' message

method request(self, localpart='/', method='GET', data=None, host='0.0.0.0:8080', headers=None, https=False, **kw)

Makes request to this application for the specified path and method. Response will be a storage object with data, status and headers.

>>> urls = ("/hello", "hello")
>>> app = application(urls, globals())
>>> class hello:
...     def GET(self): 
...         web.header('Content-Type', 'text/plain')
...         return "hello"
...
>>> response = app.request("/hello")
>>> response.data
'hello'
>>> response.status
'200 OK'
>>> response.headers['Content-Type']
'text/plain'

To use https, use https=True.

>>> urls = ("/redirect", "redirect")
>>> app = application(urls, globals())
>>> class redirect:
...     def GET(self): raise web.seeother("/foo")
...
>>> response = app.request("/redirect")
>>> response.headers['Location']
'http://0.0.0.0:8080/foo'
>>> response = app.request("/redirect", https=True)
>>> response.headers['Location']
'https://0.0.0.0:8080/foo'

The headers argument specifies HTTP headers as a mapping object such as a dict.

>>> urls = ('/ua', 'uaprinter')
>>> class uaprinter:
...     def GET(self):
...         return 'your user-agent is ' + web.ctx.env['HTTP_USER_AGENT']
... 
>>> app = application(urls, globals())
>>> app.request('/ua', headers = {
...      'User-Agent': 'a small jumping bean/1.0 (compatible)'
... }).data
'your user-agent is a small jumping bean/1.0 (compatible)'

method run(self, *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.

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

method wsgifunc(self, *middleware)

Returns a WSGI-compatible function for this application.

class subdomain_application(self, mapping=(), fvars={}, autoreload=None)

Application to delegate requests based on the host.

>>> urls = ("/hello", "hello")
>>> app = application(urls, globals())
>>> class hello:
...     def GET(self): return "hello"
>>>
>>> mapping = (r"hello\.example\.com", app)
>>> app2 = subdomain_application(mapping)
>>> app2.request("/hello", host="hello.example.com").data
'hello'
>>> response = app2.request("/hello", host="something.example.com")
>>> response.status
'404 Not Found'
>>> response.data
'not found'

method add_mapping(self, pattern, classname)

method add_processor(self, processor)

Adds a processor to the application.

>>> urls = ("/(.*)", "echo")
>>> app = application(urls, globals())
>>> class echo:
...     def GET(self, name): return name
...
>>>
>>> def hello(handler): return "hello, " +  handler()
...
>>> app.add_processor(hello)
>>> app.request("/web.py").data
'hello, web.py'

method browser(self)

method cgirun(self, *middleware)

Return a CGI handler. This is mostly useful with Google App Engine. There you can just do:

main = app.cgirun()

method get_parent_app(self)

method handle(self)

method handle_with_processors(self)

method init_mapping(self, mapping)

method internalerror(self)

Returns HTTPError with '500 internal error' message

method load(self, env)

Initializes ctx using env.

method notfound(self)

Returns HTTPError with '404 not found' message

method request(self, localpart='/', method='GET', data=None, host='0.0.0.0:8080', headers=None, https=False, **kw)

Makes request to this application for the specified path and method. Response will be a storage object with data, status and headers.

>>> urls = ("/hello", "hello")
>>> app = application(urls, globals())
>>> class hello:
...     def GET(self): 
...         web.header('Content-Type', 'text/plain')
...         return "hello"
...
>>> response = app.request("/hello")
>>> response.data
'hello'
>>> response.status
'200 OK'
>>> response.headers['Content-Type']
'text/plain'

To use https, use https=True.

>>> urls = ("/redirect", "redirect")
>>> app = application(urls, globals())
>>> class redirect:
...     def GET(self): raise web.seeother("/foo")
...
>>> response = app.request("/redirect")
>>> response.headers['Location']
'http://0.0.0.0:8080/foo'
>>> response = app.request("/redirect", https=True)
>>> response.headers['Location']
'https://0.0.0.0:8080/foo'

The headers argument specifies HTTP headers as a mapping object such as a dict.

>>> urls = ('/ua', 'uaprinter')
>>> class uaprinter:
...     def GET(self):
...         return 'your user-agent is ' + web.ctx.env['HTTP_USER_AGENT']
... 
>>> app = application(urls, globals())
>>> app.request('/ua', headers = {
...      'User-Agent': 'a small jumping bean/1.0 (compatible)'
... }).data
'your user-agent is a small jumping bean/1.0 (compatible)'

method run(self, *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.

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

method wsgifunc(self, *middleware)

Returns a WSGI-compatible function for this application.

function loadhook(h)

Converts a load hook into an application processor.

>>> app = auto_application()
>>> def f(): "something done before handling request"
...
>>> app.add_processor(loadhook(f))

function unloadhook(h)

Converts an unload hook into an application processor.

>>> app = auto_application()
>>> def f(): "something done after handling request"
...
>>> app.add_processor(unloadhook(f))

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

module web.contrib.template

Interface to various templating engines.

class render_cheetah(self, path)

Rendering interface to Cheetah Templates.

Example:

render = render_cheetah('templates')
render.hello(name="cheetah")

class render_genshi(self, *a, **kwargs)

Rendering interface genshi templates. Example:

for xml/html templates.

render = render_genshi(['templates/'])
render.hello(name='genshi')

For text templates:

render = render_genshi(['templates/'], type='text')
render.hello(name='genshi')

class render_mako(self, *a, **kwargs)

Rendering interface to Mako Templates.

Example:

render = render_mako(directories=['templates'])
render.hello(name="mako")

class cache(self, render)

Cache for any rendering interface.

Example:

render = cache(render_cheetah("templates/"))
render.hello(name='cache')

module web.db

Database API (part of web.py)

type UnknownParamstyle

raised for unsupported db paramstyles

(currently supported: qmark, numeric, format, pyformat)

type UnknownDB

raised for unsupported dbms

type TransactionError

function sqllist(lst)

Converts the arguments for use in something like a WHERE clause.

>>> sqllist(['a', 'b'])
'a, b'
>>> sqllist('a')
'a'
>>> sqllist(u'abc')
u'abc'

function sqlors(left, lst)

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

>>> sqlors('foo = ', [])
<sql: '1=2'>
>>> sqlors('foo = ', [1])
<sql: 'foo = 1'>
>>> sqlors('foo = ', 1)
<sql: 'foo = 1'>
>>> sqlors('foo = ', [1,2,3])
<sql: '(foo = 1 OR foo = 2 OR foo = 3 OR 1=2)'>

function reparam(string_, dictionary)

Takes a string and a dictionary and interpolates the string using values from the dictionary. Returns an SQLQuery for the result.

>>> reparam("s = $s", dict(s=True))
<sql: "s = 't'">
>>> reparam("s IN $s", dict(s=[1, 2]))
<sql: 's IN (1, 2)'>

function sqlquote(a)

Ensures a is quoted properly for use in a SQL query.

>>> 'WHERE x = ' + sqlquote(True) + ' AND y = ' + sqlquote(3)
<sql: "WHERE x = 't' AND y = 3">
>>> 'WHERE x = ' + sqlquote(True) + ' AND y IN ' + sqlquote([2, 3])
<sql: "WHERE x = 't' AND y IN (2, 3)">

type SQLQuery(self, items=None)

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.

Internally, consists of items, which is a list of strings and SQLParams, which get concatenated to produce the actual query.

method append(self, value)

function join(items, sep=' ', prefix=None, suffix=None, target=None)

Joins multiple queries.

SQLQuery.join(['a', 'b'], ', ')

Optinally, prefix and suffix arguments can be provided.

SQLQuery.join(['a', 'b'], ', ', prefix='(', suffix=')')

If target argument is provided, the items are appended to target instead of creating a new SQLQuery.

method query(self, paramstyle=None)

Returns the query part of the sql query.

q = SQLQuery(["SELECT * FROM test WHERE name=", SQLParam('joe')]) q.query() 'SELECT * FROM test WHERE name=%s' q.query(paramstyle='qmark') 'SELECT * FROM test WHERE name=?'

method values(self)

Returns the values of the parameters used in the sql query.

q = SQLQuery(["SELECT * FROM test WHERE name=", SQLParam('joe')]) q.values() ['joe']

type SQLParam(self, value)

Parameter in SQLQuery.

>>> q = SQLQuery(["SELECT * FROM test WHERE name=", SQLParam("joe")])
>>> q
<sql: "SELECT * FROM test WHERE name='joe'">
>>> q.query()
'SELECT * FROM test WHERE name=%s'
>>> q.values()
['joe']

method get_marker(self, paramstyle='pyformat')

method sqlquery(self)

type sqlparam(self, value)

Parameter in SQLQuery.

>>> q = SQLQuery(["SELECT * FROM test WHERE name=", SQLParam("joe")])
>>> q
<sql: "SELECT * FROM test WHERE name='joe'">
>>> q.query()
'SELECT * FROM test WHERE name=%s'
>>> q.values()
['joe']

method get_marker(self, paramstyle='pyformat')

method sqlquery(self)

class SQLLiteral(self, v)

Protects a string from sqlquote.

>>> sqlquote('NOW()')
<sql: "'NOW()'">
>>> sqlquote(SQLLiteral('NOW()'))
<sql: 'NOW()'>

class sqlliteral(self, v)

Protects a string from sqlquote.

>>> sqlquote('NOW()')
<sql: "'NOW()'">
>>> sqlquote(SQLLiteral('NOW()'))
<sql: 'NOW()'>

function database(dburl=None, **params)

Creates appropriate database using params.

Pooling will be enabled if DBUtils module is available. Pooling can be disabled by passing pooling=False in params.

class DB(self, db_module, keywords)

Database

property ctx

method delete(self, table, where, using=None, vars=None, _test=False)

Deletes from table with clauses where and using.

>>> db = DB(None, {})
>>> name = 'Joe'
>>> db.delete('foo', where='name = $name', vars=locals(), _test=True)
<sql: "DELETE FROM foo WHERE name = 'Joe'">

method gen_clause(self, sql, val, vars)

method insert(self, tablename, seqname=None, _test=False, **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.

>>> db = DB(None, {})
>>> q = db.insert('foo', name='bob', age=2, created=SQLLiteral('NOW()'), _test=True)
>>> q
<sql: "INSERT INTO foo (age, name, created) VALUES (2, 'bob', NOW())">
>>> q.query()
'INSERT INTO foo (age, name, created) VALUES (%s, %s, NOW())'
>>> q.values()
[2, 'bob']

method multiple_insert(self, tablename, values, seqname=None, _test=False)

Inserts multiple rows into tablename. The values must be a list of dictioanries, one for each row to be inserted, each with the same set of keys. Returns the list of ids of the inserted rows.
Set seqname to the ID if it's not the default, or to False if there isn't one.

>>> db = DB(None, {})
>>> db.supports_multiple_insert = True
>>> values = [{"name": "foo", "email": "foo@example.com"}, {"name": "bar", "email": "bar@example.com"}]
>>> db.multiple_insert('person', values=values, _test=True)
<sql: "INSERT INTO person (name, email) VALUES ('foo', 'foo@example.com'), ('bar', 'bar@example.com')">

method query(self, sql_query, vars=None, processed=False, _test=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.

>>> db = DB(None, {})
>>> db.query("SELECT * FROM foo", _test=True)
<sql: 'SELECT * FROM foo'>
>>> db.query("SELECT * FROM foo WHERE x = $x", vars=dict(x='f'), _test=True)
<sql: "SELECT * FROM foo WHERE x = 'f'">
>>> db.query("SELECT * FROM foo WHERE x = " + sqlquote('f'), _test=True)
<sql: "SELECT * FROM foo WHERE x = 'f'">

method select(self, tables, vars=None, what='*', where=None, order=None, group=None, limit=None, offset=None, _test=False)

Selects what from tables with clauses where, order, group, limit, and offset. Uses vars to interpolate. Otherwise, each clause can be a SQLQuery.

>>> db = DB(None, {})
>>> db.select('foo', _test=True)
<sql: 'SELECT * FROM foo'>
>>> db.select(['foo', 'bar'], where="foo.bar_id = bar.id", limit=5, _test=True)
<sql: 'SELECT * FROM foo, bar WHERE foo.bar_id = bar.id LIMIT 5'>

method sql_clauses(self, what, tables, where, group, order, limit, offset)

method transaction(self)

Start a transaction.

method update(self, tables, where, vars=None, _test=False, **values)

Update tables with clause where (interpolated using vars) and setting values.

>>> db = DB(None, {})
>>> name = 'Joseph'
>>> q = db.update('foo', where='name = $name', name='bob', age=2,
...     created=SQLLiteral('NOW()'), vars=locals(), _test=True)
>>> q
<sql: "UPDATE foo SET age = 2, name = 'bob', created = NOW() WHERE name = 'Joseph'">
>>> q.query()
'UPDATE foo SET age = %s, name = %s, created = NOW() WHERE name = %s'
>>> q.values()
[2, 'bob', 'Joseph']

method where(self, table, what='*', order=None, group=None, limit=None, offset=None, _test=False, **kwargs)

Selects from table where keys are equal to values in kwargs.

>>> db = DB(None, {})
>>> db.where('foo', bar_id=3, _test=True)
<sql: 'SELECT * FROM foo WHERE bar_id = 3'>
>>> db.where('foo', source=2, crust='dewey', _test=True)
<sql: "SELECT * FROM foo WHERE source = 2 AND crust = 'dewey'">
>>> db.where('foo', _test=True)
<sql: 'SELECT * FROM foo'>

module web.debugerror

pretty debug errors (part of web.py)

portions adapted from Django Copyright (c) 2005, the Lawrence Journal-World Used under the modified BSD license: http://www.xfree86.org/3.3.6/COPYRIGHT2.html#5

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

function djangoerror()

function emailerrors(to_address, olderror, from_address=None)

Wraps the old internalerror handler (pass as olderror) to additionally email all errors to to_address, to aid in debugging production websites.

Emails contain a normal text traceback as well as an attachment containing the nice debugerror page.

module web.form

HTML forms (part of web.py)

type AttributeList

List of atributes of input.

a = AttributeList(type='text', name='x', value=20) a

method copy(self)

type Button(self, name, *validators, **attrs)

HTML Button.

Button("save").render() '' Button("action", value="save", html="Save Changes").render() ''

method addatts(self)

method get_default_id(self)

method get_type(self)

method get_value(self)

method is_hidden(self)

method render(self)

method rendernote(self, note)

method set_value(self, value)

method validate(self, value)

type Checkbox(self, name, *validators, **attrs)

Checkbox input.

Checkbox('foo', value='bar', checked=True).render() '' Checkbox('foo', value='bar').render() '' c = Checkbox('foo', value='bar') c.validate('on') True c.render() ''

method addatts(self)

method get_default_id(self)

method get_type(self)

method get_value(self)

method is_hidden(self)

method render(self)

method rendernote(self, note)

method set_value(self, value)

method validate(self, value)

type Dropdown(self, name, args, *validators, **attrs)

Dropdown/select input.

Dropdown(name='foo', args=['a', 'b', 'c'], value='b').render() '\n' Dropdown(name='foo', args=[('a', 'aa'), ('b', 'bb'), ('c', 'cc')], value='b').render() '\n'

method addatts(self)

method get_default_id(self)

method get_type(self)

method get_value(self)

method is_hidden(self)

method render(self)

method rendernote(self, note)

method set_value(self, value)

method validate(self, value)

type File(self, name, *validators, **attrs)

File input.

File(name='f').render() ''

method addatts(self)

method get_default_id(self)

method get_type(self)

method get_value(self)

method is_hidden(self)

method render(self)

method rendernote(self, note)

method set_value(self, value)

method validate(self, value)

type Form(self, *inputs, **kw)

HTML form.

>>> f = Form(Textbox("x"))
>>> f.render()
'<table>\n    <tr><th><label for="x">x</label></th><td><input type="text" id="x" name="x"/></td></tr>\n</table>'

method fill(self, source=None, **kw)

method get(self, i, default=None)

method render(self)

method render_css(self)

method rendernote(self, note)

method validates(self, source=None, _validate=True, **kw)

type Hidden(self, name, *validators, **attrs)

Hidden Input.

Hidden(name='foo', value='bar').render() ''

method addatts(self)

method get_default_id(self)

method get_type(self)

method get_value(self)

method is_hidden(self)

method render(self)

method rendernote(self, note)

method set_value(self, value)

method validate(self, value)

type Input(self, name, *validators, **attrs)

method addatts(self)

method get_default_id(self)

method get_type(self)

method get_value(self)

method is_hidden(self)

method render(self)

method rendernote(self, note)

method set_value(self, value)

method validate(self, value)

type Password(self, name, *validators, **attrs)

Password input.

Password(name='password', value='secret').render() ''

method addatts(self)

method get_default_id(self)

method get_type(self)

method get_value(self)

method is_hidden(self)

method render(self)

method rendernote(self, note)

method set_value(self, value)

method validate(self, value)

type Radio(self, name, args, *validators, **attrs)

method addatts(self)

method get_default_id(self)

method get_type(self)

method get_value(self)

method is_hidden(self)

method render(self)

method rendernote(self, note)

method set_value(self, value)

method validate(self, value)

type Textarea(self, name, *validators, **attrs)

Textarea input.

Textarea(name='foo', value='bar').render() ''

method addatts(self)

method get_default_id(self)

method get_type(self)

method get_value(self)

method is_hidden(self)

method render(self)

method rendernote(self, note)

method set_value(self, value)

method validate(self, value)

type Textbox(self, name, *validators, **attrs)

Textbox input.

Textbox(name='foo', value='bar').render() '' Textbox(name='foo', value=0).render() ''

method addatts(self)

method get_default_id(self)

method get_type(self)

method get_value(self)

method is_hidden(self)

method render(self)

method rendernote(self, note)

method set_value(self, value)

method validate(self, value)

class Validator(self, msg, test, jstest=None)

method valid(self, value)

function attrget(obj, attr, value=None)

class regexp(self, rexp, msg)

method valid(self, value)

module web.http

HTTP Utilities (from web.py)

function expires(delta)

Outputs an Expires header for delta from now. delta is a timedelta object or a number of seconds.

function lastmodified(date_obj)

Outputs a Last-Modified header for datetime.

function prefixurl(base='')

Sorry, this function is really difficult to explain. Maybe some other time.

function modified(date=None, etag=None)

Checks to see if the page has been modified since the version in the requester's cache.

When you publish pages, you can include Last-Modified and ETag with the date the page was last modified and an opaque token for the particular version, respectively. When readers reload the page, the browser sends along the modification date and etag value for the version it has in its cache. If the page hasn't changed, the server can just return 304 Not Modified and not have to send the whole page again.

This function takes the last-modified date date and the ETag etag and checks the headers to see if they match. If they do, it returns True, or otherwise it raises NotModified error. It also sets Last-Modified and ETag output headers.

function changequery(query=None, **kw)

Imagine you're at /foo?a=1&b=2. Then changequery(a=3) will return /foo?a=3&b=2 -- the same URL but with the arguments you requested changed.

function url(path=None, doseq=False, **kw)

Makes url by concatinating web.ctx.homepath and path and the query string created using the arguments.

function profiler(app)

Outputs basic profiling information at the bottom of each response.

module web.httpserver

function runsimple(func, server_address=('0.0.0.0', 8080))

Runs CherryPy WSGI server hosting WSGI app func. The directory static/ is hosted statically.

module web.net

Network Utilities (from web.py)

function validipaddr(address)

Returns True if address is a valid IPv4 address.

>>> validipaddr('192.168.1.1')
True
>>> validipaddr('192.168.1.800')
False
>>> validipaddr('192.168.1')
False

function validipport(port)

Returns True if port is a valid IPv4 port.

>>> validipport('9000')
True
>>> validipport('foo')
False
>>> validipport('1000000')
False

function validip(ip, defaultaddr='0.0.0.0', defaultport=8080)

Returns (ip_address, port) from string ip_addr_port

function validaddr(string_)

Returns either (ipaddress, port) or "/path/to/socket" from string

>>> validaddr('/path/to/socket')
'/path/to/socket'
>>> validaddr('8000')
('0.0.0.0', 8000)
>>> validaddr('127.0.0.1')
('127.0.0.1', 8080)
>>> validaddr('127.0.0.1:8000')
('127.0.0.1', 8000)
>>> validaddr('fff')
Traceback (most recent call last):
    ...
ValueError: fff is not a valid IP address/port

function urlquote(val)

Quotes a string for use in a URL.

>>> urlquote('://?f=1&j=1')
'%3A//%3Ff%3D1%26j%3D1'
>>> urlquote(None)
''
>>> urlquote(u'\u203d')
'%E2%80%BD'

function httpdate(date_obj)

Formats a datetime object for use in HTTP headers.

>>> import datetime
>>> httpdate(datetime.datetime(1970, 1, 1, 1, 1, 1))
'Thu, 01 Jan 1970 01:01:01 GMT'

function parsehttpdate(string_)

Parses an HTTP date into a datetime object.

>>> parsehttpdate('Thu, 01 Jan 1970 01:01:01 GMT')
datetime.datetime(1970, 1, 1, 1, 1, 1)

function htmlquote(text)

Encodes text for raw use in HTML.

>>> htmlquote(u"<'&\">")
u'&lt;&#39;&amp;&quot;&gt;'

function htmlunquote(text)

Decodes text that's HTML quoted.

>>> htmlunquote(u'&lt;&#39;&amp;&quot;&gt;')
u'<\'&">'

function websafe(val)

Converts val so that it is safe for use in Unicode HTML.

websafe("<'&\">") u'<'&">' websafe(None) u'' websafe(u'\u203d') u'\u203d' websafe('\xe2\x80\xbd') u'\u203d'

module web.session

Session Management (from web.py)

type Session(self, app, store, initializer=None)

Session management for web.py

method expired(self)

Called when an expired session is atime

method kill(self)

Kill the session, make it no longer available

type SessionExpired(self, message)

class Store(self)

Base class for session stores

method cleanup(self, timeout)

removes all the expired sessions

method decode(self, session_data)

decodes the data to get back the session dict

method encode(self, session_dict)

encodes session dict as a string

class DiskStore(self, root)

Store for saving a session on disk.

>>> import tempfile
>>> root = tempfile.mkdtemp()
>>> s = DiskStore(root)
>>> s['a'] = 'foo'
>>> s['a']
'foo'
>>> time.sleep(0.01)
>>> s.cleanup(0.01)
>>> s['a']
Traceback (most recent call last):
    ...
KeyError: 'a'

method cleanup(self, timeout)

method decode(self, session_data)

decodes the data to get back the session dict

method encode(self, session_dict)

encodes session dict as a string

class DBStore(self, db, table_name)

Store for saving a session in database Needs a table with the following columns:

session_id CHAR(128) UNIQUE NOT NULL,
atime DATETIME NOT NULL default current_timestamp,
data TEXT

method cleanup(self, timeout)

method decode(self, session_data)

decodes the data to get back the session dict

method encode(self, session_dict)

encodes session dict as a string

module web.template

simple, elegant templating (part of web.py)

Template design:

Template string is split into tokens and the tokens are combined into nodes. Parse tree is a nodelist. TextNode and ExpressionNode are simple nodes and for-loop, if-loop etc are block nodes, which contain multiple child nodes.

Each node can emit some python string. python string emitted by the root node is validated for safeeval and executed using python in the given environment.

Enough care is taken to make sure the generated code and the template has line to line match, so that the error messages can point to exact line number in template. (It doesn't work in some cases still.)

Grammar:

template -> defwith sections 
defwith -> '$def with (' arguments ')' | ''
sections -> section*
section -> block | assignment | line

assignment -> '$ ' <assignment expression>
line -> (text|expr)*
text -> <any characters other than $>
expr -> '$' pyexpr | '$(' pyexpr ')' | '${' pyexpr '}'
pyexpr -> <python expression>

class Template(self, text, filename='