WEB2PY 2.
9 Cheat Sheet Database Abstraction Layer Forms
http://www.web2py.com db = DAL('sqlite://storage.sqlite',pool_size=1) form = SQLFORM(db.thing,record=None)
db.define_table('thing', Field('name','string')) form = SQLFORM.factory(Field('name')) (no db)
URL Parsing id = db.thing.insert(name='max') form = SQLFORM.dictform(d) (for d={...})
http://host:port/admin (admin interface) query = db.thing.name.contains('m')&(db.thing.id==1)
db(query).update(name='max') form = SQLFORM(db.thing).process()
http://host:port/app/static/file (app static file)
db(query).delete() if form.accepted: ...
http://host:port/app/appadmin (database interface)
things = db(query).select(db.thing.ALL, elif form.errors: ...
http://host:port/app/c/f(.e)/!args?vars
app → request.application orderby=~db.thing.name, groupby=db.thing.id
c → request.controller dictinct=True, cache=(cache.ram,60)) Grids
f → request.function thing = db.thing(id) or redirect(URL('error')) grid = SQLFORM.grid(query)
e → request.extension thing.update_record(name='max') grid = SQLFORM.smartgrid(table, linked_tables=[])
args → request.args (list) things.export_to_csv_file(open(filename,'wb'))
vars → request.vars (dict) db.thing.import_from_csv_file(open(filename,'rb')) SQLFORM.grid(
’c/f.e’ → response.view query, fields=None, field_id=None, left=None,
Field Types headers={}, orderby=None, searchable=True,
host → request.env.http_host
port → request.env.http_port string, text, boolean, integer, double, decimal(n,m), date, sortable=True, paginate=20, deletable=True,
time, datetime, password, upload, blob, json, list:string, editable=True, details=True, selectable=None,
Global Objects list:integer, reference table, list:reference table create=True, csv=True, links=None, ...)
request.obj Field Attributes
Field(fieldname, type='string', length=None,
Auth
application, controller, function, now, client, is_local, default=None, required=False, requires=None, @auth.requires_login()
is_https, ajax, args, vars, get_vars, post_vars, ondelete='CASCADE', notnull=False, unique=False, @auth.requires_membership('groupname')
env.request_method, env.path_info, env.query_string, uploadfield=True, widget=None, label=None, @auth.requires_premission('edit','tablename',id)
env.http_*, env.wsgi_* comment=None, writable=True, readable=True, @auth.requires(condition)
update=None, authorize=None, autodelete=False, auth.(has|add|del)_membership(...)
response.obj represent=None, uploadfolder=None, auth.(has|add|del)_permission(...)
status=200, view='filename.html', flash='flash me', uploadseparate=False, compute=None, ...)
js = 'alert("run me")', download(request,db), Full Example
stream(file), render(template,**vars) Validators models/db.py
CLEANUP, CRYPT, IS_ALPHANUMERIC, IS_DATE, IS_DATETIME, from gluon.tools import *
session.obj IS_DATETIME_IN_RANGE, IS_DATE_IN_RANGE, db = DAL('sqlite://storage.sqlite')
connect(request,response,db,separate=False), IS_DECIMAL_IN_RANGE, IS_EMAIL, IS_EMPTY_OR, IS_EQUAL_TO, auth = Auth(db)
flash, secure(), forget(), _unlock(response) IS_EXPR, IS_FLOAT_IN_RANGE, IS_GENERIC_URL, IS_HTTP_URL, auth.define_tables()
IS_IMAGE, IS_INT_IN_RANGE, IS_IN_DB, IS_IN_SET, db.define_table('thing',
cache IS_IN_SUBSET, IS_IPV4, IS_LENGTH, IS_LIST_OF, IS_LOWER, Field('name',requires=IS_NOT_EMPTY()), auth.signature)
@cache('key',3600,cache.ram) IS_MATCH, IS_NOT_EMPTY, IS_NOT_IN_DB, IS_NULL_OR, IS_SLUG, auth.enable_record_versioning(db) # for full db auditing
@cache('key',3600,cache.disk) IS_STRONG, IS_TIME, IS_UPLOAD_FILENAME, IS_UPPER, IS_URL
cache.ram.clear(regex='k.*') controllers/default.py
Helpers def index(): return auth.wiki() # embed a wiki
T (internationalization) A, B, BEAUTIFY, BODY, BR, CAT, CENTER, CODE, COL, COLGROUP, def download(): return response.download(request,db)
DIV, EM, EMBED, FIELDSET, FORM, H1, H2, H3, H4, H5, H6, HEAD, HR, def user(): return dict(form=auth) # login/etc.
T('hello %(key)s',dict(key='thing')) HTML, I, IFRAME, IMG, INPUT, LABEL, LEGEND, LI, LINK, MARKMIN,
T.current_languages = ['en'] (no translate) MENU, META, OBJECT, ON, OL, OPTGROUP, OPTION, P, PRE, SCRIPT,
T.force('en') (use languages/en.py) @auth requires_login()
SELECT, SPAN, STYLE, TABLE, TAG, TBODY, TD, TEXTAREA, TFOOT, def manage_things(): # access you data
TH, THEAD, TITLE, TR, TT, UL, XHTML, XML grid = SQLFORM.grid(db.thing.created_by==auth.user.id)
URL, redirect, and HTTP
DIV(SPAN('hello'),_id='myid',_class='myclass') return locals()
URL('function')
A('link',_href=URL(...))
URL('controller','function') views/default/manage things.html
SPAN(A('link',callback=URL(...),delete='span'))
URL('app','controller','function')
TABLE(*[TR(TD(item)) for item in [...]]) {{extend 'layout.html'}}
URL('function',args=[...],vars={...})
div = DIV(SPAN('hello',_id='x')) <h1>Your things</h1>
URL('function',scheme=True) (full url)
div.element('span#x').append("world") {{=grid}}
URL('function',user_signature=True)
div.element('span#x')['_class'] = 'myclass' {{# any python between double braces}}
(then use @auth.requires_signature())
DIV('1<2').xml()==DIV(XML('1<2',sanitize=True)).xml()
redirect(URL('index'))
div = TAG.DIV(TAG.SPAN('hello',_id='x'))
raise HTTP(500,'message') Copyleft 2014 Massimo Di Pierro
div = TAG('<div><span id="hello">hello</span></div>')
Generic views @{variable} and @{controller/function/args}""" Payment Systems
generic.html {{=MARKMIN(text,
url=True,environment=dict(variable='x'),
Stripe
generic.rss
extra=dict(up=lambda t:cgi.escape(t.upper())))}} from gluon.contrib.stripe import StripeForm
generic.ics
form = StripeForm(
generic.map # google map
pk=STRIPE_PUBLISHABLE_KEY,
generic.pdf # html -> pdf
generic.json
Login Methods sk=STRIPE_SECRET_KEY,
from gluon.contrib.login_methods.basic_auth import * amount=150, # (amount is in cents)
generic.jsonp
auth.settings.login_methods.append( description="Nothing").process()
basic_auth('http://server')) if form.accepted: payment_id = form.response['id']
Web services
from gluon.tools import Service from ....ldap_auth import * Google wallet button
service = service() auth.settings.login_methods.append(ldap_auth( from gluon.contrib.google_wallet import button
def call(): return service() mode='ad', server='my.domain.controller', {{=button(merchant_id="123456789012345",
@service.rss base_dn='ou=Users,dc=domain,dc=com')) products=[dict(name="shoes",
@service.xml
quantity=1, price=23.5, currency='USD',
@service.json from ....pam_auth import * description="running shoes black")])}}
@service.xmlrpc auth.settings.login_methods.append(pam_auth())
@service.jsonrpc
@service.amfrpc3('domain')
from ....openid_auth import * Deployment
@service.soap('name',args={'x':int},returns={'y':int}) web2py.py -i ip -p port -a password
auth.settings.login_form = OpenIDAuth(auth)
@service.run web2py.py -S app -M -N -R script.py (run script)
from ....email_auth import * web2py.py -S app -M -N (shell)
REST auth.settings.login_methods.append( web2py.py -K app (task queue worker)
@request.restful() email_auth("smtp.gmail.com:587","@gmail.com")) anyserver.py -s server (third party server)
def index(): servers: bjoern, cgi, cherrypy, diesel, eventlet, fapws, flup,
def GET(a,b,c): return dict() from ....browserid_account import * gevent, gnuicorn, mongrel2, paste, rocket, tornado, twisted,
def PUT(a,b,c): return dict() auth.settings.login_form = BrowserID(request, wsgiref
def POST(a,b,c): return dict() audience = "http://127.0.0.1:8000" Setup Scripts
def DELETE(a,b,c): return dict() assertion_post_url = 'http://...//user/login')
return locals() from
https://github.com/web2py/web2py/tree/master/scripts
from ....dropbox_account import *
MARKMIN auth.settings.login_form = DropboxAccount(request, setup-scheduler-centos.sh
text = """ key="...",secret="...",access_type="...", setup-web2py-centos7.sh
# section url = "http://.../user/login') setup-web2py-debian-sid.sh
## subsection setup-web2py-fedora-ami.sh
**bold** ''italic'' ``code``, ``what``:up from ....janrain_account import * setup-web2py-fedora.sh
----------------------------------------------- auth.settings.login_form = RPXAccount(request, setup-web2py-heroku.sh
image | http://example.com/image.jpg api_key="...",domain="...", setup-web2py-nginx-uwsgi-centos64.sh
audio | http://example.com/audio.mp3 url='http://.../user/login' setup-web2py-nginx-uwsgi-on-centos.sh
video | http://example.com/video.mp4 setup-web2py-nginx-uwsgi-opensuse.sh
iframe | embed:http://example.com/page.html from ....x509_auth import * setup-web2py-nginx-uwsgi-ubuntu.sh
-------------------------------------:css_class auth.settings.login_form = X509Account() setup-web2py-ubuntu.sh