WEB2PY 2.
0 Cheat Sheet
[Link]
Database Abstraction Layer
db = DAL('sqlite://[Link]',pool_size=1) db.define_table('thing', Field('name','string')) id = [Link](name='max') query = [Link]('m')&([Link]==1) db(query).update(name='max') db(query).delete() things = db(query).select([Link], orderby=~[Link], groupby=[Link] dictinct=True, cache=([Link],60)) thing = [Link](id) or redirect(URL('error')) thing.update_record(name='max') things.export_to_csv_file(open(filename,'wb')) [Link].import_from_csv_file(open(filename,'rb'))
Forms
form = SQLFORM([Link],record=None) form = [Link](Field('name')) (no db) form = [Link](d) (for d={...}) form = SQLFORM([Link]).process() if [Link]: ... elif [Link]: ...
URL Parsing
[Link] (admin interface) [Link] (app static le) [Link] (database interface) [Link] host request.http_host port request.http_port app [Link] c [Link] f [Link] e [Link] args [Link] (list) vars [Link] (dict) c/f.e [Link]
Grids
grid = [Link](query) grid = [Link](table, linked_tables=[]) [Link]( query, fields=None, field_id=None, left=None, headers={}, orderby=None, searchable=True, sortable=True, paginate=20, deletable=True, editable=True, details=True, selectable=None, create=True, csv=True, links=None, ...)
Field Types
string, text, boolean, integer, double, decimal(n,m), date, time, datetime, password, upload, blob, list:string, list:integer, reference table, list:reference table
Global Objects
[Link]
application, controller, function, now, client, is_local, is_https, ajax, args, vars, get_vars, post_vars, [Link], env.path_info, env.query_string, env.http_*, env.wsgi_*
Field Attributes
Field(fieldname, type='string', length=None, default=None, required=False, requires=None, 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, uploadfolder=None, uploadseparate=False, compute=None, ...)
Auth
@auth.requires_login() @auth.requires_membership('groupname') @auth.requires_premission('edit','tablename',id) @[Link](condition) auth.(has|add|del)_membership(...) auth.(has|add|del)_permission(...)
[Link]
status=200, view='[Link]', flash='flash me', js = 'alert("run me")', download(request,db), stream(file), render(template,**vars)
Full Example
models/[Link]
from [Link] import * db = DAL('sqlite://[Link]') auth = Auth(db) auth.define_tables() db.define_table('thing', Field('name',requires=IS_NOT_EMPTY()), [Link]) auth.enable_record_versioning(db) # for full db auditing
Validators
CLEANUP, CRYPT, IS_ALPHANUMERIC, IS_DATE, IS_DATETIME, IS_DATETIME_IN_RANGE, IS_DATE_IN_RANGE, IS_DECIMAL_IN_RANGE, IS_EMAIL, IS_EMPTY_OR, IS_EQUAL_TO, IS_EXPR, IS_FLOAT_IN_RANGE, IS_GENERIC_URL, IS_HTTP_URL, IS_IMAGE, IS_INT_IN_RANGE, IS_IN_DB, IS_IN_SET, IS_IN_SUBSET, IS_IPV4, IS_LENGTH, IS_LIST_OF, IS_LOWER, IS_MATCH, IS_NOT_EMPTY, IS_NOT_IN_DB, IS_NULL_OR, IS_SLUG, IS_STRONG, IS_TIME, IS_UPLOAD_FILENAME, IS_UPPER, IS_URL
[Link]
connect(request,response,db,separate=False), flash, secure(), forget(), _unlock(response)
cache
@cache('key',3600,[Link]) @cache('key',3600,[Link]) [Link](regex='k.*')
Helpers
A, B, BEAUTIFY, BODY, BR, CAT, CENTER, CODE, COL, COLGROUP, DIV, EM, EMBED, FIELDSET, FORM, H1, H2, H3, H4, H5, H6, HEAD, HR, HTML, I, IFRAME, IMG, INPUT, LABEL, LEGEND, LI, LINK, MARKMIN, MENU, META, OBJECT, ON, OL, OPTGROUP, OPTION, P, PRE, SCRIPT, SELECT, SPAN, STYLE, TABLE, TAG, TBODY, TD, TEXTAREA, TFOOT, TH, THEAD, TITLE, TR, TT, UL, XHTML, XML DIV(SPAN('hello'),_id='myid',_class='myclass') A('link',_href=URL(...)) SPAN(A('link',callback=URL(...),delete='span')) TABLE(*[TR(TD(item)) for item in [...]]) div = DIV(SPAN('hello',_id='x')) [Link]('span#x').append("world") [Link]('span#x')['_class'] = 'myclass' DIV('1<2').xml()==DIV(XML('1<2',sanitize=True)).xml() div = [Link]([Link]('hello',_id='x')) div = TAG('<div><span id="hello">hello</span></div>')
controllers/[Link]
def index(): return [Link]() # embed a wiki def download(): return [Link](request,db) def user(): return dict(form=auth) # login/etc. @auth requires_login() def manage_things(): # access you data grid = [Link]([Link].created_by==[Link]) return locals()
T (internationalization)
T('hello %(key)s',dict(key='thing')) T.current_languages = ['en'] (no translate) [Link]('en') (use languages/[Link])
URL, redirect, and HTTP
URL('function') URL('controller','function') URL('app','controller','function') URL('function',args=[...],vars={...}) URL('function',scheme=True) (full url) URL('function',user_signature=True) (then use @auth.requires_signature()) redirect(URL('index')) raise HTTP(500,'message')
views/default/manage [Link]
{{extend '[Link]'}} <h1>Your things</h1> {{=grid}} {{# any python between double braces}}
Copyleft 2012 Massimo Di Pierro
Generic views
[Link] [Link] [Link] [Link] # google map [Link] # html -> pdf [Link] [Link]
from ....ldap_auth import * [Link].login_methods.append(ldap_auth( mode='ad', server='[Link]', base_dn='ou=Users,dc=domain,dc=com')) from ....pam_auth import * [Link].login_methods.append(pam_auth()) from ....openid_auth import * [Link].login_form = OpenIDAuth(auth) from ....email_auth import * [Link].login_methods.append( email_auth("[Link]","@[Link]")) from ....browserid_account import * [Link].login_form = BrowserID(request, audience = "[Link] assertion_post_url = '[Link] from ....dropbox_account import * [Link].login_form = DropboxAccount(request, key="...",secret="...",access_type="...", url = "[Link] from ....rpx_account import * [Link].login_form = RPXAccount(request, api_key="...",domain="...", url='[Link] from ....x509_auth import * [Link].login_form = X509Account()
Deployment
[Link] -i ip -p port -a password [Link] -S app -M -N -R [Link] (run script) [Link] -S app -M -N (shell) [Link] -K app (task queue worker) [Link] -s server (third party server) servers: bjoern, cgi, cherrypy, diesel, eventlet, fapws, up, gevent, gnuicorn, mongrel2, paste, rocket, tornado, twisted, wsgiref
Web services
from [Link] import Service service = service() def call(): return service() @[Link] @[Link] @[Link] @[Link] @[Link] @service.amfrpc3('domain') @[Link]('name',args={'x':int},returns={'y':int}) @[Link]
Apache + mod proxy
sudo aptitude install libapache2-mod-proxy-html sudo a2enmod proxy cd /etc/apache2 sudo ln -s mods-available/proxy_http.load \ mods-enabled/proxy_http.load In VirutualHost: ProxyRequests off ProxyPass /myapp [Link] ProxyHTMLURLMap [Link] /myapp
REST
@[Link]() def index(): def GET(a,b,c): return dict() def PUT(a,b,c): return dict() def POST(a,b,c): return dict() def DELETE(a,b,c): return dict() return locals()
Apache + mod wsgi
sudo apt-get install libapache2-mod-wsgi sudo a2enmod wsgi In VirutualHost: DocumentRoot /path/web2py/ WSGIScriptAlias / /path/web2py/[Link] WSGIDaemonProcess web2py user=apache group=web2py \ home=/path/web2py/ processes=5 <LocationMatch "(/[\w_]*/static/.*)"> Order Allow,Deny Allow from all </LocationMatch> <Location ""/"> Order deny,allow Allow from all WSGIProcessGroup web2py </Location>
Payment Systems
Google wallet button
from [Link].google_wallet import button {{=button(merchant_id="123456789012345", products=[dict(name="shoes", quantity=1, price=23.5, currency='USD', description="running shoes black")])}}
MARKMIN
text = """ # section ## subsection **bold** ''italic'' code , what :up ----------------------------------------------image | [Link] audio | [Link] video | [Link] iframe | embed:[Link] -------------------------------------:css_class @{variable} and @{controller/function/args}""" {{=MARKMIN(text, url=True,environment=dict(variable='x'), extra=dict(up=lambda t:[Link]([Link]())))}}
Stripe
from [Link] import Stripe Stripe(key).charge(amount=100,currency='usd', card_number='4242424242424242', card_exp_month='5',card_exp_year='2012', card_cvc_check='123', description='test charge') Stripe(key).check(d['id']) Stripe(key).refund(d['id'])
Login Methods
from [Link].login_methods.basic_auth import * [Link].login_methods.append( basic_auth('[Link]
[Link]
from [Link] import process process(card_number,expiration,total,cvv=None, tax=None,invoice=None, login='cnpdev4289', transkey='SR2P8g4jdEn7vFLQ',testmode=True)
uWSGI
hg clone [Link] cd uwsgi; make -f Makefile.Py27 uwsgi/uwsgi --pythonpath /path/web2py --async 24 -t 20 \ --ugreen --module wsgihandler -s /tmp/[Link]