Gluon Package

This page contains the Gluon Package documentation.

The validators Module

This file is part of web2py Web Framework (Copyrighted, 2007-2009). Developed by Massimo Di Pierro <mdipierro@cs.depaul.edu>. License: GPL v2

Thanks to ga2arch for help with IS_IN_DB and IS_NOT_IN_DB on GAE

class gluon.validators.IS_ALPHANUMERIC(error_message='must be alphanumeric!')

Bases: gluon.validators.IS_MATCH

example:

INPUT(_type='text', _name='name', requires=IS_ALPHANUMERIC())
class gluon.validators.IS_DATE(format='%Y-%m-%d', error_message='must be YYYY-MM-DD!')

Bases: gluon.validators.Validator

example:

INPUT(_type='text', _name='name', requires=IS_DATE())

date has to be in the ISO8960 format YYYY-MM-DD

formatter(value)
class gluon.validators.IS_DATETIME(format='%Y-%m-%d %H:%M:%S', error_message='must be YYYY-MM-DD HH:MM:SS!')

Bases: gluon.validators.Validator

example:

INPUT(_type='text', _name='name', requires=IS_DATETIME())

datetime has to be in the ISO8960 format YYYY-MM-DD hh:mm:ss

formatter(value)
class gluon.validators.IS_EMAIL(banned=None, forced=None, error_message='invalid email!')

Bases: gluon.validators.Validator

Checks if field’s value is a valid email address. Can be set to disallow or force addresses from certain domain(s).

Email regex taken from http://regexlib.com/REDetails.aspx?regexp_id=541

Arguments:

banned: regex text for disallowed address domains forced: regex text for required address domains

Both arguments can also be custom objects with a match(value) method.

Examples:

Check for valid email address: INPUT(_type=’text’, _name=’name’, requires=IS_EMAIL())

Check for valid email address that can’t be from a .com domain: INPUT(_type=’text’, _name=’name’, requires=IS_EMAIL(banned=’^.*.com(|..*)$’))

System Message: WARNING/2 (/Users/mdipierro/web2py/gluon/validators.py:docstring of gluon.validators.IS_EMAIL, line 20); backlink

Inline substitution_reference start-string without end-string.

Check for valid email address that must be from a .edu domain: INPUT(_type=’text’, _name=’name’, requires=IS_EMAIL(forced=’^.*.edu(|..*)$’))

System Message: WARNING/2 (/Users/mdipierro/web2py/gluon/validators.py:docstring of gluon.validators.IS_EMAIL, line 23); backlink

Inline substitution_reference start-string without end-string.
class gluon.validators.IS_EXPR(expression, error_message='invalid expression!')

Bases: gluon.validators.Validator

example:

INPUT(_type='text', _name='name',
    requires=IS_EXPR('5 < int(value) < 10'))

the argument of IS_EXPR must be python condition:

>>> IS_EXPR('int(value) < 2')('1')
('1', None)

>>> IS_EXPR('int(value) < 2')('2')
('2', 'invalid expression!')
class gluon.validators.IS_UPLOAD_FILENAME(filename=None, extension=None, lastdot=True, case=1, error_message='invalid filename or extension!')

Bases: gluon.validators.Validator

Checks if name and extension of file uploaded through file input matches given criteria.

Does not ensure the file type in any way. Returns validation failure if no data was uploaded.

Arguments:

System Message: WARNING/2 (/Users/mdipierro/web2py/gluon/validators.py:docstring of gluon.validators.IS_UPLOAD_FILENAME, line 11)

Literal block expected; none found.

filename: filename (before dot) regex extension: extension (after dot) regex lastdot: which dot should be used as a filename / extension separator:

System Message: ERROR/3 (<autodoc>, line 0)

Unexpected indentation.
True means last dot, eg. file.png -> file / png False means first dot, eg. file.tar.gz -> file / tar.gz

System Message: WARNING/2 (/Users/mdipierro/web2py/gluon/validators.py:docstring of gluon.validators.IS_UPLOAD_FILENAME, line 16)

Block quote ends without a blank line; unexpected unindent.
case: 0 - keep the case, 1 - transform the string into lowercase (default),
2 - transform the string into uppercase

If there is no dot present, extension checks will be done against empty string and filename checks against whole value.

Examples:

#Check if file has a pdf extension (case insensitive):
INPUT(_type='file', _name='name', requires=IS_UPLOAD_FILENAME(extension='pdf'))

#Check if file has a tar.gz extension and name starting with backup:
INPUT(_type='file', _name='name', requires=IS_UPLOAD_FILENAME(filename='backup.*', extension='tar.gz', lastdot=False))

#Check if file has no extension and name matching README (case sensitive):
INPUT(_type='file', _name='name', requires=IS_UPLOAD_FILENAME(filename='^README$', extension='^$', case=0))
class gluon.validators.IS_FLOAT_IN_RANGE(minimum, maximum, error_message='too small or too large!')

Bases: gluon.validators.Validator

example:

INPUT(_type='text', _name='name', requires=IS_FLOAT_IN_RANGE(0, 10))
class gluon.validators.IS_IMAGE(extensions=('bmp', 'gif', 'jpeg', 'png'), maxsize=(10000, 10000), minsize=(0, 0), error_message='invalid image!')

Bases: gluon.validators.Validator

Checks if file uploaded through file input was saved in one of selected image formats and has dimensions (width and height) within given boundaries.

Does not check for maximum file size (use IS_LENGTH for that). Returns validation failure if no data was uploaded.

Supported file formats: BMP, GIF, JPEG, PNG.

Code parts taken from http://mail.python.org/pipermail/python-list/2007-June/617126.html

Arguments:

extensions: iterable containing allowed lowercase image file extensions (‘jpg’ extension of uploaded file counts as ‘jpeg’) maxsize: iterable containing maximum width and height of the image minsize: iterable containing minimum width and height of the image

Use (-1, -1) as minsize to pass image size check.

Examples:

#Check if uploaded file is in any of supported image formats:
INPUT(_type='file', _name='name', requires=IS_IMAGE())

#Check if uploaded file is either JPEG or PNG:
INPUT(_type='file', _name='name', requires=IS_IMAGE(extensions=('jpeg', 'png')))

#Check if uploade file is PNG with maximum size of 200x200 pixels:
INPUT(_type='file', _name='name', requires=IS_IMAGE(extensions=('png'), maxsize=(200, 200)))
class gluon.validators.IS_INT_IN_RANGE(minimum, maximum, error_message='too small or too large!')

Bases: gluon.validators.Validator

example:

INPUT(_type='text', _name='name', requires=IS_INT_IN_RANGE(0, 10))
class gluon.validators.IS_IN_SET(theset, labels=None, error_message='value not allowed!', multiple=False)

Bases: gluon.validators.Validator

example:

INPUT(_type='text', _name='name', requires=IS_IN_SET(['max', 'john']))

the argument of IS_IN_SET must be a list or set

options()
class gluon.validators.IS_IPV4(minip='0.0.0.0', maxip='255.255.255.255', error_message='invalid IPv4 address!')

Bases: gluon.validators.Validator

Checks if field’s value is an IP version 4 address in decimal form. Can be set to force adresses from certain range.

IPv4 regex taken from: http://regexlib.com/REDetails.aspx?regexp_id=1411

Arguments:

minip: lowest allowed address; accepts:
str, eg. 192.168.0.1 iterable of numbers, eg. [192, 168, 0, 1] int, eg. 3232235521

System Message: WARNING/2 (/Users/mdipierro/web2py/gluon/validators.py:docstring of gluon.validators.IS_IPV4, line 14)

Definition list ends without a blank line; unexpected unindent.

maxip: highest allowed address; same as above

All three example values are equal, since addresses are converted to integers for inclusion check with following function:

number = 16777216 * IP[0] + 65536 * IP[1] + 256 * IP[2] + IP[3]

Examples:

#Check for valid IPv4 address:
INPUT(_type='text',_name='name',requires=IS_IPV4())

#Check for valid private network IPv4 address:
INPUT(_type='text',_name='name',requires=IS_IPV4(minip='192.168.0.1', maxip='192.168.255.255'))
class gluon.validators.IS_LENGTH(maxsize=255, minsize=0, error_message='invalid length!')

Bases: gluon.validators.Validator

Checks if length of field’s value fits between given boundaries. Works for both text and file inputs.

Arguments:

maxsize: maximum allowed length / size minsize: minimum allowed length / size

Examples:

#Check if text string is shorter than 33 characters:
INPUT(_type='text', _name='name', requires=IS_LENGTH(32))

#Check if password string is longer than 5 characters:
INPUT(_type='password', _name='name', requires=IS_LENGTH(minsize=6))

#Check if uploaded file has size between 1KB and 1MB:
INPUT(_type='file', _name='name', requires=IS_LENGTH(1048576, 1024))
class gluon.validators.IS_LIST_OF(other)
Bases: gluon.validators.Validator
class gluon.validators.IS_LOWER
Bases: gluon.validators.Validator
class gluon.validators.IS_MATCH(expression, error_message='invalid expression!')

Bases: gluon.validators.Validator

example:

INPUT(_type='text', _name='name', requires=IS_MATCH('.+'))

the argument of IS_MATCH is a regular expression:

>>> IS_MATCH('.+')('hello')
('hello', None)

>>> IS_MATCH('.+')('')
('', 'invalid expression!')
class gluon.validators.IS_NOT_EMPTY(error_message='cannot be empty!')

Bases: gluon.validators.Validator

example:

INPUT(_type='text', _name='name', requires=IS_NOT_EMPTY())
class gluon.validators.IS_TIME(error_message='must be HH:MM:SS!')

Bases: gluon.validators.Validator

example:

INPUT(_type='text', _name='name', requires=IS_TIME())

understands the follwing formats hh:mm:ss [am/pm] hh:mm [am/pm] hh [am/pm]

[am/pm] is options, ‘:’ can be replaced by any other non-digit

class gluon.validators.IS_URL(error_message='invalid url!', mode='http', allowed_schemes=None, prepend_scheme='http')

Bases: gluon.validators.Validator

Rejects a URL string if any of the following is true:
  • The string is empty or None
  • The string uses characters that are not allowed in a URL
  • The string breaks any of the HTTP syntactic rules
  • The URL scheme specified (if one is specified) is not ‘http’ or ‘https’
  • The top-level domain (if a host name is specified) does not exist

(These rules are based on RFC 2616: http://www.faqs.org/rfcs/rfc2616.html)

This function only checks the URL’s syntax. It does not check that the URL points to a real document, for example, or that it otherwise makes sense semantically. This function does automatically prepend ‘http://‘ in front of a URL in the case of an abbreviated URL (e.g. ‘google.ca’).

If the parameter mode=’generic’ is used, then this function’s behaviour changes. It then rejects a URL string if any of the following is true:

System Message: ERROR/3 (/Users/mdipierro/web2py/gluon/validators.py:docstring of gluon.validators.IS_ALPHANUMERIC, line 3)

Unexpected indentation.
  • The string is empty or None
  • The string uses characters that are not allowed in a URL
  • The URL scheme specified (if one is specified) is not valid

(These rules are based on RFC 2396: http://www.faqs.org/rfcs/rfc2396.html)

The list of allowed schemes is customizable with the allowed_schemes parameter. If you exclude None from the list, then abbreviated URLs (lacking a scheme such as ‘http’) will be rejected.

The default prepended scheme is customizable with the prepend_scheme parameter. If you set prepend_scheme to None then prepending will be disabled. URLs that require prepending to parse will still be accepted, but the return value will not be modified.

IS_URL is compatible with the Internationalized Domain Name (IDN) standard specified in RFC 3490 (http://tools.ietf.org/html/rfc3490). As a result, URLs can be regular strings or unicode strings. If the URL’s domain component (e.g. google.ca) contains non-US-ASCII letters, then the domain will be converted into Punycode (defined in RFC 3492, http://tools.ietf.org/html/rfc3492). IS_URL goes a bit beyond the standards, and allows non-US-ASCII characters to be present in the path and query components of the URL as well. These non-US-ASCII characters will be escaped using the standard ‘%20’ type syntax. e.g. the unicode character with hex code 0x4e86 will become ‘%4e%86’

Code Examples:

INPUT(_type='text', _name='name', requires=IS_URL())
INPUT(_type='text', _name='name', requires=IS_URL(mode='generic'))
INPUT(_type='text', _name='name',
    requires=IS_URL(allowed_schemes=['https']))
INPUT(_type='text', _name='name',
    requires=IS_URL(prepend_scheme='https'))
INPUT(_type='text', _name='name',
    requires=IS_URL(mode='generic', allowed_schemes=['ftps', 'https'],
        prepend_scheme='https'))

@author: Jonathan Benn

class gluon.validators.CLEANUP

Bases: gluon.validators.Validator

example:

INPUT(_type='text', _name='name', requires=CLEANUP())

removes special characters on validation

class gluon.validators.CRYPT(key=None, digest_alg='md5')

Bases: object

example:

INPUT(_type='text', _name='name', requires=CRYPT())

encodes the value on validation with a digest

class gluon.validators.IS_IN_DB(dbset, field, label=None, error_message='value not in database!', orderby=None, cache=None, multiple=False)

Bases: gluon.validators.Validator

example:

INPUT(_type='text', _name='name', requires=IS_IN_DB(db, db.table))

used for reference fields, rendered as a dropbox

build_set()
options()
class gluon.validators.IS_NOT_IN_DB(dbset, field, error_message='value already in database!', allowed_override=[])

Bases: gluon.validators.Validator

example:

INPUT(_type='text', _name='name', requires=IS_NOT_IN_DB(db, db.table))

makes the field unique

set_self_id(id)
class gluon.validators.IS_UPPER
Bases: gluon.validators.Validator
class gluon.validators.IS_NULL_OR(other, null=None)

Bases: gluon.validators.Validator

formatter(value)
set_self_id(id)
class gluon.validators.IS_STRONG(min=8, max=20, upper=1, lower=1, number=1, special=1, specials='~!@#$%^&*()_+-=?<>, .:;{}[], |', invalid=' "', error_message=None)

Bases: object

example:

INPUT(_type='password', _name='passwd',
    requires=IS_STRONG(min=10, special=2, upper=2))

enforces complexity requirements on a field

The sql Module

This file is part of web2py Web Framework (Copyrighted, 2007-2009). Developed by Massimo Di Pierro <mdipierro@cs.depaul.edu>. License: GPL v2

Thanks to

This file contains the DAL support for many relational databases, like SQLite, MySQL, Postgres, Oracle, MS-Sql, DB2, Interbase.

class gluon.sql.SQLDB(uri='sqlite://dummy.db', pool_size=0, pools=0)

Bases: gluon.sql.SQLStorage

an instance of this class represents a database connection

Example:

db=SQLDB('sqlite://test.db')
db.define_table('tablename', SQLField('fieldname1'),
                            SQLField('fieldname2'))
Field
alias of SQLField
Table
alias of SQLTable
static close_all_instances(action)
to close cleanly databases in a multithreaded environment
commit()
define_table(tablename, *fields, **args)
static distributed_transaction_commit(*instances)
executesql(query)
export_to_csv_file(ofile)
import_from_csv_file(ifile, id_map={})
rollback()
class gluon.sql.SQLField(fieldname, type='string', length=None, default=None, required=False, requires=<function sqlhtml_validators at 0x2084270>, ondelete='CASCADE', notnull=False, unique=False, uploadfield=True, widget=None, label=None, comment=None, writable=True, readable=True, update=None, authorize=None, autodelete=False, represent=None)

Bases: gluon.sql.SQLXorable

an instance of this class represents a database field

example:

a = SQLField(name, 'string', length=32, required=False, default=None, 
    requires=IS_NOT_EMPTY(), notnull=False, unique=False,
    uploadfield=True, widget=None, label=None, comment=None,
    writable=True, readable=True, update=None, authorize=None,
    autodelete=False, represent=None)

to be used as argument of SQLDB.define_table

allowed field types: string, boolean, integer, double, text, blob, date, time, datetime, upload, password

strings must have a length or 32 by default. fields should have a default or they will be required in SQLFORMs the requires argument is used to validate the field input in SQLFORMs

count()
day()
formatter(value)
hour()
lower()
max()
min()
minutes()
month()
seconds()
sum()
upper()
validate(value)
year()

The xmlrpc Module

This file is part of web2py Web Framework (Copyrighted, 2007-2009). Developed by Massimo Di Pierro <mdipierro@cs.depaul.edu>. License: GPL v2

gluon.xmlrpc.handler(request, response, methods)

The shell Module

This file is part of web2py Web Framework (Copyrighted, 2007-2009). Developed by Massimo Di Pierro <mdipierro@cs.depaul.edu>, limodou <limodou@gmail.com> and srackham <srackham@gmail.com>. License: GPL v2

gluon.shell.die(msg)
gluon.shell.env(a, import_models=False, c=None, f=None, dir='')
Return web2py execution environment for application (a), controller (c), function (f). If import_models is True the exec all application models into the environment.
gluon.shell.exec_environment(pyfile='', request=<Storage {'function': None, 'cookies': <Storage {}>, 'extension': None, 'vars': <Storage {}>, 'args':[], 'application': None, 'env': <Storage {}>, 'get_vars': <Storage {}>, 'folder': None, 'now': datetime.datetime(2009, 6, 30, 21, 6, 36, 555781), 'post_vars': <Storage {}>}>, response=<Storage {'status': 200, 'body': <cStringIO.StringO object at 0x30e9940>, 'cookies': <Storage {}>, '_view_environment': None, '_vars': None, 'description': '', 'menu': None, 'flash': None, 'session_id': None, 'headers': <Storage {}>, 'postprocessing':[], '_caller': <function <lambda> at 0x30ffbf0>, 'keywords': '', '_custom_commit': None, '_custom_rollback': None}>, session=<Storage {}>)
gluon.shell.exec_environment([pyfile=''[, request=Request()
[, response=Response[, sessions=Session()]]]])

Environment builder and module loader.

Builds a web2py environment and optionally executes a Python file into the environment. A Storage dictionary containing the resulting environment is returned. The working directory must be web2py root – this is the web2py default.

gluon.shell.exec_pythonrc()
gluon.shell.execute_from_command_line(argv=None)
gluon.shell.get_usage()
gluon.shell.parse_path_info(path_info)
Parse path info formatted like a/c/f where c and f are optional and a leading / accepted. Return tuple (a,c,f). If invalid path_info a is set to None. If c or f are omitted they are set to None.
gluon.shell.run(appname, plain=False, import_models=False, startfile=None)

Start interactive shell or run Python script (startfile) in web2py controller environment. appname is formatted like:

a web2py application name a/c exec the controller c into the application environment

gluon.shell.test(testpath, import_models=True, verbose=False)

Run doctests in web2py environment. testpath is formatted like:

a tests all controllers in application a a/c tests controller c in application a a/c/f test function f in controller c, application a

Where a, c and f are application, controller and function names respectively. If the testpath is a file name the file is tested. If a controller is specified models are executed by default.

The utils Module

This file is part of web2py Web Framework (Copyrighted, 2007-2009). Developed by Massimo Di Pierro <mdipierro@cs.depaul.edu>. License: GPL v2

gluon.utils.hash(text, digest_alg='md5')
Generates hash with the given text using the specified digest hashing algorithm
gluon.utils.md5_hash(text)
Generate a md5 hash with the given text

The globals Module

This file is part of web2py Web Framework (Copyrighted, 2007-2009). Developed by Massimo Di Pierro <mdipierro@cs.depaul.edu>. License: GPL v2

Contains the classes for the global used variables:

  • Request
  • Response
  • Session
class gluon.globals.Request

Bases: gluon.storage.Storage

defines the request object and the default values of its members

  • env: environment variables, by gluon.main.wsgibase()
  • cookies
  • get_vars
  • post_vars
  • vars
  • folder
  • application
  • function
  • args
  • extension
  • now: datetime.datetime.today()
class gluon.globals.Response

Bases: gluon.storage.Storage

defines the response object and the default values of its members response.write( ) can be used to write in the output html

download(request, db, chunk_size=1000000)

example of usage in controller:

def download(): 
    return response.download(request, db)

downloads from http://..../download/filename

json(data)
render(*a, **b)
stream(stream, chunk_size=1000000, request=None)

if a controller function:

return response.stream(file, 100)

the file content will be streamed at 100 bytes at the time

write(data, escape=True)
xmlrpc(request, methods)

assuming:

def add(a, b):
    return a+b

if a controller function “func”:

return response.xmlrpc(request, [add])

the controller will be able to handle xmlrpc requests for the add function. Example:

import xmlrpclib
connection = xmlrpclib.ServerProxy('http://hostname/app/contr/func')
print connection.add(3, 4)
class gluon.globals.Session

Bases: gluon.storage.Storage

defines the session object and the default values of its members (None)

connect(request, response, db=None, tablename='web2py_session', masterapp=None, migrate=True)
forget(response=None)
secure()

The compileapp Module

This file is part of web2py Web Framework (Copyrighted, 2007-2009). Developed by Massimo Di Pierro <mdipierro@cs.depaul.edu>. License: GPL v2

Functions required to execute app components

FOR INTERNAL USE ONLY

gluon.compileapp.build_environment(request, response, session)
Build the environment dictionary into which web2py files are executed.
gluon.compileapp.compile_application(folder)
Compiles all models, views, controller for the application in folder.
gluon.compileapp.compile_controllers(folder)
Compiles all the controllers in the application specified by folder
gluon.compileapp.compile_models(folder)
Compiles all the models in the application specified by folder
gluon.compileapp.compile_views(folder)
Compiles all the views in the application specified by folder
gluon.compileapp.getcfs(key, filename, filter=None)

Caches the filtered file filename with key until the file is modifiled. filter is the function used for filtering. Normally filename is a .py file and filter is a function that bytecode compiles the file. In this way the bytecode compiled file is cached.

This is used on Google App Engine since pyc files cannot be saved.

gluon.compileapp.read_pyc(filename)
Read the code inside a bytecode compiled file if the MAGIC number is compatible Returns a code object
gluon.compileapp.remove_compiled_application(folder)
Deletes the folder compiled containing the compiled application.
gluon.compileapp.run_controller_in(controller, function, environment)
Runs the controller.function() (for the app specified by the current folder). It tries pre-compiled controller_function.pyc first before compiling it.
gluon.compileapp.run_models_in(environment)
Runs all models (in the app specified by the current folder) It tries pre-compiled models first before compiling them.
gluon.compileapp.run_view_in(environment)
Executes the view for the requested action. The view is the one specified in response.view or deterined by the url or view/generic.extension It tries the pre-compiled views_controller_function.pyc before comiling it.
gluon.compileapp.save_pyc(filename)
Bytecode compiles the file filename
gluon.compileapp.test()

Example:

>>> import traceback, types
>>> environment={'x':1}
>>> open('a.py','w').write('print 1/x')
>>> save_pyc('a.py')
>>> os.unlink('a.py')
>>> if type(read_pyc('a.pyc'))==types.CodeType: print 'code'
code
>>> exec read_pyc('a.pyc') in environment
1

The wsgiserver Module

High-speed, production ready, thread pooled, generic WSGI server.

Simplest example on how to use this module directly (without using CherryPy’s application machinery):

from cherrypy import wsgiserver

def my_crazy_app(environ, start_response):
    status = '200 OK'
    response_headers = [('Content-type','text/plain')]
    start_response(status, response_headers)
    return ['Hello world!']

server = wsgiserver.CherryPyWSGIServer(
            ('0.0.0.0', 8070), my_crazy_app,
            server_name='www.cherrypy.example')

The CherryPy WSGI server can serve as many WSGI applications as you want in one instance by using a WSGIPathInfoDispatcher:

d = WSGIPathInfoDispatcher({'/': my_crazy_app, '/blog': my_blog_app})
server = wsgiserver.CherryPyWSGIServer(('0.0.0.0', 80), d)

Want SSL support? Just set these attributes:

server.ssl_certificate = <filename>
server.ssl_private_key = <filename>

if __name__ == '__main__':
    try:
        server.start()
    except KeyboardInterrupt:
        server.stop()

This won’t call the CherryPy engine (application side) at all, only the WSGI server, which is independent from the rest of CherryPy. Don’t let the name “CherryPyWSGIServer” throw you; the name merely reflects its origin, not its coupling.

class gluon.wsgiserver.CherryPyWSGIServer(bind_addr, wsgi_app, numthreads=10, server_name=None, max=-1, request_queue_size=5, timeout=10, shutdown_timeout=5)

Bases: object

An HTTP server for WSGI.

Parameters:
  • bind_addr – The interface on which to listen for connections. For TCP sockets, a (host, port) tuple. Host values may be any IPv4 or IPv6 address, or any valid hostname. The string ‘localhost’ is a synonym for ‘127.0.0.1’ (or ‘::1’, if your hosts file prefers IPv6). The string ‘0.0.0.0’ is a special IPv4 entry meaning “any active interface” (INADDR_ANY), and ‘::’ is the similar IN6ADDR_ANY for IPv6. The empty string or None are not allowed. For UNIX sockets, supply the filename as a string.
  • wsgi_app – the WSGI ‘application callable’; multiple WSGI applications may be passed as (path_prefix, app) pairs.
  • numthreads – the number of worker threads to create (default 10).
  • server_name – the string to set for WSGI’s SERVER_NAME environ entry. Defaults to socket.gethostname().
  • max – the maximum number of queued requests (defaults to -1 = no limit).
  • request_queue_size – the ‘backlog’ argument to socket.listen(); specifies the maximum number of queued connections (default 5).
  • timeout – the timeout in seconds for accepted connections (default 10).
  • protocol – the version string to write in the Status-Line of all HTTP responses. For example, “HTTP/1.1” (the default). This also limits the supported features used in the response.
ConnectionClass
alias of HTTPConnection
bind(family, type, proto=0)
Create (or recreate) the actual socket object.
bind_addr

The interface on which to listen for connections.

For TCP sockets, a (host, port) tuple. Host values may be any IPv4 or IPv6 address, or any valid hostname. The string ‘localhost’ is a synonym for ‘127.0.0.1’ (or ‘::1’, if your hosts file prefers IPv6). The string ‘0.0.0.0’ is a special IPv4 entry meaning “any active interface” (INADDR_ANY), and ‘::’ is the similar IN6ADDR_ANY for IPv6. The empty string or None are not allowed.

For UNIX sockets, supply the filename as a string.

interrupt
Set this to an Exception instance to interrupt the server.
numthreads
populate_ssl_environ()
Create WSGI environ entries to be merged into each request.
start()
Run the server forever.
stop()
Gracefully shutdown a server that is serving forever.
tick()
Accept a new connection and put it on the Queue.
class gluon.wsgiserver.HTTPConnection(sock, wsgi_app, environ)

Bases: object

An HTTP connection (active socket).

socket: the raw socket object (usually TCP) for this connection. wsgi_app: the WSGI application for this server/connection. environ: a WSGI environ template. This will be copied for each request.

rfile: a fileobject for reading from the socket. sendall: a function for writing (+ flush) to the socket.

RequestHandlerClass
alias of HTTPRequest
close()
Close the socket underlying this connection.
communicate()
Read each request and respond appropriately.
class gluon.wsgiserver.HTTPRequest(sendall, environ, wsgi_app)

Bases: object

An HTTP Request (and response).

A single HTTP connection may consist of multiple request/response pairs.

Parameters:
  • sendall – the ‘sendall’ method from the connection’s fileobject.
  • wsgi_app – the WSGI application to call.
  • environ

    a partial WSGI environ (server and connection entries). The caller MUST set the following entries:

    • All wsgi.* entries, including .input
    • SERVER_NAME and SERVER_PORT
    • Any SSL_* entries
    • Any custom entries like REMOTE_ADDR and REMOTE_PORT
    • SERVER_SOFTWARE: the value to write in the “Server” response header.
    • ACTUAL_SERVER_PROTOCOL: the value to write in the Status-Line of
      the response. From RFC 2145: “An HTTP server SHOULD send a response version equal to the highest version for which the server is at least conditionally compliant, and whose major version is less than or equal to the one received in the request. An HTTP server MUST NOT send a version for which it is not at least conditionally compliant.”
  • outheaders – a list of header tuples to write in the response.
  • ready – when True, the request has been parsed and is ready to begin generating the response. When False, signals the calling Connection that the response should not be generated and the connection should close.
  • close_connection – signals the calling Connection that the request should close. This does not imply an error! The client and/or server may each request that the connection be closed.
  • chunked_write – if True, output will be encoded with the “chunked” transfer-coding. This value is set automatically inside send_headers.
decode_chunked()
Decode the ‘chunked’ transfer coding.
parse_request()
Parse the next HTTP request start-line and message-headers.
read_headers()
Read header lines from the incoming stream.
respond()
Call the appropriate WSGI app and write its iterable output.
send_headers()
Assert, process, and send the HTTP response message-headers.
simple_response(status, msg='')
Write a simple response back to the client.
start_response(status, headers, exc_info=None)
WSGI callable to begin the HTTP response.
write(chunk)

WSGI callable to write unbuffered data to the client.

This method is also used internally by start_response (to write data from the iterable returned by the WSGI application).

exception gluon.wsgiserver.MaxSizeExceeded
Bases: exceptions.Exception
exception gluon.wsgiserver.NoSSLError

Bases: exceptions.Exception

Exception raised when a client speaks HTTP to an HTTPS socket.

class gluon.wsgiserver.SSLConnection(*args)

A thread-safe wrapper for an SSL.Connection.

Parameter:args – the arguments to create the wrapped SSL.Connection.
accept(*args)
bind(*args)
close(*args)
connect(*args)
connect_ex(*args)
fileno(*args)
get_app_data(*args)
get_cipher_list(*args)
get_context(*args)
get_peer_certificate(*args)
getpeername(*args)
getsockname(*args)
getsockopt(*args)
listen(*args)
makefile(*args)
pending(*args)
read(*args)
recv(*args)
renegotiate(*args)
send(*args)
sendall(*args)
set_accept_state(*args)
set_app_data(*args)
set_connect_state(*args)
setblocking(*args)
setsockopt(*args)
settimeout(*args)
shutdown(*args)
sock_shutdown(*args)
state_string(*args)
want_read(*args)
want_write(*args)
write(*args)
class gluon.wsgiserver.SSL_fileobject(sock, mode='rb', bufsize=-1, close=False)

Bases: socket._fileobject

Faux file object attached to a socket object.

close(*args, **kwargs)
flush(*args, **kwargs)
read(*args, **kwargs)
readline(*args, **kwargs)
readlines(*args, **kwargs)
write(*args, **kwargs)
writelines(*args, **kwargs)
class gluon.wsgiserver.SizeCheckWrapper(rfile, maxlen)

Bases: object

Wraps a file-like object, raising MaxSizeExceeded if too large.

close()
next()
read(size=None)
readline(size=None)
readlines(sizehint=0)
class gluon.wsgiserver.ThreadPool(server, min=10, max=-1)

Bases: object

A Request Queue for the CherryPyWSGIServer which pools threads.

grow(amount)
Spawn new worker threads (not above self.max).
idle
Number of worker threads which are idle. Read-only.
put(obj)
shrink(amount)
Kill off worker threads (not below self.min).
start()
Start the pool of threads.
stop(timeout=5)
class gluon.wsgiserver.WSGIPathInfoDispatcher(apps)

Bases: object

A WSGI dispatcher for dispatch based on the PATH_INFO.

apps: a dict or list of (path_prefix, app) pairs.

class gluon.wsgiserver.WorkerThread(server)

Bases: threading.Thread

Thread which continuously polls a Queue for Connection objects.

server: the HTTP Server which spawned this thread, and which owns the
Queue and is placing active connections into it.
ready: a simple flag for the calling server to know when this thread
has begun polling the Queue.

Due to the timing issues of polling a Queue, a WorkerThread does not check its own ‘ready’ flag after it has started. To stop the thread, it is necessary to stick a _SHUTDOWNREQUEST object onto the Queue (one for each running WorkerThread).

run()
gluon.wsgiserver.format_exc(limit=None)
Like print_exc() but return a string. Backport for Python 2.3.
gluon.wsgiserver.plat_specific_errors(*errnames)

Return error numbers for all errors in errnames on this platform.

The ‘errno’ module contains different global constants depending on the specific platform (OS). This function will return the list of numeric values for a given list of potential names.

The winservice Module

System Message: WARNING/2 (/Users/mdipierro/web2py/doc/source/gluon/gluon.rst, line 81)

autodoc can’t import/find module ‘gluon.winservice’, it reported error: “No module named win32serviceutil”, please check your spelling and sys.path

The template Module

This file is part of web2py Web Framework (Copyrighted, 2007-2009). Developed by Massimo Di Pierro <mdipierro@cs.depaul.edu>. License: GPL v2

gluon.template.parse(text)
gluon.template.reindent(text)
gluon.template.parse_template(filename, path='views/', cache='cache/', context={})
filename can be a view filename in the views/ folder or an imput stream path is the path of a views folder context is a dictionary of symbols used to render the template

The fileutils Module

This file is part of web2py Web Framework (Copyrighted, 2007-2009). Developed by Massimo Di Pierro <mdipierro@cs.depaul.edu>. License: GPL v2

gluon.fileutils.listdir(path, expression='^.+$', drop=True, add_dirs=False)
like os.listdir() but you can specify a regex patter to filter filed. if add_dirs==True the returned items will have the full path.
gluon.fileutils.cleanpath(path)
turns any expression/path into a valid filename. replaces / with _ and removes special characters.
gluon.fileutils.tar(file, dir, expression='^.+$')
tars dir into file, only tars file that match expression
gluon.fileutils.untar(file, dir)
untar file into dir
gluon.fileutils.tar_compiled(file, dir, expression='^.+$')
used to tar a compiled application. the content of models, views, controllers is not stored in the tar file.
gluon.fileutils.get_session(request, other_application='admin')
checks that user is authorized to access other_application
gluon.fileutils.check_credentials(request, other_application='admin')
checks that user is authorized to access other_application

The sqlhtml Module

This file is part of web2py Web Framework (Copyrighted, 2007-2009). Developed by Massimo Di Pierro <mdipierro@cs.depaul.edu>. License: GPL v2

Holds:

  • SQLFORM: provide a form for a table (with/without record)
  • SQLTABLE: provides a table for a set of records
  • form_factory: provides a SQLFORM for an non-db backed table
class gluon.sqlhtml.BooleanWidget

Bases: gluon.sqlhtml.FormWidget

static widget(field, value, **attributes)

generates an INPUT checkbox tag.

see also: FormWidget.widget()

class gluon.sqlhtml.CheckboxesWidget

Bases: gluon.sqlhtml.OptionsWidget

static widget(field, value, **attributes)

generates a TABLE tag, including INPUT checkboxes (multiple allowed)

see also: FormWidget.widget()

class gluon.sqlhtml.DateWidget
Bases: gluon.sqlhtml.StringWidget
class gluon.sqlhtml.DatetimeWidget
Bases: gluon.sqlhtml.StringWidget
class gluon.sqlhtml.DoubleWidget
Bases: gluon.sqlhtml.StringWidget
class gluon.sqlhtml.FormWidget

Bases: object

helper for SQLFORM to generate form input fields (widget), related to the fieldtype

static widget(field, value, **attributes)

generates the widget for the field.

When serialized, will provide an INPUT tag:

  • id = tablename_fieldname
  • class = field.type
  • name = fieldname
Parameters:
  • field – the field needing the widget
  • value – value
  • attributes – any other attributes to be applied
class gluon.sqlhtml.IntegerWidget
Bases: gluon.sqlhtml.StringWidget
class gluon.sqlhtml.MultipleOptionsWidget

Bases: gluon.sqlhtml.OptionsWidget

static widget(field, value, size=5, **attributes)

generates a SELECT tag, including OPTIONs (multiple options allowed)

see also: FormWidget.widget()

Parameter:size – optional param (default=5) to indicate how many rows must be shown
class gluon.sqlhtml.OptionsWidget

Bases: gluon.sqlhtml.FormWidget

static has_options(field)

checks if the field has selectable options

Parameter:field – the field needing checking
Returns:True if the field has options
static widget(field, value, **attributes)

generates a SELECT tag, including OPTIONs (only 1 option allowed)

see also: FormWidget.widget()

class gluon.sqlhtml.PasswordWidget

Bases: gluon.sqlhtml.FormWidget

static widget(field, value, **attributes)

generates a INPUT password tag. If a value is present it will be shown as a number of ‘*’, not related to the length of the actual value.

see also: FormWidget.widget()

class gluon.sqlhtml.RadioWidget

Bases: gluon.sqlhtml.OptionsWidget

static widget(field, value, **attributes)

generates a TABLE tag, including INPUT radios (only 1 option allowed)

see also: FormWidget.widget()

class gluon.sqlhtml.SQLFORM(table, record=None, deletable=False, linkto=None, upload=None, fields=None, labels=None, col3={}, submit_button='Submit', delete_label='Check to delete:', showid=True, readonly=False, comments=True, keepopts=[], ignore_rw=False, **attributes)

Bases: gluon.html.FORM

SQLFORM is used to map a table (and a current record) into an HTML form

given a SQLTable stored in db.table

generates an insert form:

SQLFORM(db.table) 

generates an update form:

record=db(db.table.id==some_id).select()[0]
SQLFORM(db.table, record) 

generates an update with a delete button:

SQLFORM(db.table, record, deletable=True) 

if record is an int:

record=db(db.table.id==record).select()[0]

optional arguments:

Parameters:
  • fields – a list of fields that should be placed in the form, default is all.
  • labels – a dictionary with labels for each field. keys are field names.
  • col3 – a dictionary with content for an optional third column (right of each field). keys are field names.
  • linkto – the URL of a controller/function to access referencedby records see controller appadmin.py for examples
  • upload – the URL of a controller/function to download an uploaded file see controller appadmin.py for examples
any named optional attribute is passed to the <form> tag
for example _class, _id, _style, _action,_method, etc.
accepts(request_vars, session=None, formname='%(tablename)s_%(record_id)s', keepvalues=False, onvalidation=None)
same as FORM.accepts but also does insert, update or delete in SQLDB.
static factory(*fields, **attributes)

generates a SQLFORM for the given fields.

Internally will build a non-database based data model to hold the fields.

class gluon.sqlhtml.SQLTABLE(sqlrows, linkto=None, upload=None, orderby=None, headers={}, truncate=16, **attributes)

Bases: gluon.html.TABLE

given a SQLRows object, as returned by a db().select(), generates an html table with the rows.

optional arguments:

Parameters:
  • linkto – URL to edit individual records
  • upload – URL to download uploaded files
  • orderby – Add an orderby link to column headers.
  • headers – dictionary of headers to headers redefinions
  • truncate – length at which to truncate text in table cells. Defaults to 16 characters.

optional names attributes for passed to the <table> tag

class gluon.sqlhtml.StringWidget

Bases: gluon.sqlhtml.FormWidget

static widget(field, value, **attributes)

generates an INPUT text tag.

see also: FormWidget.widget()

class gluon.sqlhtml.TextWidget

Bases: gluon.sqlhtml.FormWidget

static widget(field, value, **attributes)

generates a TEXTAREA tag.

see also: FormWidget.widget()

class gluon.sqlhtml.TimeWidget
Bases: gluon.sqlhtml.StringWidget
class gluon.sqlhtml.UploadWidget

Bases: gluon.sqlhtml.FormWidget

static is_image(value)

Tries to check if the filename provided references to an image

Checking is based on filename extension. Currently recognized:
gif, png, jp(e)g, bmp
Parameter:value – filename
static represent(field, value, download_url=None)

how to represent the file:

  • with download url and if it is an image: <A href=...><IMG ...></A>
  • otherwise with download url: <A href=...>file</A>
  • otherwise: file
Parameters:
  • field – the field
  • value – the field value
  • download_url – url for the file download 9default = None)
static widget(field, value, download_url=None, **attributes)

generates a INPUT file tag.

Optionally provides an A link to the file, including a checkbox so the file can be deleted. All is wrapped in a DIV.

see also: FormWidget.widget()

Parameter:download_url – Optional URL to link to the file (default = None)
gluon.sqlhtml.form_factory(*fields, **attributes)

generates a SQLFORM for the given fields.

Internally will build a non-database based data model to hold the fields.

The tools Module

This file is part of web2py Web Framework (Copyrighted, 2007-2009). Developed by Massimo Di Pierro <mdipierro@cs.depaul.edu>. License: GPL v2

class gluon.tools.Mail

Bases: object

Class for configuring and sending emails. Works with SMTP and Google App Engine

Example:

from contrib.utils import *
mail=Mail()
mail.settings.server='smtp.gmail.com:587'
mail.settings.sender='you@somewhere.com'
mail.settings.login=None or 'username:password'
mail.send(to=['you@whatever.com'],subject='None',message='None')

In Google App Engine use:

mail.settings.server='gae'
send(to, subject='None', message='None')
Sends an email. Returns True on success, False on failure.
class gluon.tools.Auth(environment, db=None)

Bases: object

Class for authentication, authorization, role based access control.

Includes:

  • registration and profile
  • login and logout
  • username and password retrieval
  • event logging
  • role creation and assignment
  • user defined group/role based permission

Authentication Example:

from contrib.utils import *
mail=Mail()
mail.settings.server='smtp.gmail.com:587'
mail.settings.sender='you@somewhere.com'
mail.settings.login='username:password'
auth=Auth(globals(), db)
auth.settings.mailer=mail
# auth.settings....=...
auth.define_tables()
def authentication(): 
    return dict(form=auth())

exposes:

  • http://.../{application}/{controller}/authentication/login
  • http://.../{application}/{controller}/authentication/logout
  • http://.../{application}/{controller}/authentication/register
  • http://.../{application}/{controller}/authentication/veryfy_email
  • http://.../{application}/{controller}/authentication/retrieve_username
  • http://.../{application}/{controller}/authentication/retrieve_password
  • http://.../{application}/{controller}/authentication/profile
  • http://.../{application}/{controller}/authentication/change_password

On registration a group with role=new_user.id is created and user is given membership of this group.

You can create a group with:

group_id=auth.add_group('Manager', 'can access the manage action')
auth.add_permission(group_id, 'access to manage')

Here “access to manage” is just a user defined string. You can give access to a user:

auth.add_membership(group_id, user_id)

If user id is omitted, the logged in user is assumed

Then you can decorate any action:

@auth.requires_permission('access to manage')
def manage():
    return dict()

You can restrict a permission to a specific table:

auth.add_permission(group_id, 'edit', db.sometable)
@auth.requires_permission('edit', db.sometable)

Or to a specific record:

auth.add_permission(group_id, 'edit', db.sometable, 45)
@auth.requires_permission('edit', db.sometable,45)

If authorization is not granted calls:

auth.settings.on_failed_authorization

Other options:

auth.settings.mailer=None
auth.settings.expiration=3600 # seconds

...

### these are messages that can be customized
...
accessible_query(name, table, user_id=None)

returns a query with all accessible records for user_id or the current logged in user this method does not work on GAE because uses JOIN and IN

example:

db(accessible_query('read', db.mytable)).select(db.mytable.ALL)
add_group(role, description='')
creates a group associated to a role
add_membership(group_id, user_id=None)
gives user_id membership of group_id if group_id==None than user_id is that of current logged in user
add_permission(group_id, name='any', table_name='', record_id=0)
gives group_id ‘name’ access to ‘table_name’ and ‘record_id’
basic()
change_password(next=<function <lambda> at 0x465d5b0>, onvalidation=<function <lambda> at 0x465d5b0>, onaccept=<function <lambda> at 0x465d5b0>, log=<function <lambda> at 0x465d5b0>)

returns a form that lets the user change password

Auth.change_password([next=DEFAULT[, onvalidation=DEFAULT[,
onaccepet=DEFAULT[, log=DEFAULT]]]])
define_tables(migrate=True)

to be called unless tables are defined manually

usages:

# defines all needed tables and table files UUID+'_auth_user.table',...
auth.define_tables()

# defines all needed tables and table files 'myprefix_auth_user.table',...
auth.define_tables(migrate='myprefix_')

# defines all needed tables without migration/table files
auth.define_tables(migrate=False)              
del_group(group_id)
deletes a group
del_membership(group_id, user_id=None)
revokes membership from group_id to user_id if group_id==None than user_id is that of current logged in user
del_permission(group_id, name='any', table_name='', record_id=0)
revokes group_id ‘name’ access to ‘table_name’ and ‘record_id’
get_or_create_user(keys)
groups()
displays the groups and their roles for the logged in user
has_membership(group_id, user_id=None)
checks if user is member of group_id
has_permission(name='any', table_name='', record_id=0, user_id=None)
checks if user_id or current logged in user is member of a group that has ‘name’ permission on ‘table_name’ and ‘record_id’
id_group(role)
returns the group_id of the group specified by the role
impersonate(user_id=<function <lambda> at 0x465d5b0>)

usage: http://..../impersonate/[user_id] or: http://..../impersonate/0 to restore impersonator

requires impersonator is logged in and has_permission(‘impersonate’,’auth_user’,user_id)

is_impersonating()
is_logged_in()
checks if the user is logged in and returns True/False. if so user is in auth.user as well as in session.auth.user
log_event(description, origin='auth')

usage:

auth.log_event(description='this happened',origin='auth')
login(next=<function <lambda> at 0x465d5b0>, onvalidation=<function <lambda> at 0x465d5b0>, onaccept=<function <lambda> at 0x465d5b0>, log=<function <lambda> at 0x465d5b0>)

returns a login form

Auth.login([next=DEFAULT [, onvalidation=DEFAULT
[, onaccept=DEFAULT [, log=DEFAULT]]]])
login_bare(username, password)
logins user
logout(next=<function <lambda> at 0x465d5b0>, onlogout=<function <lambda> at 0x465d5b0>, log=<function <lambda> at 0x465d5b0>)

logout and redirects to login

logout([next=DEFAULT[, onlogout=DEFAULT[, log=DEFAULT]]])
not_authorized()
you can change the view for this page to make it look as you like
profile(next=<function <lambda> at 0x465d5b0>, onvalidation=<function <lambda> at 0x465d5b0>, onaccept=<function <lambda> at 0x465d5b0>, log=<function <lambda> at 0x465d5b0>)

returns a form that lets the user change his/her profile

Auth.profile([next=DEFAULT [, onvalidation=DEFAULT
[, onaccept=DEFAULT [, log=DEFAULT]]]])
random_password()
register(next=<function <lambda> at 0x465d5b0>, onvalidation=<function <lambda> at 0x465d5b0>, onaccept=<function <lambda> at 0x465d5b0>, log=<function <lambda> at 0x465d5b0>)

returns a registration form

Auth.register([next=DEFAULT [, onvalidation=DEFAULT
[, onaccept=DEFAULT [, log=DEFAULT]]]])
requires(condition)
decorator that prevents access to action if not logged in
requires_login()
decorator that prevents access to action if not logged in
requires_membership(role)
decorator that prevents access to action if not logged in or if user logged in is not a member of group_id. If role is provided instead of group_id then the group_id is calculated.
requires_permission(name, table_name='', record_id=0)
decorator that prevents access to action if not logged in or if user logged in is not a member of any group (role) that has ‘name’ access to ‘table_name’, ‘record_id’.
retrieve_password(next=<function <lambda> at 0x465d5b0>, onvalidation=<function <lambda> at 0x465d5b0>, onaccept=<function <lambda> at 0x465d5b0>, log=<function <lambda> at 0x465d5b0>)

returns a form to retrieve the user password

Auth.retrieve_password([next=DEFAULT [, onvalidation=DEFAULT
[, onaccept=DEFAULT [, log=DEFAULT]]]])
retrieve_username(next=<function <lambda> at 0x465d5b0>, onvalidation=<function <lambda> at 0x465d5b0>, onaccept=<function <lambda> at 0x465d5b0>, log=<function <lambda> at 0x465d5b0>)

returns a form to retrieve the user username (only if there is a username field)

Auth.retrieve_username([next=DEFAULT [, onvalidation=DEFAULT
[, onaccept=DEFAULT [, log=DEFAULT]]]])
url(f=None, args=[], vars={})
user_group(user_id=None)
returns the group_id of the group uniquely associated to this user i.e. role=user:[user_id]
verify_email(next=<function <lambda> at 0x465d5b0>, onaccept=<function <lambda> at 0x465d5b0>, log=<function <lambda> at 0x465d5b0>)

action user to verify the registration email, XXXXXXXXXXXXXXXX

Auth.verify_email([next=DEFAULT [, onvalidation=DEFAULT
[, onaccept=DEFAULT [, log=DEFAULT]]]])
class gluon.tools.Recaptcha(request, public_key='', private_key='', use_ssl=False, error=None, error_message='invalid')

Bases: gluon.html.DIV

xml()
class gluon.tools.Crud(environment, db)

Bases: object

create(table, next=<function <lambda> at 0x465d5b0>, onvalidation=<function <lambda> at 0x465d5b0>, onaccept=<function <lambda> at 0x465d5b0>, log=<function <lambda> at 0x465d5b0>, message=<function <lambda> at 0x465d5b0>)
Crud.create(table, [next=DEFAULT [, onvalidation=DEFAULT
[, onaccept=DEFAULT [, log=DEFAULT[, message=DEFAULT]]]]])
delete(table, record_id, next=<function <lambda> at 0x465d5b0>, message=<function <lambda> at 0x465d5b0>)
delete(table, record_id[, next=DEFAULT[, message=DEFAULT]])
has_permission(name, table, record=0)
log_event(message)
read(table, record)
select(table, query=None, fields=None, orderby=None, limitby=None, headers={}, **attr)
tables()
update(table, record, next=<function <lambda> at 0x465d5b0>, onvalidation=<function <lambda> at 0x465d5b0>, onaccept=<function <lambda> at 0x465d5b0>, ondelete=<function <lambda> at 0x465d5b0>, log=<function <lambda> at 0x465d5b0>, message=<function <lambda> at 0x465d5b0>, deletable=<function <lambda> at 0x465d5b0>)
Crud.update(table, record, [next=DEFAULT [, onvalidation=DEFAULT
[, onaccept=DEFAULT [, log=DEFAULT[, message=DEFAULT[, deletable=DEFAULT]]]]]])
url(f=None, args=[], vars={})
class gluon.tools.Service(environment)
amfrpc(f)

example:

service = Service(globals())
@service.amfrpc
def myfunction(a, b):
    return a + b
def call(): 
    return service()

The call it with:

wget http://..../app/default/call/amfrpc/myfunc?a=hello&b=world
csv(f)

example:

service = Service(globals())
@service.csv
def myfunction(a, b):
    return a + b
def call():
    return service()

Then call it with:

wget http://..../app/default/call/csv/myfunc?a=3&b=4
error()
json(f)

example:

service = Service(globals())
@service.json
def myfunction(a, b):
    return [{a: b}]
def call(): 
    return service()

Then call it with:

wget http://..../app/default/call/json/myfunc?a=hello&b=world
jsonrpc(f)

example:

service = Service(globals())
@service.jsonrpc
def myfunction(a, b):
    return a + b
def call(): 
    return service()

Then call it with:

wget http://..../app/default/call/jsonrpc/myfunc?a=hello&b=world
rss(f)

example:

service = Service(globals())
@service.rss
def myfunction():
    return dict(title=...,link=...,description=...,created_on=...,
                entries=[dict(title=...,link=...,description=...,created_on=...])
def call(): 
    return service()

Then call it with:

wget http://..../app/default/call/rss/myfunc
run(f)

example:

service = Service(globals())
@service.run
def myfunction(a, b):
    return a + b
def call():
    return service()

Then call it with:

wget http://..../app/default/call/run/myfunc?a=3&b=4
serve_amfrpc()
serve_csv(args=None)
serve_json(args=None)
serve_jsonrpc()
serve_rss(args=None)
serve_run(args=None)
serve_xml(args=None)
serve_xmlrpc()
xml(f)

example:

service = Service(globals())
@service.xml
def myfunction(a, b):
    return a + b
def call():
    return service()

Then call it with:

wget http://..../app/default/call/xml/myfunc?a=3&b=4
xmlrpc(f)

example:

service = Service(globals())
@service.xmlrpc
def myfunction(a, b):
    return a + b
def call(): 
    return service()

The call it with:

wget http://..../app/default/call/xmlrpc/myfunc?a=hello&b=world
gluon.tools.fetch(url)
gluon.tools.geocode(address)

The languages Module

This file is part of web2py Web Framework (Copyrighted, 2007-2009). Developed by Massimo Di Pierro <mdipierro@cs.depaul.edu>. License: GPL v2

class gluon.languages.translator(request)

Bases: object

this class is instantiated once in gluon/main.py as the T object

T.force(None) # turns off translation
T.force('fr, it') # forces web2py to translate using fr.py or it.py

T("Hello World") # translates "Hello World" using the selected file

notice 1: there is no need to force since, by default, T uses accept_langauge to determine a translation file.

notice 2: en and en-en are considered different languages!

force(languages=[])
translate(message, symbols)
gluon.languages.findT(path, language='en-us')
must be run by the admin app
gluon.languages.update_all_languages(application_path)

The streamer Module

This file is part of web2py Web Framework (Copyrighted, 2007-2009). Developed by Massimo Di Pierro <mdipierro@cs.depaul.edu>. License: GPL v2

gluon.streamer.stream_file_or_304_or_206(static_file, chunk_size=1000000, request=None, headers={}, error_message='<html><body><h1>Invalid request</h1></body></html>')
gluon.streamer.streamer(file, chunk_size=1000000, bytes=None)

The restricted Module

This file is part of web2py Web Framework (Copyrighted, 2007-2009). Developed by Massimo Di Pierro <mdipierro@cs.depaul.edu>. License: GPL v2

class gluon.restricted.RestrictedError(layer='', code='', output='', environment={})

class used to wrap an exception that occurs in the restricted environment below. the traceback is used to log the exception and generate a ticket.

load(request, app, ticket_id)
loads a logged exception.
log(request)
logs the exception.
gluon.restricted.restricted(code, environment={}, layer='Unknown')
runs code in environment and returns the output. if an exception occurs in code it raises a RestrictedError containing the traceback. layer is passed to RestrictedError to identify where the error occurred.
class gluon.restricted.TicketStorage(db=None, tablename='web2py_ticket')

Bases: gluon.storage.Storage

defines the ticket object and the default values of its members (None)

load(request, app, ticket_id)
store(request, ticket_id, ticket_data)
stores the ticket. It will figure out if this must be on disk or in db

The http Module

This file is part of web2py Web Framework (Copyrighted, 2007-2009). Developed by Massimo Di Pierro <mdipierro@cs.depaul.edu>. License: GPL v2

exception gluon.http.HTTP(status, body='', **headers)

Bases: exceptions.BaseException

to(responder)
gluon.http.redirect(location, how=303)

The storage Module

This file is part of web2py Web Framework (Copyrighted, 2007-2009). Developed by Massimo Di Pierro <mdipierro@cs.depaul.edu>. License: GPL v2

Provides:

  • List; like list but returns None instead of IndexOutOfBounds
  • Storage; like dictionary allowing also for obj.foo for obj[‘foo’]
class gluon.storage.List

Bases: list

Like a regular python list but a[i] if i is out of bounds return None instead of IndexOutOfBounds

class gluon.storage.Storage

Bases: dict

A Storage object is like a dictionary except obj.foo can be used in addition to obj[‘foo’].

>>> o = Storage(a=1)
>>> print o.a
1
>>> o['a']
1
>>> o.a = 2
>>> print o['a']
2
>>> del o.a
>>> print o.a
None
class gluon.storage.Settings
Bases: gluon.storage.Storage
class gluon.storage.Messages(T)
Bases: gluon.storage.Storage
gluon.storage.load_storage(filename)
gluon.storage.save_storage(storage, filename)

The highlight Module

This file is part of web2py Web Framework (Copyrighted, 2007-2009). Developed by Massimo Di Pierro <mdipierro@cs.depaul.edu>. License: GPL v2

gluon.highlight.highlight(code, language, link='/examples/globals/vars/', counter=1, styles={}, attributes={})

The cache Module

This file is part of web2py Web Framework (Copyrighted, 2007-2009). Developed by Massimo Di Pierro <mdipierro@cs.depaul.edu>. License: GPL v2

Basic caching classes and methods

  • Cache - The generic caching object interfacing with the others
  • CacheInRam - providing caching in ram
  • CacheInDisk - provides caches on disk

Memcache is also available via a different module (see gluon.contrib.memcache)

When web2py is running on Google App Engine, caching will be provided by the GAE memcache (see gluon.contrib.gae_memcache)

class gluon.cache.Cache(request)

Bases: object

Sets up generic caching, creating an instance of both CacheInRam and CacheOnDisk. In case of GAE will make use of gluon.contrib.gae_memcache

  • self.ram is an instance of CacheInRam
  • self.disk is an instance of CacheOnDisk

The sanitizer Module

# from http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/496942
# Title: Cross-site scripting (XSS) defense
# Submitter: Josh Goldfoot (other recipes)
# Last Updated: 2006/08/05
# Version no: 1.0
gluon.sanitizer.sanitize(text, permitted_tags=[, 'a', 'b', 'blockquote', 'br/', 'i', 'li', 'ol', 'ul', 'p', 'cite', 'code', 'pre', 'img/'], allowed_attributes={'a':[, 'href', 'title'], 'blockquote':[, 'type'], 'img':[, 'src', 'alt'], })

The main Module

This file is part of web2py Web Framework (Copyrighted, 2007-2009). Developed by Massimo Di Pierro <mdipierro@cs.depaul.edu>. License: GPL v2

Contains:

  • wsgibase: the gluon wsgi application
gluon.main.wsgibase(environ, responder)

this is the gluon wsgi application. the first function called when a page is requested (static or dynamic). it can be called by paste.httpserver or by apache mod_wsgi.

  • fills request with info
    • the environment variables, replacing ‘.’ with ‘_’
    • adds web2py path and version info
    • compensates for fcgi missing path_info and query_string
  • validates the path in url

The url path must be either:

  1. for static pages:
  • /<application>/static/<file>
  1. for dynamic pages:
  • /<application>[/<controller>[/<function>[/<sub>]]][.<extension>]

  • (sub may go several levels deep, currently 3 levels are supported:

    sub1/sub2/sub3)

The naming conventions are:

  • application, controller, function and extension may only contain [a-zA-Z0-9_]
  • file and sub may also contain ‘-‘, ‘=’, ‘.’ and ‘/’
gluon.main.save_password(password, port)
used by main() to save the password in the parameters.py file.
gluon.main.appfactory(wsgiapp=<function wsgibase at 0x30ff5f0>, logfilename='httpsever.log', profilerfilename='profiler.log', web2py_path='/Users/mdipierro/web2py')

generates a wsgi application that does logging and profiling and calls wsgibase

gluon.main.appfactory(
[wsgiapp=wsgibase
[, logfilename='httpsever.log'
[, profilerfilename='profiler.log'
[, web2py_path=web2py_path]]]])
class gluon.main.HttpServer(ip='127.0.0.1', port=8000, password='', pid_filename='httpserver.pid', log_filename='httpserver.log', profiler_filename=None, ssl_certificate=None, ssl_private_key=None, numthreads=10, server_name=None, request_queue_size=5, timeout=10, shutdown_timeout=5, path='/Users/mdipierro/web2py')

Bases: object

the web2py web server (wsgiserver)

start()
start the web server
stop()
stop the web server

The widget Module

This file is part of web2py Web Framework (Copyrighted, 2007-2009). Developed by Massimo Di Pierro <mdipierro@cs.depaul.edu>. License: GPL v2

The widget is called from web2py.

class gluon.widget.IO

Bases: object

write(data)
gluon.widget.console()
Defines the behaviour of the console web2py execution
gluon.widget.presentation(root)
Draw the splash screen
gluon.widget.start(cron=True)
Start server
gluon.widget.start_browser(ip, port)
Starts the default browser
gluon.widget.try_start_browser(url)
Try to start the default browser
class gluon.widget.web2pyDialog(root, options)

Bases: object

Main window dialog

checkTaskBar()
Check taskbar status
connect_pages()
Connect pages
error(message)
Show error message
quit(justHide=False)
Finish the program execution
start()
Start web2py server
stop()
Stop web2py server
update(text)
Update app text
update_canvas()
Update canvas

The rewrite Module

This file is part of web2py Web Framework (Copyrighted, 2007-2009). Developed by Massimo Di Pierro <mdipierro@cs.depaul.edu>. License: GPL v2

gluon.rewrite.rewrite(wsgibase, URL)

The html Module

This file is part of web2py Web Framework (Copyrighted, 2007-2009). Developed by Massimo Di Pierro <mdipierro@cs.depaul.edu>. License: GPL v2

class gluon.html.A(*components, **attributes)
Bases: gluon.html.DIV
class gluon.html.B(*components, **attributes)
Bases: gluon.html.DIV
class gluon.html.BEAUTIFY(component, **attributes)

Bases: gluon.html.DIV

example:

>>> BEAUTIFY(['a', 'b', {'hello': 'world'}]).xml()
'<div><table><tr><td><div>a</div></td></tr><tr><td><div>b</div></td></tr><tr><td><div><table><tr><td><b><div>hello</div></b></td><td align="top">:</td><td><div>world</div></td></tr></table></div></td></tr></table></div>'

turns any list, dictionarie, etc into decent looking html.

class gluon.html.BODY(*components, **attributes)
Bases: gluon.html.DIV
class gluon.html.BR(*components, **attributes)
Bases: gluon.html.DIV
class gluon.html.CENTER(*components, **attributes)
Bases: gluon.html.DIV
class gluon.html.CODE(*components, **attributes)

Bases: gluon.html.DIV

displays code in HTML with syntax highlighting.

Parameter:attributes

optional attributes:

  • language: indicates the language, otherwise PYTHON is assumed
  • link: can provide a link
  • styles: for styles

Example:

{{=CODE("print 'hello world'", language='python', link=None, counter=1, styles={})}}

supported languages are “python”, “html_plain”, “c”, “cpp”, “web2py”, “html”. The “html” language interprets {{ and }} tags as “web2py” code, “html_plain” doesn’t.

if a link=’/examples/global/vars/’ is provided web2py keywords are linked to the online docs. the counter is used for line numbering, counter can be None or a prompt string.

xml()
class gluon.html.DIV(*components, **attributes)

Bases: gluon.html.XmlComponent

HTML helper, for easy generating and manipulating a DOM structure. Little or no validation is done.

Behaves like a dictionary regarding updating of attributes. Behaves like a list regarding inserting/appending components.

example:

>>> DIV('hello','world',_style='color:red;').xml() 
'<div style="color:red;">helloworld</div>'

all other HTML helpers are derived from DIV.

_something=”value” attributes are transparently translated into something=”value” HTML attributes

append(value)
list style appending of components
element(**kargs)

find the first component that matches the supplied attribute dictionary, or None if nothing could be found

Also the components of the components are searched.

insert(i, value)
list style inserting of components
update(**kargs)
dictionary like updating of the tag attributes
xml()
generates the xml for this component.
class gluon.html.EM(*components, **attributes)
Bases: gluon.html.DIV
class gluon.html.EMBED(*components, **attributes)
Bases: gluon.html.DIV
class gluon.html.FIELDSET(*components, **attributes)
Bases: gluon.html.DIV
class gluon.html.FORM(*components, **attributes)

Bases: gluon.html.DIV

example:

>>> form=FORM(INPUT(_name="test",requires=IS_NOT_EMPTY()))
>>> form.xml()
'<form action="" enctype="multipart/form-data" method="post"><input name="test" type="text" /></form>'

a FORM is container for INPUT, TEXTAREA, SELECT and other helpers

form has one important method:

form.accepts(request.vars, session)

if form is accepted (and all validators pass) form.vars contains the accepted vars, otherwise form.errors contains the errors. in case of errors the form is modified to present the errors to the user.

accepts(vars, session=None, formname='default', keepvalues=False, onvalidation=None)
hidden_fields()
xml()
class gluon.html.H1(*components, **attributes)
Bases: gluon.html.DIV
class gluon.html.H2(*components, **attributes)
Bases: gluon.html.DIV
class gluon.html.H3(*components, **attributes)
Bases: gluon.html.DIV
class gluon.html.H4(*components, **attributes)
Bases: gluon.html.DIV
class gluon.html.H5(*components, **attributes)
Bases: gluon.html.DIV
class gluon.html.H6(*components, **attributes)
Bases: gluon.html.DIV
class gluon.html.HEAD(*components, **attributes)
Bases: gluon.html.DIV
class gluon.html.HR(*components, **attributes)
Bases: gluon.html.DIV
class gluon.html.HTML(*components, **attributes)

Bases: gluon.html.DIV

HTML: Will provide a doctype on xml()

You can override the default doctype by supplying the ‘doctype’ attribute

see also DIV

xml()
class gluon.html.IFRAME(*components, **attributes)
Bases: gluon.html.DIV
class gluon.html.IMG(*components, **attributes)
Bases: gluon.html.DIV
class gluon.html.INPUT(*components, **attributes)

Bases: gluon.html.DIV

INPUT Component

examples:

>>> INPUT(_type='text',_name='name',value='Max').xml()
'<input name="name" type="text" value="Max" />'

>>> INPUT(_type='checkbox',_name='checkbox',value='on').xml()
'<input checked="checked" name="checkbox" type="checkbox" value="on" />'

>>> INPUT(_type='radio',_name='radio',_value='yes',value='yes').xml()
'<input checked="checked" name="radio" type="radio" value="yes" />'

>>> INPUT(_type='radio',_name='radio',_value='no',value='yes').xml()
'<input name="radio" type="radio" value="no" />'

the input helper takes two special attributes value= and requires=.

Parameters:
  • value

    used to pass the initial value for the input field. value differs from _value because it works for checkboxes, radio, textarea and select/option too.

    • for a checkbox value should be ‘’ or ‘on’.
    • for a radio or select/option value should be the _value
      of the checked/selected item.
  • requires – should be None, or a validator or a list of validators for the value of the field.
xml()
class gluon.html.LABEL(*components, **attributes)
Bases: gluon.html.DIV
class gluon.html.LEGEND(*components, **attributes)
Bases: gluon.html.DIV
class gluon.html.LI(*components, **attributes)
Bases: gluon.html.DIV
Bases: gluon.html.DIV
class gluon.html.OL(*components, **attributes)
Bases: gluon.html.UL
class gluon.html.UL(*components, **attributes)

Bases: gluon.html.DIV

UL Component.

If subcomponents are not LI-components they will be wrapped in a LI

see also DIV

class gluon.html.MENU(data, **args)

Bases: gluon.html.DIV

Used to build menus

Optional arguments
_class: defaults to ‘web2py-menu web2py-menu-vertical’ ul_class: defaults to ‘web2py-menu-vertical’ li_class: defaults to ‘web2py-menu-expand’
Example:
menu = MENU([[‘name’, False, URL(...), [submenu]], ...]) {{=menu}}
serialize(data, level=0)
xml()
class gluon.html.META(*components, **attributes)
Bases: gluon.html.DIV
class gluon.html.OBJECT(*components, **attributes)
Bases: gluon.html.DIV
class gluon.html.OPTION(*components, **attributes)
Bases: gluon.html.DIV
class gluon.html.P(*components, **attributes)

Bases: gluon.html.DIV

Will replace \n by <br /> if the cr2br attribute is provided.

see also DIV

xml()
class gluon.html.PRE(*components, **attributes)
Bases: gluon.html.DIV
class gluon.html.SCRIPT(*components, **attributes)

Bases: gluon.html.DIV

xml()
class gluon.html.SELECT(*components, **attributes)

Bases: gluon.html.INPUT

example:

>>> SELECT('yes', 'no', _name='selector', value='yes',
...    requires=IS_IN_SET(['yes', 'no'])).xml()
'<select name="selector"><option selected="selected" value="yes">yes</option><option value="no">no</option></select>'
class gluon.html.SPAN(*components, **attributes)
Bases: gluon.html.DIV
class gluon.html.STYLE(*components, **attributes)
Bases: gluon.html.SCRIPT
class gluon.html.TABLE(*components, **attributes)

Bases: gluon.html.DIV

TABLE Component.

If subcomponents are not TR/TBODY/THEAD/TFOOT-components they will be wrapped in a TR

see also DIV

gluon.html.TAG

TAG factory example:

>>> print TAG.first(TAG.second('test'), _key = 3)
<first key="3"><second>test</second></first>
class gluon.html.TD(*components, **attributes)
Bases: gluon.html.DIV
class gluon.html.TEXTAREA(*components, **attributes)

Bases: gluon.html.INPUT

example:

TEXTAREA(_name='sometext', value='bla '*100, requires=IS_NOT_EMPTY())

‘bla bla bla ...’ will be the content of the textarea field.

class gluon.html.TH(*components, **attributes)
Bases: gluon.html.DIV
class gluon.html.THEAD(*components, **attributes)
Bases: gluon.html.DIV
class gluon.html.TBODY(*components, **attributes)
Bases: gluon.html.DIV
class gluon.html.TFOOT(*components, **attributes)
Bases: gluon.html.DIV
class gluon.html.TITLE(*components, **attributes)
Bases: gluon.html.DIV
class gluon.html.TR(*components, **attributes)

Bases: gluon.html.DIV

TR Component.

If subcomponents are not TD/TH-components they will be wrapped in a TD

see also DIV

class gluon.html.TT(*components, **attributes)
Bases: gluon.html.DIV
gluon.html.URL(a=None, c=None, f=None, r=None, args=[], vars={}, anchor='')

generate a relative URL

example:

>>> URL(a='a', c='c', f='f', args=['x', 'y', 'z'], 
...     vars={'p':1, 'q':2}, anchor='1')
'/a/c/f/x/y/z#1?q=2&p=1'

generates a url “/a/c/f” corresponding to application a, controller c and function f. If r=request is passed, a,c,f are set, respectively, to r.applicaiton, r.controller, r.function.

The more typical usage is:

URL(r=request,f=’index’) that generates a url for the index function within the present application and controller.

Parameters:
  • a – application (default to current if r is given)
  • c – controller (default to current if r is given)
  • f – function (default to current if r is given)
  • r – request (optional)
  • args – any arguments (optional)
  • vars – any variables (optional)
  • anchor – anchorname, without # (optional)
Raises SyntaxError:
 

when no application, controller or function is available

Raises SyntaxError:
 

when a CRLF is found in the generated url

class gluon.html.XML(text, sanitize=False, permitted_tags=[, 'a', 'b', 'blockquote', 'br/', 'i', 'li', 'ol', 'ul', 'p', 'cite', 'code', 'pre', 'img/'], allowed_attributes={'a':[, 'href', 'title'], 'blockquote':[, 'type'], 'img':[, 'src', 'alt'], })

Bases: gluon.html.XmlComponent

use it to wrap a string that contains XML/HTML so that it will not be escaped by the template

example:

>>> XML('<h1>Hello</h1>').xml()
'<h1>Hello</h1>'
xml()
gluon.html.xmlescape(data, quote=False)

returns an escaped string of the provided data

Parameters:
  • data – the data to be escaped
  • quote – optional (default False)
gluon.html.embed64(filename=None, file=None, data=None, extension='image/gif')

helper to encode the provided (binary) data into base64.

Parameters:
  • filename – if provided, opens and reads this file in ‘rb’ mode
  • file – if provided, reads this file
  • data – if provided, uses the provided data

The contenttype Module

This file is part of web2py Web Framework (Copyrighted, 2007-2009). Developed by Massimo Di Pierro <mdipierro@cs.depaul.edu>. License: GPL v2

gluon.contenttype.contenttype(filename)
Returns the Content-Type string matching extension of the given filename.