This page contains the Gluon Package documentation.
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
Bases: gluon.validators.IS_MATCH
example:
INPUT(_type='text', _name='name', requires=IS_ALPHANUMERIC())
Bases: gluon.validators.Validator
example:
INPUT(_type='text', _name='name', requires=IS_DATE())
date has to be in the ISO8960 format YYYY-MM-DD
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
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(|..*)$’))
Check for valid email address that must be from a .edu domain: INPUT(_type=’text’, _name=’name’, requires=IS_EMAIL(forced=’^.*.edu(|..*)$’))
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!')
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:
filename: filename (before dot) regex extension: extension (after dot) regex lastdot: which dot should be used as a filename / extension separator:
True means last dot, eg. file.png -> file / png False means first dot, eg. file.tar.gz -> file / tar.gz
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))
Bases: gluon.validators.Validator
example:
INPUT(_type='text', _name='name', requires=IS_FLOAT_IN_RANGE(0, 10))
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)))
Bases: gluon.validators.Validator
example:
INPUT(_type='text', _name='name', requires=IS_INT_IN_RANGE(0, 10))
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
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:
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'))
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))
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!')
Bases: gluon.validators.Validator
example:
INPUT(_type='text', _name='name', requires=IS_NOT_EMPTY())
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
Bases: gluon.validators.Validator
(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:
- 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
Bases: gluon.validators.Validator
example:
INPUT(_type='text', _name='name', requires=CLEANUP())
removes special characters on validation
Bases: object
example:
INPUT(_type='text', _name='name', requires=CRYPT())
encodes the value on validation with a digest
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
Bases: gluon.validators.Validator
example:
INPUT(_type='text', _name='name', requires=IS_NOT_IN_DB(db, db.table))
makes the field unique
Bases: gluon.validators.Validator
Bases: object
example:
INPUT(_type='password', _name='passwd',
requires=IS_STRONG(min=10, special=2, upper=2))
enforces complexity requirements on a field
This file is part of web2py Web Framework (Copyrighted, 2007-2009). Developed by Massimo Di Pierro <mdipierro@cs.depaul.edu>. License: GPL v2
This file contains the DAL support for many relational databases, like SQLite, MySQL, Postgres, Oracle, MS-Sql, DB2, Interbase.
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'))
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
This file is part of web2py Web Framework (Copyrighted, 2007-2009). Developed by Massimo Di Pierro <mdipierro@cs.depaul.edu>. License: GPL v2
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
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.
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
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.
This file is part of web2py Web Framework (Copyrighted, 2007-2009). Developed by Massimo Di Pierro <mdipierro@cs.depaul.edu>. License: GPL v2
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:
Bases: gluon.storage.Storage
defines the request object and the default values of its members
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
example of usage in controller:
def download():
return response.download(request, db)
downloads from http://..../download/filename
if a controller function:
return response.stream(file, 100)
the file content will be streamed at 100 bytes at the time
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)
Bases: gluon.storage.Storage
defines the session object and the default values of its members (None)
This file is part of web2py Web Framework (Copyrighted, 2007-2009). Developed by Massimo Di Pierro <mdipierro@cs.depaul.edu>. License: GPL v2
FOR INTERNAL USE ONLY
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.
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
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.
Bases: object
An HTTP server for WSGI.
Parameters: |
|
---|
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.
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.
Bases: object
An HTTP Request (and response).
A single HTTP connection may consist of multiple request/response pairs.
Parameters: |
|
---|
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).
Bases: exceptions.Exception
Exception raised when a client speaks HTTP to an HTTPS socket.
A thread-safe wrapper for an SSL.Connection.
Parameter: | args – the arguments to create the wrapped SSL.Connection. |
---|
Bases: socket._fileobject
Faux file object attached to a socket object.
Bases: object
Wraps a file-like object, raising MaxSizeExceeded if too large.
Bases: object
A Request Queue for the CherryPyWSGIServer which pools threads.
Bases: object
A WSGI dispatcher for dispatch based on the PATH_INFO.
apps: a dict or list of (path_prefix, app) pairs.
Bases: threading.Thread
Thread which continuously polls a Queue for Connection objects.
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).
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.
This file is part of web2py Web Framework (Copyrighted, 2007-2009). Developed by Massimo Di Pierro <mdipierro@cs.depaul.edu>. License: GPL v2
This file is part of web2py Web Framework (Copyrighted, 2007-2009). Developed by Massimo Di Pierro <mdipierro@cs.depaul.edu>. License: GPL v2
This file is part of web2py Web Framework (Copyrighted, 2007-2009). Developed by Massimo Di Pierro <mdipierro@cs.depaul.edu>. License: GPL v2
Holds:
Bases: gluon.sqlhtml.FormWidget
generates an INPUT checkbox tag.
see also: FormWidget.widget()
Bases: gluon.sqlhtml.OptionsWidget
generates a TABLE tag, including INPUT checkboxes (multiple allowed)
see also: FormWidget.widget()
Bases: object
helper for SQLFORM to generate form input fields (widget), related to the fieldtype
generates the widget for the field.
When serialized, will provide an INPUT tag:
Parameters: |
|
---|
Bases: gluon.sqlhtml.OptionsWidget
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 |
---|
Bases: gluon.sqlhtml.FormWidget
checks if the field has selectable options
Parameter: | field – the field needing checking |
---|---|
Returns: | True if the field has options |
generates a SELECT tag, including OPTIONs (only 1 option allowed)
see also: FormWidget.widget()
Bases: gluon.sqlhtml.FormWidget
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()
Bases: gluon.sqlhtml.OptionsWidget
generates a TABLE tag, including INPUT radios (only 1 option allowed)
see also: FormWidget.widget()
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: |
|
---|
generates a SQLFORM for the given fields.
Internally will build a non-database based data model to hold the fields.
Bases: gluon.html.TABLE
given a SQLRows object, as returned by a db().select(), generates an html table with the rows.
optional arguments:
Parameters: |
|
---|
optional names attributes for passed to the <table> tag
Bases: gluon.sqlhtml.FormWidget
generates an INPUT text tag.
see also: FormWidget.widget()
Bases: gluon.sqlhtml.FormWidget
generates a TEXTAREA tag.
see also: FormWidget.widget()
Bases: gluon.sqlhtml.FormWidget
Tries to check if the filename provided references to an image
Parameter: | value – filename |
---|
how to represent the file:
Parameters: |
|
---|
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) |
---|
generates a SQLFORM for the given fields.
Internally will build a non-database based data model to hold the fields.
This file is part of web2py Web Framework (Copyrighted, 2007-2009). Developed by Massimo Di Pierro <mdipierro@cs.depaul.edu>. License: GPL v2
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'
Bases: object
Class for authentication, authorization, role based access control.
Includes:
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:
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
...
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)
returns a form that lets the user change password
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)
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)
usage:
auth.log_event(description='this happened',origin='auth')
returns a login form
logout and redirects to login
returns a form that lets the user change his/her profile
returns a registration form
returns a form to retrieve the user password
returns a form to retrieve the user username (only if there is a username field)
action user to verify the registration email, XXXXXXXXXXXXXXXX
Bases: gluon.html.DIV
Bases: object
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
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
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
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
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
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
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
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
This file is part of web2py Web Framework (Copyrighted, 2007-2009). Developed by Massimo Di Pierro <mdipierro@cs.depaul.edu>. License: GPL v2
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!
This file is part of web2py Web Framework (Copyrighted, 2007-2009). Developed by Massimo Di Pierro <mdipierro@cs.depaul.edu>. License: GPL v2
This file is part of web2py Web Framework (Copyrighted, 2007-2009). Developed by Massimo Di Pierro <mdipierro@cs.depaul.edu>. License: GPL v2
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.
Bases: gluon.storage.Storage
defines the ticket object and the default values of its members (None)
This file is part of web2py Web Framework (Copyrighted, 2007-2009). Developed by Massimo Di Pierro <mdipierro@cs.depaul.edu>. License: GPL v2
Bases: exceptions.BaseException
This file is part of web2py Web Framework (Copyrighted, 2007-2009). Developed by Massimo Di Pierro <mdipierro@cs.depaul.edu>. License: GPL v2
Provides:
Bases: list
Like a regular python list but a[i] if i is out of bounds return None instead of IndexOutOfBounds
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
This file is part of web2py Web Framework (Copyrighted, 2007-2009). Developed by Massimo Di Pierro <mdipierro@cs.depaul.edu>. License: GPL v2
This file is part of web2py Web Framework (Copyrighted, 2007-2009). Developed by Massimo Di Pierro <mdipierro@cs.depaul.edu>. License: GPL v2
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)
# 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
This file is part of web2py Web Framework (Copyrighted, 2007-2009). Developed by Massimo Di Pierro <mdipierro@cs.depaul.edu>. License: GPL v2
Contains:
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.
The url path must be either:
- /<application>/static/<file>
/<application>[/<controller>[/<function>[/<sub>]]][.<extension>]
- (sub may go several levels deep, currently 3 levels are supported:
sub1/sub2/sub3)
The naming conventions are:
generates a wsgi application that does logging and profiling and calls wsgibase
Bases: object
the web2py web server (wsgiserver)
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.
Bases: object
Main window dialog
This file is part of web2py Web Framework (Copyrighted, 2007-2009). Developed by Massimo Di Pierro <mdipierro@cs.depaul.edu>. License: GPL v2
This file is part of web2py Web Framework (Copyrighted, 2007-2009). Developed by Massimo Di Pierro <mdipierro@cs.depaul.edu>. License: GPL v2
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.
Bases: gluon.html.DIV
displays code in HTML with syntax highlighting.
Parameter: | attributes – optional attributes:
|
---|
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.
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
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.
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.
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
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: |
|
---|
Bases: gluon.html.DIV
UL Component.
If subcomponents are not LI-components they will be wrapped in a LI
see also DIV
Bases: gluon.html.DIV
Used to build menus
Bases: gluon.html.DIV
Will replace \n by <br /> if the cr2br attribute is provided.
see also DIV
Bases: gluon.html.DIV
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>'
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
TAG factory example:
>>> print TAG.first(TAG.second('test'), _key = 3)
<first key="3"><second>test</second></first>
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.
Bases: gluon.html.DIV
TR Component.
If subcomponents are not TD/TH-components they will be wrapped in a TD
see also DIV
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: |
|
---|---|
Raises SyntaxError: | |
when no application, controller or function is available |
|
Raises SyntaxError: | |
when a CRLF is found in the generated url |
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>'
returns an escaped string of the provided data
Parameters: |
|
---|
helper to encode the provided (binary) data into base64.
Parameters: |
|
---|
This file is part of web2py Web Framework (Copyrighted, 2007-2009). Developed by Massimo Di Pierro <mdipierro@cs.depaul.edu>. License: GPL v2