fixed examples in examples

This commit is contained in:
Massimo Di Pierro committed 2011-11-23 16:35:10 -06:00
1 parent f43fa28e29
commit 113095c3ac
19 files changed
+470 -528

No files matched your search

+1 -1
View File
@@ -1 +1 @@
Version 1.99.3 (2011-11-23 15:05:14) dev Version 1.99.3 (2011-11-23 16:35:01) dev
@@ -1,7 +1,3 @@
def index(): def index():
return dict() return dict()
@@ -1,51 +1,50 @@
from gluon.fileutils import read_file from gluon.fileutils import read_file
response.menu = [['Register User', False, URL(r=request, response.menu = [['Register Person', False, URL('register_person')],
f='register_user')], ['Register Dog', False, ['Register Dog', False, URL('register_dog')],
URL('register_dog')], ['Register Product' ['Register Product', False, URL('register_product')],
, False, URL('register_product')],
['Buy product', False, URL('buy')]] ['Buy product', False, URL('buy')]]
def register_user(): def register_person():
""" simple user registration form with validation and database.insert() """ simple person registration form with validation and database.insert()
also lists all records currently in the table""" also lists all records currently in the table"""
# ## create an insert form from the table # create an insert form from the table
form = SQLFORM(db.person)
form = SQLFORM(db.users) # if form correct perform the insert
if form.process().accepted:
# ## if form correct perform the insert
if form.accepts(request.vars, session):
response.flash = 'new record inserted' response.flash = 'new record inserted'
# ## and get a list of all users # and get a list of all persons
records = SQLTABLE(db().select(db.person.ALL),headers='fieldname:capitalize')
records = SQLTABLE(db().select(db.users.ALL))
return dict(form=form, records=records) return dict(form=form, records=records)
def register_dog(): def register_dog():
""" simple user registration form with validation and database.insert() """ simple person registration form with validation and database.insert()
also lists all records currently in the table""" also lists all records currently in the table"""
form = SQLFORM(db.dogs) form = SQLFORM(db.dog)
if form.accepts(request.vars, session): if form.process().accepted:
response.flash = 'new record inserted' response.flash = 'new record inserted'
download = URL('download') # to see the picture download = URL('download') # to see the picture
records = SQLTABLE(db().select(db.dogs.ALL), upload=download) records = SQLTABLE(db().select(db.dog.ALL), upload=download,
headers='fieldname:capitalize')
return dict(form=form, records=records) return dict(form=form, records=records)
def register_product(): def register_product():
""" simple user registration form with validation and database.insert() """ simple person registration form with validation and database.insert()
also lists all records currently in the table""" also lists all records currently in the table"""
form = SQLFORM(db.products) form = SQLFORM(db.product)
if form.accepts(request.vars, session): if form.process().accepted:
response.flash = 'new record inserted' response.flash = 'new record inserted'
records = SQLTABLE(db().select(db.products.ALL)) records = SQLTABLE(db().select(db.product.ALL),
headers='fieldname:capitalize')
return dict(form=form, records=records) return dict(form=form, records=records)
@@ -53,100 +52,38 @@ def buy():
""" uses a form to query who is buying what. validates form and """ uses a form to query who is buying what. validates form and
updates existing record or inserts new record in purchases """ updates existing record or inserts new record in purchases """
buyerRecords = db().select(db.users.ALL) form = SQLFORM.factory(
buyerOptions = [] Field('buyer_id',requires=IS_IN_DB(db,db.person.id,'%(name)s')),
for row in buyerRecords: Field('product_id',requires=IS_IN_DB(db,db.product.id,'%(name)s')),
buyerOptions.append(OPTION(row.name, _value=row.id)) Field('quantity','integer',requires=IS_INT_IN_RANGE(1,100)))
if form.process().accepted:
# get previous purchese
purchase = db((db.purchase.buyer_id == form.vars.buyer_id)&
(db.purchase.product_id==form.vars.product_id)).select().first()
productRecords = db().select(db.products.ALL) if purchase:
productOptions = [] # if list contains a record, update that record
for row in productRecords: purchase.update_record(
productOptions.append(OPTION(row.name, _value=row.id)) quantity = purchase.quantity+form.vars.quantity)
else:
form = FORM(TABLE( # self insert a new record in table
TR('Buyer id:', db.purchase.insert(buyer_id=form.vars.buyer_id,
SELECT(buyerOptions,_name='buyer_id')), product_id=form.vars.product_id,
TR('Product id:', quantity=form.vars.quantity)
SELECT(productOptions,_name='product_id')), response.flash = 'product purchased!'
TR('Quantity:', elif form.errors:
INPUT(_type='text', _name='quantity',
requires=IS_INT_IN_RANGE(1, 100))),
TR('',
INPUT(_type='submit', _value='Order'))
))
if form.accepts(request.vars, session, keepvalues=True):
# ## check if user is in the database
if len(db(db.users.id == form.vars.buyer_id).select()) == 0:
form.errors.buyer_id = 'buyer not in database'
# ## check if product is the database
if len(db(db.products.id == form.vars.product_id).select())\
== 0:
form.errors.product_id = 'product not in database'
# ## if no errors
if len(form.errors) == 0:
# ## get a list of same purchases by same user
purchases = db((db.purchases.buyer_id == form.vars.buyer_id)
& (db.purchases.product_id
== form.vars.product_id)).select()
# ## if list contains a record, update that record
if len(purchases) > 0:
purchases[0].update_record(quantity=purchases[0].quantity
+ form.vars.quantity)
else:
# ## or insert a new record in table
db.purchases.insert(buyer_id=form.vars.buyer_id,
product_id=form.vars.product_id,
quantity=form.vars.quantity)
response.flash = 'product purchased!'
if len(form.errors):
response.flash = 'invalid values in form!' response.flash = 'invalid values in form!'
# ## now get a list of all purchases # now get a list of all purchases
records = SQLTABLE(db(purchased).select(),headers='fieldname:capitalize')
# quick fix to make it runnable on gae return dict(form=form, records=records)
if purchased:
records = db(purchased).select(db.users.name,
db.purchases.quantity,
db.products.name)
else:
records = db().select(db.purchases.ALL)
return dict(form=form, records=SQLTABLE(records), vars=form.vars,
vars2=request.vars)
def delete_purchased(): def delete_purchased():
""" delete all records in purchases """ """ delete all records in purchases """
db(db.purchase.id > 0).delete()
db(db.purchases.id > 0).delete()
redirect(URL('buy')) redirect(URL('buy'))
def reset_purchased():
""" set quantity=0 for all records in purchases """
db(db.purchases.id > 0).update(quantity=0)
redirect(URL('buy'))
def download(): def download():
""" used to download uploaded files """ """ used to download uploaded files """
return response.download(request,db)
import gluon.contenttype
app = request.application
filename = request.args[0]
response.headers['Content-Type'] = \
gluon.contenttype.contenttype(filename)
return read_file('applications/%s/uploads/%s' % (app, filename), 'rb')
+11 -11
View File
@@ -8,11 +8,11 @@ response.description = T('web2py Web Framework')
session.forget() session.forget()
@cache('index') #@cache('index')
def index(): def index():
return response.render() return response.render()
@cache('what') #@cache('what')
def what(): def what():
import urllib; import urllib;
try: try:
@@ -21,30 +21,30 @@ def what():
images = [] images = []
return response.render(images=images) return response.render(images=images)
@cache('download') #@cache('download')
def download(): def download():
return response.render() return response.render()
@cache('who') #@cache('who')
def who(): def who():
return response.render() return response.render()
@cache('support') #@cache('support')
def support(): def support():
return response.render() return response.render()
@cache('documentation') #@cache('documentation')
def documentation(): def documentation():
return response.render() return response.render()
@cache('usergroups') #@cache('usergroups')
def usergroups(): def usergroups():
return response.render() return response.render()
def contact(): def contact():
redirect(URL('default','usergroups')) redirect(URL('default','usergroups'))
@cache('videos') #@cache('videos')
def videos(): def videos():
return response.render() return response.render()
@@ -54,7 +54,7 @@ def security():
def api(): def api():
redirect('http://web2py.com/book/default/chapter/04#API') redirect('http://web2py.com/book/default/chapter/04#API')
@cache('license') #@cache('license')
def license(): def license():
import os import os
filename = os.path.join(request.env.gluon_parent, 'LICENSE') filename = os.path.join(request.env.gluon_parent, 'LICENSE')
@@ -63,11 +63,11 @@ def license():
def version(): def version():
return 'Version %s.%s.%s (%s) %s' % request.env.web2py_version return 'Version %s.%s.%s (%s) %s' % request.env.web2py_version
@cache('examples') #@cache('examples')
def examples(): def examples():
return response.render() return response.render()
@cache('changelog') #@cache('changelog')
def changelog(): def changelog():
import os import os
filename = os.path.join(request.env.gluon_parent, 'CHANGELOG') filename = os.path.join(request.env.gluon_parent, 'CHANGELOG')
@@ -1,6 +1,3 @@
def civilized(): def civilized():
response.menu = [['civilized', True, URL('civilized' response.menu = [['civilized', True, URL('civilized'
)], ['slick', False, URL('slick')], )], ['slick', False, URL('slick')],
@@ -39,7 +39,7 @@ def hello6():
def status(): def status():
""" page that shows internal status""" """ page that shows internal status"""
response.view = 'generic.html' response.view = 'generic.html'
return dict(request=request, session=session, response=response) return dict(toolbar=response.toolbar())
def redirectme(): def redirectme():
@@ -18,52 +18,55 @@ else:
db = DAL('sqlite://storage.sqlite') db = DAL('sqlite://storage.sqlite')
db.define_table( db.define_table(
'users', 'person',
Field('name'), Field('name'),
Field('email') Field('email'),
format = '%(name)s',
singular = 'Person',
plural = 'Persons',
) )
# ONE (users) TO MANY (dogs) # ONE (person) TO MANY (dogs)
db.define_table( db.define_table(
'dogs', 'dog',
Field('owner_id', db.users), Field('owner_id', db.person),
Field('name'), Field('name'),
Field('type'), Field('type'),
Field('vaccinated', 'boolean', default=False), Field('vaccinated', 'boolean', default=False),
Field('picture', 'upload', default=''), Field('picture', 'upload', default=''),
format = '%(name)s',
singular = 'Dog',
plural = 'Dogs',
) )
db.define_table( db.define_table(
'products', 'product',
Field('name'), Field('name'),
Field('description', 'text') Field('description', 'text'),
format = '%(name)s',
singular = 'Product',
plural = 'Products',
) )
# MANY (users) TO MANY (purchases) # MANY (persons) TO MANY (purchases)
db.define_table( db.define_table(
'purchases', 'purchase',
Field('buyer_id', db.users), Field('buyer_id', db.person),
Field('product_id', db.products), Field('product_id', db.product),
Field('quantity', 'integer') Field('quantity', 'integer'),
format = '%(quantity)s %(product_id)s -> %(buyer_id)s',
singular = 'Purchase',
plural = 'Purchases',
) )
# if running on Google App Engine purchased = \
if settings.web2py_runtime_gae: (db.person.id==db.purchase.buyer_id)&\
# quick hack to skip the join (db.product.id==db.purchase.product_id)
purchased = None
else:
# use a joined view
purchased = (db.users.id == db.purchases.buyer_id) & (db.products.id
== db.purchases.product_id)
db.users.name.requires = IS_NOT_EMPTY() db.person.name.requires = IS_NOT_EMPTY()
db.users.email.requires = [IS_EMAIL(), IS_NOT_IN_DB(db, 'users.email')] db.person.email.requires = [IS_EMAIL(), IS_NOT_IN_DB(db, 'person.email')]
db.dogs.owner_id.requires = IS_IN_DB(db, 'users.id', 'users.name') db.dog.name.requires = IS_NOT_EMPTY()
db.dogs.name.requires = IS_NOT_EMPTY() db.dog.type.requires = IS_IN_SET(('small', 'medium', 'large'))
db.dogs.type.requires = IS_IN_SET(['small', 'medium', 'large']) db.purchase.quantity.requires = IS_INT_IN_RANGE(0, 10)
db.purchases.buyer_id.requires = IS_IN_DB(db, 'users.id', 'users.name')
db.purchases.product_id.requires = IS_IN_DB(db, 'products.id',
'products.name')
db.purchases.quantity.requires = IS_INT_IN_RANGE(0, 10)
@@ -19,4 +19,4 @@ input:focus,textarea:focus {background:#f0f0f0!important}
table.downloads { width:100%; } table.downloads { width:100%; }
table.downloads th, table.downloads td {text-align:center;} table.downloads th, table.downloads td {text-align:center;}
table.downloads a.button { width: 150px; } table.downloads a.button { width: 150px; }
th,td {padding-right: 10px;}
+1 -1
View File
@@ -77,7 +77,7 @@ fieldset { padding: 16px; border-top: 1px #DEDEDE solid;}
fieldset legend {text-transform:uppercase; font-weight: bold; padding: 4px 16px 4px 16px; background: #f1f1f1;} fieldset legend {text-transform:uppercase; font-weight: bold; padding: 4px 16px 4px 16px; background: #f1f1f1;}
/* fix ie problem with menu */ /* fix ie problem with menu */
.ie-lte7 .topbar {z-index: 2; } .ie-lte7 .topbar .container {z-index: 2; }
td.w2p_fw {padding-bottom: 1em;} td.w2p_fw {padding-bottom: 1em;}
td.w2p_fl, td.w2p_fw, td.w2p_fc { vertical-align:top; } td.w2p_fl, td.w2p_fw, td.w2p_fc { vertical-align:top; }
@@ -1,7 +1,6 @@
{{extend 'layout_examples/layout_civilized.html'}} {{extend 'layout.html'}}
<h1>Purchase form</h1> <h1>Purchase form</h1>
{{=form}} {{=form}}
[ {{=A('reset purchased',_href=URL('reset_purchased'))}} | [ {{=A('delete purchases',_href=URL('delete_purchased'))}} ]
{{=A('delete purchased',_href=URL('delete_purchased'))}} ]<br/>
<h2>Current purchases (SQL JOIN!)</h2> <h2>Current purchases (SQL JOIN!)</h2>
<p>{{=records}}</p> <p>{{=records}}</p>
@@ -1,6 +1,6 @@
{{extend 'layout_examples/layout_civilized.html'}} {{extend 'layout.html'}}
<h1>Dog registration form</h1> <h1>Dog registration form</h1>
{{=form}} {{=form}}
<h2>Current dogs</h2> <h2>Current dogs</h2>
{{=records}} {{=records}}
@@ -1,6 +1,6 @@
{{extend 'layout_examples/layout_civilized.html'}} {{extend 'layout.html'}}
<h1>User registration form</h1> <h1>User registration form</h1>
{{=form}} {{=form}}
<h2>Current users</h2> <h2>Current users</h2>
{{=records}} {{=records}}
@@ -1,6 +1,6 @@
{{extend 'layout_examples/layout_civilized.html'}} {{extend 'layout.html'}}
<h1>Product registration form</h1> <h1>Product registration form</h1>
{{=form}} {{=form}}
<h2>Current products</h2> <h2>Current products</h2>
{{=records}} {{=records}}
@@ -16,13 +16,13 @@
<tr> <tr>
<td><a class="button" href="http://www.web2py.com/examples/static/web2py_win.zip">For Windows</a></td> <td><a class="button" href="http://www.web2py.com/examples/static/web2py_win.zip">For Windows</a></td>
<td><a class="button" href="http://www.web2py.com/examples/static/nightly/web2py_win.zip">For Windows</a></td> <td><a class="button" href="http://www.web2py.com/examples/static/nightly/web2py_win.zip">For Windows</a></td>
<td><a class="button" href="http://code.google.com/p/web2py/" target="_blank">Mercurial Repository</a></td> <td><a class="button" href="http://github.com/mdipierro/web2py/" target="_blank">Git Repository</a></td>
<td><a class="button" href="http://web2py.com/examples/static/web2py.plugin.wiki.w2p">Download</a></td> <td><a class="button" href="http://web2py.com/examples/static/web2py.plugin.wiki.w2p">Download</a></td>
</tr> </tr>
<tr> <tr>
<td><a class="button" href="http://www.web2py.com/examples/static/web2py_osx.zip">For Mac</a></td> <td><a class="button" href="http://www.web2py.com/examples/static/web2py_osx.zip">For Mac</a></td>
<td><a class="button" href="http://www.web2py.com/examples/static/nightly/web2py_osx.zip">For Mac</a></td> <td><a class="button" href="http://www.web2py.com/examples/static/nightly/web2py_osx.zip">For Mac</a></td>
<td><a class="button" href="http://code.google.com/p/web2py/issues/list" target="_blank">Issue Tracker</a></td> <td><a class="button" href="http://code.google.com/p/web2py/" target="_blank">Mercurial Repository</a></td>
<td><a class="button" href="http://code.google.com/p/cube2py/" target="_blank">Mercurial Repository</a> <td><a class="button" href="http://code.google.com/p/cube2py/" target="_blank">Mercurial Repository</a>
</tr> </tr>
<tr> <tr>
@@ -34,7 +34,8 @@
<tr> <tr>
<td><a class="button" href="{{=URL('changelog')}}">Change Log</a></td> <td><a class="button" href="{{=URL('changelog')}}">Change Log</a></td>
<td><a class="button" href="http://www.web2py.com/examples/static/nightly/tests.log">Unittest Log</a></td> <td><a class="button" href="http://www.web2py.com/examples/static/nightly/tests.log">Unittest Log</a></td>
<td></td><td></td> <td><a class="button" href="http://code.google.com/p/web2py/issues/list" target="_blank">Issue Tracker</a></td>
<td></td>
</tr> </tr>
</table> </table>
</center> </center>
+355 -346
View File
@@ -28,28 +28,28 @@
<h3>Example {{c=1}}{{=c}}{{c+=1}}</h3><b>In controller: simple_examples.py</b> <h3>Example {{c=1}}{{=c}}{{c+=1}}</h3><b>In controller: simple_examples.py</b>
{{=CODE(""" {{=CODE("""
def hello1(): def hello1():
return "Hello World" return "Hello World"
""".strip(),language='web2py',link=URL(r=request,c='global',f='vars'),_class='boxCode')}} """.strip(),language='web2py',link=URL('global','vars'),_class='boxCode')}}
<p>If the controller function returns a string, that is the body of the rendered page.<br/>Try it here: <a href="/{{=request.application}}/simple_examples/hello1">hello1</a></p> <p>If the controller function returns a string, that is the body of the rendered page.<br/>Try it here: <a href="/{{=request.application}}/simple_examples/hello1">hello1</a></p>
<h3>Example {{=c}}{{c+=1}}</h3><b>In controller: simple_examples.py</b> <h3>Example {{=c}}{{c+=1}}</h3><b>In controller: simple_examples.py</b>
{{=CODE(""" {{=CODE("""
def hello2(): def hello2():
return T("Hello World") return T("Hello World")
""".strip(),language='web2py',link=URL(r=request,c='global',f='vars'),_class='boxCode')}} """.strip(),language='web2py',link=URL('global','vars'),_class='boxCode')}}
<p>The function T() marks strings that need to be translated. Translation dictionaries can be created at /admin/default/design<br/>Try it here: <a href="/{{=request.application}}/simple_examples/hello2">hello2</a></p> <p>The function T() marks strings that need to be translated. Translation dictionaries can be created at /admin/default/design<br/>Try it here: <a href="/{{=request.application}}/simple_examples/hello2">hello2</a></p>
<h3>Example {{=c}}{{c+=1}}</h3><b>In controller: simple_examples.py</b> <h3>Example {{=c}}{{c+=1}}</h3><b>In controller: simple_examples.py</b>
{{=CODE(""" {{=CODE("""
def hello3(): def hello3():
return dict(message=T("Hello World")) return dict(message=T("Hello World"))
""".strip(),language='web2py',link=URL(r=request,c='global',f='vars'),_class='boxCode')}} """.strip(),language='web2py',link=URL('global','vars'),_class='boxCode')}}
<b>and view: simple_examples/hello3.html</b> <b>and view: simple_examples/hello3.html</b>
{{=CODE(open(os.path.join(request.folder,'views/simple_examples/hello3.html'),'r').read(),language='html',link=URL(r=request,c='global',f='vars'),_class='boxCode')}} {{=CODE(open(os.path.join(request.folder,'views/simple_examples/hello3.html'),'r').read(),language='html',link=URL('global','vars'),_class='boxCode')}}
<p>If you return a dictionary, the variables defined in the dictionery are visible to the view (template). <p>If you return a dictionary, the variables defined in the dictionery are visible to the view (template).
<br/>Try it here: <a href="/{{=request.application}}/simple_examples/hello3.html">hello3</a></p> <br/>Try it here: <a href="/{{=request.application}}/simple_examples/hello3.html">hello3</a></p>
@@ -57,18 +57,18 @@
<h3>Example {{=c}}{{c+=1}}</h3><b>In controller: simple_examples.py</b> <h3>Example {{=c}}{{c+=1}}</h3><b>In controller: simple_examples.py</b>
{{=CODE(""" {{=CODE("""
def hello4(): def hello4():
response.view='simple_examples/hello3.html' response.view='simple_examples/hello3.html'
return dict(message=T("Hello World")) return dict(message=T("Hello World"))
""".strip(),language='web2py',link=URL(r=request,c='global',f='vars'),_class='boxCode')}} """.strip(),language='web2py',link=URL('global','vars'),_class='boxCode')}}
<p>You can change the view, but the default is /[controller]/[function].html. If the default is not found web2py tries to render the page using the generic.html view. <p>You can change the view, but the default is /[controller]/[function].html. If the default is not found web2py tries to render the page using the generic.html view.
<br/>Try it here: <a href="/{{=request.application}}/simple_examples/hello4">hello4</a></p> <br/>Try it here: <a href="/{{=request.application}}/simple_examples/hello4">hello4</a></p>
<h3>Example {{=c}}{{c+=1}}</h3><b>In controller: simple_examples.py</b> <h3>Example {{=c}}{{c+=1}}</h3><b>In controller: simple_examples.py</b>
{{=CODE(""" {{=CODE("""
def hello5(): def hello5():
return HTML(BODY(H1(T('Hello World'),_style="color: red;"))).xml() # .xml to serialize return HTML(BODY(H1(T('Hello World'),_style="color: red;"))).xml() # .xml to serialize
""".strip(),language='web2py',link=URL(r=request,c='global',f='vars'),_class='boxCode')}} """.strip(),language='web2py',link=URL('global','vars'),_class='boxCode')}}
<p>You can also generate HTML using helper objects HTML, BODY, H1, etc. Each of these tags is a class and the views know how to render the corresponding objects. The method .xml() serializes them and produce html/xml code for the page. <p>You can also generate HTML using helper objects HTML, BODY, H1, etc. Each of these tags is a class and the views know how to render the corresponding objects. The method .xml() serializes them and produce html/xml code for the page.
Each tag, DIV for example, takes three types of arguments:</p> Each tag, DIV for example, takes three types of arguments:</p>
<ul> <ul>
@@ -80,54 +80,54 @@
<h3>Example {{=c}}{{c+=1}}</h3><b>In controller: simple_examples.py</b> <h3>Example {{=c}}{{c+=1}}</h3><b>In controller: simple_examples.py</b>
{{=CODE(""" {{=CODE("""
def hello6(): def hello6():
response.flash=T("Hello World in a flash!") response.flash=T("Hello World in a flash!")
return dict(message=T("Hello World")) return dict(message=T("Hello World"))
""".strip(),language='web2py',link=URL(r=request,c='global',f='vars'),_class='boxCode')}} """.strip(),language='web2py',link=URL('global','vars'),_class='boxCode')}}
<p>response.flash allows you to flash a message to the user when the page is returned. Use session.flash instead of response.flash to display a message after redirection. With default layout, you can click on the flash to make it disappear. <p>response.flash allows you to flash a message to the user when the page is returned. Use session.flash instead of response.flash to display a message after redirection. With default layout, you can click on the flash to make it disappear.
<br/>Try it here: <a href="/{{=request.application}}/simple_examples/hello6">hello6</a></p> <br/>Try it here: <a href="/{{=request.application}}/simple_examples/hello6">hello6</a></p>
<h3>Example {{=c}}{{c+=1}}</h3><b>In controller: simple_examples.py</b> <h3>Example {{=c}}{{c+=1}}</h3><b>In controller: simple_examples.py</b>
{{=CODE(""" {{=CODE("""
def status(): def status():
return dict(request=request,session=session,response=response) return dict(toobar=response.toolbar())
""".strip(),language='web2py',link=URL(r=request,c='global',f='vars'),_class='boxCode')}} """.strip(),language='web2py',link=URL('global','vars'),_class='boxCode')}}
<p>Here we are showing the request, session and response objects using the generic.html template. <p>Here we are showing the request, session and response objects using the generic.html template.
<br/>Try it here: <a href="/{{=request.application}}/simple_examples/status">status</a></p> <br/>Try it here: <a href="/{{=request.application}}/simple_examples/status">status</a></p>
<h3>Example {{=c}}{{c+=1}}</h3><b>In controller: simple_examples.py</b> <h3>Example {{=c}}{{c+=1}}</h3><b>In controller: simple_examples.py</b>
{{=CODE(""" {{=CODE("""
def redirectme(): def redirectme():
redirect(URL('hello3')) redirect(URL('hello3'))
""".strip(),language='web2py',link=URL(r=request,c='global',f='vars'),_class='boxCode')}} """.strip(),language='web2py',link=URL('global','vars'),_class='boxCode')}}
<p>You can do redirect. <p>You can do redirect.
<br/>Try it here: <a href="/{{=request.application}}/simple_examples/redirectme">redirectme</a></p> <br/>Try it here: <a href="/{{=request.application}}/simple_examples/redirectme">redirectme</a></p>
<h3>Example {{=c}}{{c+=1}}</h3><b>In controller: simple_examples.py</b> <h3>Example {{=c}}{{c+=1}}</h3><b>In controller: simple_examples.py</b>
{{=CODE(""" {{=CODE("""
def raisehttp(): def raisehttp():
raise HTTP(400,"internal error") raise HTTP(400,"internal error")
""".strip(),language='web2py',link=URL(r=request,c='global',f='vars'),_class='boxCode')}} """.strip(),language='web2py',link=URL('global','vars'),_class='boxCode')}}
<p>You can raise HTTP exceptions to return an error page. <p>You can raise HTTP exceptions to return an error page.
<br/>Try it here: <a href="/{{=request.application}}/simple_examples/raisehttp">raisehttp</a></p> <br/>Try it here: <a href="/{{=request.application}}/simple_examples/raisehttp">raisehttp</a></p>
<h3>Example {{=c}}{{c+=1}}</h3><b>In controller: simple_examples.py</b> <h3>Example {{=c}}{{c+=1}}</h3><b>In controller: simple_examples.py</b>
{{=CODE(""" {{=CODE("""
def raiseexception(): def raiseexception():
1/0 1/0
return 'oops' return 'oops'
""".strip(),language='web2py',link=URL(r=request,c='global',f='vars'),_class='boxCode')}} """.strip(),language='web2py',link=URL('global','vars'),_class='boxCode')}}
<p>If an exception occurs (other than HTTP) a ticket is generated and the event is logged for the administrator. These tickets and logs can be accessed, reviewed and deleted at any later time. <p>If an exception occurs (other than HTTP) a ticket is generated and the event is logged for the administrator. These tickets and logs can be accessed, reviewed and deleted at any later time.
<br/>Try it here: <a href="/{{=request.application}}/simple_examples/raiseexception">raiseexception</a></p> <br/>Try it here: <a href="/{{=request.application}}/simple_examples/raiseexception">raiseexception</a></p>
<h3>Example {{=c}}{{c+=1}}</h3><b>In controller: simple_examples.py</b> <h3>Example {{=c}}{{c+=1}}</h3><b>In controller: simple_examples.py</b>
{{=CODE(""" {{=CODE("""
def servejs(): def servejs():
import gluon.contenttype import gluon.contenttype
response.headers['Content-Type']=gluon.contenttype.contenttype('.js') response.headers['Content-Type']=gluon.contenttype.contenttype('.js')
return 'alert("This is a Javascript document, it is not supposed to run!");' return 'alert("This is a Javascript document, it is not supposed to run!");'
""".strip(),language='web2py',link=URL(r=request,c='global',f='vars'),_class='boxCode')}} """.strip(),language='web2py',link=URL('global','vars'),_class='boxCode')}}
<p>You can serve other than HTML pages by changing the contenttype via the response.headers. The gluon.contenttype module can help you figure the type of the file to be served. NOTICE: this is not necessary for static files unless you want to require authorization. <p>You can serve other than HTML pages by changing the contenttype via the response.headers. The gluon.contenttype module can help you figure the type of the file to be served. NOTICE: this is not necessary for static files unless you want to require authorization.
<br/>Try it here: <a href="/{{=request.application}}/simple_examples/servejs">servejs</a></p> <br/>Try it here: <a href="/{{=request.application}}/simple_examples/servejs">servejs</a></p>
@@ -135,7 +135,7 @@
{{=CODE(""" {{=CODE("""
def makejson(): def makejson():
return response.json(['foo', {'bar': ('baz', None, 1.0, 2)}]) return response.json(['foo', {'bar': ('baz', None, 1.0, 2)}])
""".strip(),language='web2py',link=URL(r=request,c='global',f='vars'),_class='boxCode')}} """.strip(),language='web2py',link=URL('global','vars'),_class='boxCode')}}
<p>If you are into Ajax, web2py includes gluon.contrib.<a href="http://cheeseshop.python.org/pypi/simplejson">simplejson</a>, developed by Bob Ippolito. This module provides a fast and easy way to serve asynchronous content to your Ajax page. gluon.simplesjson.dumps(...) can serialize most Python types into <a href="http://www.json.org">JSON</a>. gluon.contrib.simplejson.loads(...) performs the reverse operation. <p>If you are into Ajax, web2py includes gluon.contrib.<a href="http://cheeseshop.python.org/pypi/simplejson">simplejson</a>, developed by Bob Ippolito. This module provides a fast and easy way to serve asynchronous content to your Ajax page. gluon.simplesjson.dumps(...) can serialize most Python types into <a href="http://www.json.org">JSON</a>. gluon.contrib.simplejson.loads(...) performs the reverse operation.
<br/>Try it here: <a href="/{{=request.application}}/simple_examples/makejson">makejson</a></p> <br/>Try it here: <a href="/{{=request.application}}/simple_examples/makejson">makejson</a></p>
@@ -143,41 +143,41 @@
<h3 id="example_rtf">Example {{=c}}{{c+=1}}</h3><b>In controller: simple_examples.py</b> <h3 id="example_rtf">Example {{=c}}{{c+=1}}</h3><b>In controller: simple_examples.py</b>
{{=CODE(""" {{=CODE("""
def makertf(): def makertf():
import gluon.contrib.pyrtf as q import gluon.contrib.pyrtf as q
doc=q.Document() doc=q.Document()
section=q.Section() section=q.Section()
doc.Sections.append(section) doc.Sections.append(section)
section.append('Section Title') section.append('Section Title')
section.append('web2py is great. '*100) section.append('web2py is great. '*100)
response.headers['Content-Type']='text/rtf' response.headers['Content-Type']='text/rtf'
return q.dumps(doc) return q.dumps(doc)
""".strip(),language='web2py',link=URL(r=request,c='global',f='vars'),_class='boxCode')}} """.strip(),language='web2py',link=URL('global','vars'),_class='boxCode')}}
<p>web2py also includes gluon.contrib.<a href="http://pyrtf.sourceforge.net/">pyrtf</a>, developed by Simon Cusack and revised by Grant Edwards. This module allows you to generate Rich Text Format documents including colored formatted text and pictures.<br/>Try it here: <a href="/{{=request.application}}/simple_examples/makertf">makertf</a></p> <p>web2py also includes gluon.contrib.<a href="http://pyrtf.sourceforge.net/">pyrtf</a>, developed by Simon Cusack and revised by Grant Edwards. This module allows you to generate Rich Text Format documents including colored formatted text and pictures.<br/>Try it here: <a href="/{{=request.application}}/simple_examples/makertf">makertf</a></p>
<h3 id="example_rss">Example {{=c}}{{c+=1}}</h3><b>In controller: simple_examples.py</b> <h3 id="example_rss">Example {{=c}}{{c+=1}}</h3><b>In controller: simple_examples.py</b>
{{=CODE(""" {{=CODE("""
def rss_aggregator(): def rss_aggregator():
import datetime import datetime
import gluon.contrib.rss2 as rss2 import gluon.contrib.rss2 as rss2
import gluon.contrib.feedparser as feedparser import gluon.contrib.feedparser as feedparser
d = feedparser.parse("http://rss.slashdot.org/Slashdot/slashdot/to") d = feedparser.parse("http://rss.slashdot.org/Slashdot/slashdot/to")
rss = rss2.RSS2(title=d.channel.title, rss = rss2.RSS2(title=d.channel.title,
link = d.channel.link, link = d.channel.link,
description = d.channel.description, description = d.channel.description,
lastBuildDate = datetime.datetime.now(), lastBuildDate = datetime.datetime.now(),
items = [ items = [
rss2.RSSItem( rss2.RSSItem(
title = entry.title, title = entry.title,
link = entry.link, link = entry.link,
description = entry.description, description = entry.description,
# guid = rss2.Guid('unkown'), # guid = rss2.Guid('unkown'),
pubDate = datetime.datetime.now()) for entry in d.entries] pubDate = datetime.datetime.now()) for entry in d.entries]
) )
response.headers['Content-Type']='application/rss+xml' response.headers['Content-Type']='application/rss+xml'
return rss2.dumps(rss) return rss2.dumps(rss)
""".strip(),language='web2py',link=URL(r=request,c='global',f='vars'),_class='boxCode')}} """.strip(),language='web2py',link=URL('global','vars'),_class='boxCode')}}
<p>web2py includes gluon.contrib.<a href="http://www.dalkescientific.com/Python/PyRSS2Gen.html">rss2</a>, developed by Dalke Scientific Software, which generates RSS2 feeds, and <p>web2py includes gluon.contrib.<a href="http://www.dalkescientific.com/Python/PyRSS2Gen.html">rss2</a>, developed by Dalke Scientific Software, which generates RSS2 feeds, and
gluon.contrib.<a href="http://www.feedparser.org/">feedparser</a>, developed by Mark Pilgrim, which collects RSS and ATOM feeds. The above controller collects a slashdot feed and makes new one. gluon.contrib.<a href="http://www.feedparser.org/">feedparser</a>, developed by Mark Pilgrim, which collects RSS and ATOM feeds. The above controller collects a slashdot feed and makes new one.
<br/>Try it here: <a href="/{{=request.application}}/simple_examples/rss_aggregator">rss_aggregator</a></p> <br/>Try it here: <a href="/{{=request.application}}/simple_examples/rss_aggregator">rss_aggregator</a></p>
@@ -185,16 +185,16 @@
<h3 id="example_wiki">Example {{=c}}{{c+=1}}</h3><b>In controller: simple_examples.py</b> <h3 id="example_wiki">Example {{=c}}{{c+=1}}</h3><b>In controller: simple_examples.py</b>
{{=CODE(""" {{=CODE("""
def ajaxwiki(): def ajaxwiki():
form=FORM(TEXTAREA(_id='text',_name='text'), form=FORM(TEXTAREA(_id='text',_name='text'),
INPUT(_type='button',_value='markmin', INPUT(_type='button',_value='markmin',
_onclick="ajax('ajaxwiki_onclick',['text'],'html')")) _onclick="ajax('ajaxwiki_onclick',['text'],'html')"))
return dict(form=form,html=DIV(_id='html')) return dict(form=form,html=DIV(_id='html'))
def ajaxwiki_onclick(): def ajaxwiki_onclick():
return MARKMIN(request.vars.text).xml() return MARKMIN(request.vars.text).xml()
""".strip(),language='web2py',link=URL(r=request,c='global',f='vars'),_class='boxCode')}} """.strip(),language='web2py',link=URL('global','vars'),_class='boxCode')}}
<p>The markmin wiki markup is described <a href="{{=URL(r=request,c='static',f='markmin.html')}}">here</a>. <p>The markmin wiki markup is described <a href="{{=URL('static','markmin.html')}}">here</a>.
web2py also includes gluon.contrib.<a href="http://code.google.com/p/python-markdown2/">markdown</a>.WIKI helper (markdown2) which converts WIKI markup to HTML following <a href="http://en.wikipedia.org/wiki/Markdown">this syntax</a>. In this example we added a fancy ajax effect.<br/>Try it here: <a href="/{{=request.application}}/simple_examples/ajaxwiki">ajaxwiki</a></p> web2py also includes gluon.contrib.<a href="http://code.google.com/p/python-markdown2/">markdown</a>.WIKI helper (markdown2) which converts WIKI markup to HTML following <a href="http://en.wikipedia.org/wiki/Markdown">this syntax</a>. In this example we added a fancy ajax effect.<br/>Try it here: <a href="/{{=request.application}}/simple_examples/ajaxwiki">ajaxwiki</a></p>
<h2 id="session_examples">Session Examples</h2> <h2 id="session_examples">Session Examples</h2>
@@ -202,12 +202,11 @@
<h3>Example {{=c}}{{c+=1}}</h3><b>In controller: session_examples.py </b> <h3>Example {{=c}}{{c+=1}}</h3><b>In controller: session_examples.py </b>
{{=CODE(""" {{=CODE("""
def counter(): def counter():
if not session.counter: session.counter=0 session.counter = (sesstion.counter or 0) + 1
session.counter+=1 return dict(counter=session.counter)
return dict(counter=session.counter) """.strip(),language='web2py',link=URL('global','vars'),_class='boxCode')}}<b>and view: session_examples/counter.html</b>
""".strip(),language='web2py',link=URL(r=request,c='global',f='vars'),_class='boxCode')}}<b>and view: session_examples/counter.html</b> {{=CODE(open(os.path.join(request.folder,'views/session_examples/counter.html'),'r').read(),language='html',link=URL('global','vars'),_class='boxCode')}}
{{=CODE(open(os.path.join(request.folder,'views/session_examples/counter.html'),'r').read(),language='html',link=URL(r=request,c='global',f='vars'),_class='boxCode')}}
<p>Click to count. The session.counter is persistent for this user and application. Every applicaiton within the system has its own separate session management. <p>Click to count. The session.counter is persistent for this user and application. Every applicaiton within the system has its own separate session management.
<br/>Try it here: <a href="/{{=request.application}}/session_examples/counter">counter</a></p> <br/>Try it here: <a href="/{{=request.application}}/session_examples/counter">counter</a></p>
@@ -216,66 +215,73 @@
<h3>Example {{=c}}{{c+=1}}</h3><b>In controller: template_examples.py</b> <h3>Example {{=c}}{{c+=1}}</h3><b>In controller: template_examples.py</b>
{{=CODE(""" {{=CODE("""
def variables(): return dict(a=10, b=20) def variables():
""".strip(),language='web2py',link=URL(r=request,c='global',f='vars'),_class='boxCode')}}<b>and view: template_examples/variables.html</b> return dict(a=10, b=20)
{{=CODE(open(os.path.join(request.folder,'views/template_examples/variables.html'),'r').read(),language='html',link=URL(r=request,c='global',f='vars'),_class='boxCode')}} """.strip(),language='web2py',link=URL('global','vars'),_class='boxCode')}}<b>and view: template_examples/variables.html</b>
{{=CODE(open(os.path.join(request.folder,'views/template_examples/variables.html'),'r').read(),language='html',link=URL('global','vars'),_class='boxCode')}}
<p>A view (also known as template) is just an HTML file with &#123;&#123;...&#125;&#125; tags. You can put ANY python code into the tags, no need to indent but you must use pass to close blocks. The view is transformed into a python code and then executed. &#123;&#123;=a&#125;&#125; prints a.xml() or escape(str(a)). <p>A view (also known as template) is just an HTML file with &#123;&#123;...&#125;&#125; tags. You can put ANY python code into the tags, no need to indent but you must use pass to close blocks. The view is transformed into a python code and then executed. &#123;&#123;=a&#125;&#125; prints a.xml() or escape(str(a)).
<br/>Try it here: <a href="/{{=request.application}}/template_examples/variables">variables</a></p> <br/>Try it here: <a href="/{{=request.application}}/template_examples/variables">variables</a></p>
<h3>Example {{=c}}{{c+=1}}</h3><b>In controller: template_examples.py </b> <h3>Example {{=c}}{{c+=1}}</h3><b>In controller: template_examples.py </b>
{{=CODE(""" {{=CODE("""
def test_for(): return dict() def test_for():
""".strip(),language='web2py',link=URL(r=request,c='global',f='vars'),_class='boxCode')}}<b>and view: template_examples/test_for.html</b> return dict()
{{=CODE(open(os.path.join(request.folder,'views/template_examples/test_for.html'),'r').read(),language='html',link=URL(r=request,c='global',f='vars'),_class='boxCode')}} """.strip(),language='web2py',link=URL('global','vars'),_class='boxCode')}}<b>and view: template_examples/test_for.html</b>
{{=CODE(open(os.path.join(request.folder,'views/template_examples/test_for.html'),'r').read(),language='html',link=URL('global','vars'),_class='boxCode')}}
<p>You can do for and while loops. <p>You can do for and while loops.
<br/>Try it here: <a href="/{{=request.application}}/template_examples/test_for">test_for</a></p> <br/>Try it here: <a href="/{{=request.application}}/template_examples/test_for">test_for</a></p>
<h3>Example {{=c}}{{c+=1}}</h3><b>In controller: template_examples.py </b> <h3>Example {{=c}}{{c+=1}}</h3><b>In controller: template_examples.py </b>
{{=CODE(""" {{=CODE("""
def test_if(): return dict() def test_if():
""".strip(),language='web2py',link=URL(r=request,c='global',f='vars'),_class='boxCode')}}<b>and view: template_examples/test_if.html</b> return dict()
{{=CODE(open(os.path.join(request.folder,'views/template_examples/test_if.html'),'r').read(),language='html',link=URL(r=request,c='global',f='vars'),_class='boxCode')}} """.strip(),language='web2py',link=URL('global','vars'),_class='boxCode')}}<b>and view: template_examples/test_if.html</b>
{{=CODE(open(os.path.join(request.folder,'views/template_examples/test_if.html'),'r').read(),language='html',link=URL('global','vars'),_class='boxCode')}}
<p>You can do if, elif, else. <p>You can do if, elif, else.
<br/>Try it here: <a href="/{{=request.application}}/template_examples/test_if">test_if</a></p> <br/>Try it here: <a href="/{{=request.application}}/template_examples/test_if">test_if</a></p>
<h3>Example {{=c}}{{c+=1}}</h3><b>In controller: template_examples.py </b> <h3>Example {{=c}}{{c+=1}}</h3><b>In controller: template_examples.py </b>
{{=CODE(""" {{=CODE("""
def test_try(): return dict() def test_try():
""".strip(),language='web2py',link=URL(r=request,c='global',f='vars'),_class='boxCode')}}<b>and view: template_examples/test_try.html</b> return dict()
{{=CODE(open(os.path.join(request.folder,'views/template_examples/test_try.html'),'r').read(),language='html',link=URL(r=request,c='global',f='vars'),_class='boxCode')}} """.strip(),language='web2py',link=URL('global','vars'),_class='boxCode')}}<b>and view: template_examples/test_try.html</b>
{{=CODE(open(os.path.join(request.folder,'views/template_examples/test_try.html'),'r').read(),language='html',link=URL('global','vars'),_class='boxCode')}}
<p>You can do try, except, finally. <p>You can do try, except, finally.
<br/>Try it here: <a href="/{{=request.application}}/template_examples/test_try">test_try</a></p> <br/>Try it here: <a href="/{{=request.application}}/template_examples/test_try">test_try</a></p>
<h3>Example {{=c}}{{c+=1}}</h3><b>In controller: template_examples.py </b> <h3>Example {{=c}}{{c+=1}}</h3><b>In controller: template_examples.py </b>
{{=CODE(""" {{=CODE("""
def test_def(): return dict() def test_def():
""".strip(),language='web2py',link=URL(r=request,c='global',f='vars'),_class='boxCode')}}<b>and view: template_examples/test_def.html</b> return dict()
{{=CODE(open(os.path.join(request.folder,'views/template_examples/test_def.html'),'r').read(),language='html',link=URL(r=request,c='global',f='vars'),_class='boxCode')}} """.strip(),language='web2py',link=URL('global','vars'),_class='boxCode')}}<b>and view: template_examples/test_def.html</b>
{{=CODE(open(os.path.join(request.folder,'views/template_examples/test_def.html'),'r').read(),language='html',link=URL('global','vars'),_class='boxCode')}}
<p>You can write functions in HTML too. <p>You can write functions in HTML too.
<br/>Try it here: <a href="/{{=request.application}}/template_examples/test_def">test_def</a></p> <br/>Try it here: <a href="/{{=request.application}}/template_examples/test_def">test_def</a></p>
<h3>Example {{=c}}{{c+=1}}</h3><b>In controller: template_examples.py </b> <h3>Example {{=c}}{{c+=1}}</h3><b>In controller: template_examples.py </b>
{{=CODE(""" {{=CODE("""
def escape(): return dict(message='<h1>text is escaped</h1>') def escape():
""".strip(),language='web2py',link=URL(r=request,c='global',f='vars'),_class='boxCode')}}<b>and view: template_examples/escape.html</b> return dict(message='<h1>text is escaped</h1>')
{{=CODE(open(os.path.join(request.folder,'views/template_examples/escape.html'),'r').read(),language='html',link=URL(r=request,c='global',f='vars'),_class='boxCode')}} """.strip(),language='web2py',link=URL('global','vars'),_class='boxCode')}}<b>and view: template_examples/escape.html</b>
{{=CODE(open(os.path.join(request.folder,'views/template_examples/escape.html'),'r').read(),language='html',link=URL('global','vars'),_class='boxCode')}}
<p>The argument of &#123;&#123;=...&#125;&#125; is always escaped unless it is an object with a .xml() method such as link, A(...), a FORM(...), a XML(...) block, etc. <p>The argument of &#123;&#123;=...&#125;&#125; is always escaped unless it is an object with a .xml() method such as link, A(...), a FORM(...), a XML(...) block, etc.
<br/>Try it here: <a href="/{{=request.application}}/template_examples/escape">escape</a></p> <br/>Try it here: <a href="/{{=request.application}}/template_examples/escape">escape</a></p>
<h3>Example {{=c}}{{c+=1}}</h3><b>In controller: template_examples.py </b> <h3>Example {{=c}}{{c+=1}}</h3><b>In controller: template_examples.py </b>
{{=CODE(""" {{=CODE("""
def xml(): def xml():
return dict(message=XML('<h1>text is not escaped</h1>')) return dict(message=XML('<h1>text is not escaped</h1>'))
""".strip(),language='web2py',link=URL(r=request,c='global',f='vars'),_class='boxCode')}}<b>and view: template_examples/xml.html</b> """.strip(),language='web2py',link=URL('global','vars'),_class='boxCode')}}<b>and view: template_examples/xml.html</b>
{{=CODE(open(os.path.join(request.folder,'views/template_examples/xml.html'),'r').read(),language='html',link=URL(r=request,c='global',f='vars'),_class='boxCode')}} {{=CODE(open(os.path.join(request.folder,'views/template_examples/xml.html'),'r').read(),language='html',link=URL('global','vars'),_class='boxCode')}}
<p>If you do not want to escape the argument of &#123;&#123;=...&#125;&#125; mark it as XML. <p>If you do not want to escape the argument of &#123;&#123;=...&#125;&#125; mark it as XML.
<br/>Try it here: <a href="/{{=request.application}}/template_examples/xml">xml</a></p> <br/>Try it here: <a href="/{{=request.application}}/template_examples/xml">xml</a></p>
<h3>Example {{=c}}{{c+=1}}</h3><b>In controller: template_examples.py </b> <h3>Example {{=c}}{{c+=1}}</h3><b>In controller: template_examples.py </b>
{{=CODE(""" {{=CODE("""
def beautify(): return dict(message=BEAUTIFY(request)) def beautify():
""".strip(),language='web2py',link=URL(r=request,c='global',f='vars'),_class='boxCode')}}<b>and view: template_examples/beautify.html</b> return dict(message=BEAUTIFY(request))
{{=CODE(open(os.path.join(request.folder,'views/template_examples/beautify.html'),'r').read(),language='html',link=URL(r=request,c='global',f='vars'),_class='boxCode')}} """.strip(),language='web2py',link=URL('global','vars'),_class='boxCode')}}<b>and view: template_examples/beautify.html</b>
{{=CODE(open(os.path.join(request.folder,'views/template_examples/beautify.html'),'r').read(),language='html',link=URL('global','vars'),_class='boxCode')}}
<p>You can use BEAUTIFY to turn lists and dictionaries into organized HTML. <p>You can use BEAUTIFY to turn lists and dictionaries into organized HTML.
<br/>Try it here: <a href="/{{=request.application}}/template_examples/beautify">beautify</a></p> <br/>Try it here: <a href="/{{=request.application}}/template_examples/beautify">beautify</a></p>
@@ -284,39 +290,39 @@
<h3>Example {{=c}}{{c+=1}}</h3><b>In controller: layout_examples.py </b> <h3>Example {{=c}}{{c+=1}}</h3><b>In controller: layout_examples.py </b>
{{=CODE(""" {{=CODE("""
def civilized(): def civilized():
response.menu=[['civilized',True,URL('civilized')], response.menu=[['civilized',True,URL('civilized')],
['slick',False,URL('slick')], ['slick',False,URL('slick')],
['basic',False,URL('basic')]] ['basic',False,URL('basic')]]
response.flash='you clicked on civilized' response.flash='you clicked on civilized'
return dict(message="you clicked on civilized") return dict(message="you clicked on civilized")
""".strip(),language='web2py',link=URL(r=request,c='global',f='vars'),_class='boxCode')}}<b>and view: layout_examples/civilized.html</b> """.strip(),language='web2py',link=URL('global','vars'),_class='boxCode')}}<b>and view: layout_examples/civilized.html</b>
{{=CODE(open(os.path.join(request.folder,'views/layout_examples/civilized.html'),'r').read(),language='html',link=URL(r=request,c='global',f='vars'),_class='boxCode')}} {{=CODE(open(os.path.join(request.folder,'views/layout_examples/civilized.html'),'r').read(),language='html',link=URL('global','vars'),_class='boxCode')}}
<p>You can specify the layout file at the top of your view. civilized Layout file is a view that somewhere in the body contains &#123;&#123;include&#125;&#125;. <p>You can specify the layout file at the top of your view. civilized Layout file is a view that somewhere in the body contains &#123;&#123;include&#125;&#125;.
<br/>Try it here: <a href="/{{=request.application}}/layout_examples/civilized">civilized</a></p> <br/>Try it here: <a href="/{{=request.application}}/layout_examples/civilized">civilized</a></p>
<h3>Example {{=c}}{{c+=1}}</h3><b>In controller: layout_examples.py </b> <h3>Example {{=c}}{{c+=1}}</h3><b>In controller: layout_examples.py </b>
{{=CODE(""" {{=CODE("""
def slick(): def slick():
response.menu=[['civilized',False,URL('civilized')], response.menu = [['civilized',False,URL('civilized')],
['slick',True,URL('slick')], ['slick',True,URL('slick')],
['basic',False,URL('basic')]] ['basic',False,URL('basic')]]
response.flash='you clicked on slick' response.flash = 'you clicked on slick'
return dict(message="you clicked on slick") return dict(message="you clicked on slick")
""".strip(),language='web2py',link=URL(r=request,c='global',f='vars'),_class='boxCode')}}<b>and view: layout_examples/slick.html</b> """.strip(),language='web2py',link=URL('global','vars'),_class='boxCode')}}<b>and view: layout_examples/slick.html</b>
{{=CODE(open(os.path.join(request.folder,'views/layout_examples/slick.html'),'r').read(),language='html',link=URL(r=request,c='global',f='vars'),_class='boxCode')}} {{=CODE(open(os.path.join(request.folder,'views/layout_examples/slick.html'),'r').read(),language='html',link=URL('global','vars'),_class='boxCode')}}
<p>Same here, but using a different template.<br/>Try it here: <a href="/{{=request.application}}/layout_examples/slick">slick</a></p> <p>Same here, but using a different template.<br/>Try it here: <a href="/{{=request.application}}/layout_examples/slick">slick</a></p>
<h3>Example {{=c}}{{c+=1}}</h3><b>In controller: layout_examples.py </b> <h3>Example {{=c}}{{c+=1}}</h3><b>In controller: layout_examples.py </b>
{{=CODE(""" {{=CODE("""
def basic(): def basic():
response.menu=[['civilized',False,URL('civilized')], response.menu=[['civilized',False,URL('civilized')],
['slick',False,URL('slick')], ['slick',False,URL('slick')],
['basic',True,URL('basic')]] ['basic',True,URL('basic')]]
response.flash='you clicked on basic' response.flash='you clicked on basic'
return dict(message="you clicked on basic") return dict(message="you clicked on basic")
""".strip(),language='web2py',link=URL(r=request,c='global',f='vars'),_class='boxCode')}}<b>and view: layout_examples/basic.html</b> """.strip(),language='web2py',link=URL('global','vars'),_class='boxCode')}}<b>and view: layout_examples/basic.html</b>
{{=CODE(open(os.path.join(request.folder,'views/layout_examples/basic.html'),'r').read(),language='html',link=URL(r=request,c='global',f='vars'),_class='boxCode')}} {{=CODE(open(os.path.join(request.folder,'views/layout_examples/basic.html'),'r').read(),language='html',link=URL('global','vars'),_class='boxCode')}}
<p>'layout.html' is the default template, every application has a copy of it. <p>'layout.html' is the default template, every application has a copy of it.
<br/>Try it here: <a href="/{{=request.application}}/layout_examples/basic">basic</a></p> <br/>Try it here: <a href="/{{=request.application}}/layout_examples/basic">basic</a></p>
@@ -325,21 +331,21 @@
<h3>Example {{=c}}{{c+=1}}</h3><b>In controller: form_examples.py</b> <h3>Example {{=c}}{{c+=1}}</h3><b>In controller: form_examples.py</b>
{{=CODE(""" {{=CODE("""
def form(): def form():
form=FORM(TABLE(TR("Your name:",INPUT(_type="text",_name="name",requires=IS_NOT_EMPTY())), form=FORM(TABLE(TR("Your name:",INPUT(_type="text",_name="name",requires=IS_NOT_EMPTY())),
TR("Your email:",INPUT(_type="text",_name="email",requires=IS_EMAIL())), TR("Your email:",INPUT(_type="text",_name="email",requires=IS_EMAIL())),
TR("Admin",INPUT(_type="checkbox",_name="admin")), TR("Admin",INPUT(_type="checkbox",_name="admin")),
TR("Sure?",SELECT('yes','no',_name="sure",requires=IS_IN_SET(['yes','no']))), TR("Sure?",SELECT('yes','no',_name="sure",requires=IS_IN_SET(['yes','no']))),
TR("Profile",TEXTAREA(_name="profile",value="write something here")), TR("Profile",TEXTAREA(_name="profile",value="write something here")),
TR("",INPUT(_type="submit",_value="SUBMIT")))) TR("",INPUT(_type="submit",_value="SUBMIT"))))
if form.accepts(request,session): if form.accepts(request,session):
response.flash="form accepted" response.flash="form accepted"
elif form.errors: elif form.errors:
response.flash="form is invalid" response.flash="form is invalid"
else: else:
response.flash="please fill the form" response.flash="please fill the form"
return dict(form=form,vars=form.vars) return dict(form=form,vars=form.vars)
""".strip(),language='web2py',link=URL(r=request,c='global',f='vars'),_class='boxCode')}} """.strip(),language='web2py',link=URL('global','vars'),_class='boxCode')}}
<p>You can use HTML helpers like FORM, INPUT, TEXTAREA, OPTION, SELECT to build forms. The "value=" attribute sets the initial value of the field (works for TEXTAREA and OPTION/SELECT too) and the requires attribute sets the validators. <p>You can use HTML helpers like FORM, INPUT, TEXTAREA, OPTION, SELECT to build forms. The "value=" attribute sets the initial value of the field (works for TEXTAREA and OPTION/SELECT too) and the requires attribute sets the validators.
FORM.accepts(..) tries to validate the form and, on success, stores vars into form.vars. On failure the error messages are stored into form.errors and shown in the form. FORM.accepts(..) tries to validate the form and, on success, stores vars into form.vars. On failure the error messages are stored into form.errors and shown in the form.
<br/>Try it here: <a href="/{{=request.application}}/form_examples/form">form</a></p> <br/>Try it here: <a href="/{{=request.application}}/form_examples/form">form</a></p>
@@ -352,44 +358,51 @@
<h3>Example {{=c}}{{c+=1}}</h3><b>in model: db.py</b> <h3>Example {{=c}}{{c+=1}}</h3><b>in model: db.py</b>
{{=CODE(""" {{=CODE("""
db=DAL('sqlite://storage.db') db.define_table(
'person',
Field('name'),
Field('email'),
format = '%(name)s')
db.define_table('users', # ONE (person) TO MANY (dogs)
Field('name'),
Field('email'))
# ONE (users) TO MANY (dogs) db.define_table(
db.define_table('dogs', 'dog',
Field('owner_id',db.users), Field('owner_id', db.person),
Field('name'), Field('name'),
Field('type'), Field('type'),
Field('vaccinated','boolean',default=False), Field('vaccinated', 'boolean', default=False),
Field('picture','upload',default='')) Field('picture', 'upload', default=''),
format = '%(name)s')
db.define_table('products', db.define_table(
Field('name'), 'product',
Field('description','text')) Field('name'),
Field('description', 'text'),
format = '%(name)s')
# MANY (users) TO MANY (products) # MANY (persons) TO MANY (purchases)
db.define_table('purchases',
Field('buyer_id',db.users),
Field('product_id',db.products),
Field('quantity','integer'))
purchased=((db.users.id==db.purchases.buyer_id)&(db.products.id==db.purchases.product_id)) db.define_table(
'purchase',
Field('buyer_id', db.person),
Field('product_id', db.product),
Field('quantity', 'integer'),
format = '%(quantity)s %(product_id)s -> %(buyer_id)s')
db.users.name.requires=IS_NOT_EMPTY() purchased = \
db.users.email.requires=[IS_EMAIL(), IS_NOT_IN_DB(db,'users.email')] (db.person.id==db.purchase.buyer_id)&\
db.dogs.owner_id.requires=IS_IN_DB(db,'users.id','users.name') (db.product.id==db.purchase.product_id)
db.dogs.name.requires=IS_NOT_EMPTY()
db.dogs.type.requires=IS_IN_SET(['small','medium','large']) db.person.name.requires = IS_NOT_EMPTY()
db.purchases.buyer_id.requires=IS_IN_DB(db,'users.id','users.name') db.person.email.requires = [IS_EMAIL(), IS_NOT_IN_DB(db, 'person.email')]
db.purchases.product_id.requires=IS_IN_DB(db,'products.id','products.name') db.dog.name.requires = IS_NOT_EMPTY()
db.purchases.quantity.requires=IS_INT_IN_RANGE(0,10) db.dog.type.requires = IS_IN_SET(('small', 'medium', 'large'))
""".strip(),language='web2py',link=URL(r=request,c='global',f='vars'),_class='boxCode')}} db.purchase.quantity.requires = IS_INT_IN_RANGE(0, 10)
""".strip(),language='web2py',link=URL('global','vars'),_class='boxCode')}}
<p> <p>
Tables are created if they do not exist (try... except). Tables are created if they do not exist (try... except).
Here "purchased" is an SQLQuery object, "db(purchased)" would be a SQLSet objects. A SQLSet object can be selected, updated, deleted. SQLSets can also be intersected. Allowed field types are string, integer, password, text, blob, upload, date, time, datetime, references(*), and id(*). The id field is there by default and must not be declared. references are for one to many and many to many as in the example above. For strings you should specify a length or you get length=32.<br/><br/> Here "purchased" is an Query object, "db(purchased)" would be a Set objects. A Set object can be selected, updated, deleted. Sets can also be intersected. Allowed field types are string, integer, password, text, blob, upload, date, time, datetime, references(*), and id(*). The id field is there by default and must not be declared. references are for one to many and many to many as in the example above. For strings you should specify a length or you get length=32.<br/><br/>
You can use db.tablename.fieldname.requires= to set restrictions on the field values. These restrictions are automatically converted into widgets when generating forms from the table with SQLFORM(db.tablename). You can use db.tablename.fieldname.requires= to set restrictions on the field values. These restrictions are automatically converted into widgets when generating forms from the table with SQLFORM(db.tablename).
<br/><br/> <br/><br/>
define_tables creates the table and attempts a migration if table has changed or if database name has changed since last time. If you know you already have the table in the database and you do not want to attempt a migration add one last argument to define_table <tt>migrate=False</tt>.</p> define_tables creates the table and attempts a migration if table has changed or if database name has changed since last time. If you know you already have the table in the database and you do not want to attempt a migration add one last argument to define_table <tt>migrate=False</tt>.</p>
@@ -397,112 +410,108 @@
<h3>Example {{=c}}{{c+=1}}</h3><b>In controller: database_examples.py </b> <h3>Example {{=c}}{{c+=1}}</h3><b>In controller: database_examples.py </b>
{{=CODE(""" {{=CODE("""
response.menu=[['Register User',False,URL('register_user')], response.menu = [['Register Person', False, URL('register_person')],
['Register Dog',False,URL('register_dog')], ['Register Dog', False, URL('register_dog')],
['Register Product',False,URL('register_product')], ['Register Product', False, URL('register_product')],
['Buy product',False,URL('buy')]] ['Buy product', False, URL('buy')]]
def register_user(): def register_person():
### create an insert form from the table # create an insert form from the table
form=SQLFORM(db.users) form = SQLFORM(db.person)
### if form is correct, perform the insert
if form.accepts(request,session): # if form correct perform the insert
response.flash='new record inserted' if form.process().accepted:
### and get a list of all users response.flash = 'new record inserted'
records=SQLTABLE(db().select(db.users.ALL))
return dict(form=form,records=records) # and get a list of all persons
""".strip(),language='web2py',link=URL(r=request,c='global',f='vars'),_class='boxCode')}}<b>and view: database_examples/register_user.html</b> records = SQLTABLE(db().select(db.person.ALL),headers='fieldname:capitalize')
{{=CODE(open(os.path.join(request.folder,'views/database_examples/register_user.html'),'r').read(),language='html',link=URL(r=request,c='global',f='vars'),_class='boxCode')}}
return dict(form=form, records=records)
""".strip(),language='web2py',link=URL('global','vars'),_class='boxCode')}}<b>and view: database_examples/register_person.html</b>
{{=CODE(open(os.path.join(request.folder,'views/database_examples/register_person.html'),'r').read(),language='html',link=URL('global','vars'),_class='boxCode')}}
<p>This is a simple user registration form. SQLFORM takes a table and returns the corresponding entry form with validators, etc. SQLFORM.accepts is similar to FORM.accepts but, if form is validated, the corresponding insert is also performed. SQLFORM can also do update and edit if a record is passed as its second argument. <p>This is a simple user registration form. SQLFORM takes a table and returns the corresponding entry form with validators, etc. SQLFORM.accepts is similar to FORM.accepts but, if form is validated, the corresponding insert is also performed. SQLFORM can also do update and edit if a record is passed as its second argument.
SQLTABLE instead turns a set of records (result of a select) into an HTML table with links as specified by its optional parameters. SQLTABLE instead turns a set of records (result of a select) into an HTML table with links as specified by its optional parameters.
The response.menu on top is just a variable used by the layout to make the navigation menu for all functions in this controller.<br/> The response.menu on top is just a variable used by the layout to make the navigation menu for all functions in this controller.<br/>
Try it here: <a href="/{{=request.application}}/database_examples/register_user">register_user</a></p> Try it here: <a href="/{{=request.application}}/database_examples/register_person">register_person</a></p>
<h3>Example {{=c}}{{c+=1}}</h3><b>In controller: database_examples.py </b> <h3>Example {{=c}}{{c+=1}}</h3><b>In controller: database_examples.py </b>
{{=CODE(""" {{=CODE("""
def register_dog():
form=SQLFORM(db.dogs)
if form.accepts(request,session): def register_dog():
response.flash='new record inserted' form = SQLFORM(db.dog)
download=URL('download') # to see the picture if form.process().accepted:
records=SQLTABLE(db().select(db.dogs.ALL),upload=download) response.flash = 'new record inserted'
return dict(form=form,records=records) download = URL('download') # to see the picture
""".strip(),language='web2py',link=URL(r=request,c='global',f='vars'),_class='boxCode')}}<b>and view: database_examples/register_dog.html</b> records = SQLTABLE(db().select(db.dog.ALL), upload=download,
{{=CODE(open(os.path.join(request.folder,'views/database_examples/register_dog.html'),'r').read(),language='html',link=URL(r=request,c='global',f='vars'),_class='boxCode')}} headers='fieldname:capitalize')
return dict(form=form, records=records)
""".strip(),language='web2py',link=URL('global','vars'),_class='boxCode')}}<b>and view: database_examples/register_dog.html</b>
{{=CODE(open(os.path.join(request.folder,'views/database_examples/register_dog.html'),'r').read(),language='html',link=URL('global','vars'),_class='boxCode')}}
<p>Here is a dog registration form. Notice that the "image" (type "upload") field is rendered into a &lt;INPUT type="file"&gt; html tag. SQLFORM.accepts(...) handles the upload of the file into the uploads/ folder. <p>Here is a dog registration form. Notice that the "image" (type "upload") field is rendered into a &lt;INPUT type="file"&gt; html tag. SQLFORM.accepts(...) handles the upload of the file into the uploads/ folder.
<br/>Try it here: <a href="/{{=request.application}}/database_examples/register_dog">register_dog</a></p> <br/>Try it here: <a href="/{{=request.application}}/database_examples/register_dog">register_dog</a></p>
<h3>Example {{=c}}{{c+=1}}</h3><b>In controller: database_examples.py </b> <h3>Example {{=c}}{{c+=1}}</h3><b>In controller: database_examples.py </b>
{{=CODE(""" {{=CODE("""
def register_product(): def register_product():
form=SQLFORM(db.products) form = SQLFORM(db.product)
if form.accepts(request,session): if form.process().accepted:
response.flash='new record inserted' response.flash = 'new record inserted'
records=SQLTABLE(db().select(db.products.ALL)) records = SQLTABLE(db().select(db.product.ALL),headers='fieldname:capitalize')
return dict(form=form,records=records) return dict(form=form, records=records)
""".strip(),language='web2py',link=URL(r=request,c='global',f='vars'),_class='boxCode')}}<b>and view: database_examples/register_product.html</b>
{{=CODE(open(os.path.join(request.folder,'views/database_examples/register_product.html'),'r').read(),language='html',link=URL(r=request,c='global',f='vars'),_class='boxCode')}} """.strip(),language='web2py',link=URL('global','vars'),_class='boxCode')}}<b>and view: database_examples/register_product.html</b>
{{=CODE(open(os.path.join(request.folder,'views/database_examples/register_product.html'),'r').read(),language='html',link=URL('global','vars'),_class='boxCode')}}
<p>Nothing new here. <p>Nothing new here.
<br/>Try it here: <a href="/{{=request.application}}/database_examples/register_product">register_product</a></p> <br/>Try it here: <a href="/{{=request.application}}/database_examples/register_product">register_product</a></p>
<h3>Example {{=c}}{{c+=1}}</h3><b>In controller: database_examples.py </b> <h3>Example {{=c}}{{c+=1}}</h3><b>In controller: database_examples.py </b>
{{=CODE(""" {{=CODE("""
def buy():
form=FORM(TABLE(TR("Buyer id:",INPUT(_type="text",_name="buyer_id",requires=IS_NOT_EMPTY())), def buy():
TR("Product id:",INPUT(_type="text",_name="product_id",requires=IS_NOT_EMPTY())), form = SQLFORM.factory(
TR("Quantity:",INPUT(_type="text",_name="quantity",requires=IS_INT_IN_RANGE(1,100))), Field('buyer_id',requires=IS_IN_DB(db,db.person.id,'%(name)s')),
TR("",INPUT(_type="submit",_value="Order")))) Field('product_id',requires=IS_IN_DB(db,db.product.id,'%(name)s')),
if form.accepts(request,session): Field('quantity','integer',requires=IS_INT_IN_RANGE(1,100)))
### check if user is in the database if form.process().accepted:
if len(db(db.users.id==form.vars.buyer_id).select())==0: # get previous purchese for same product
form.errors.buyer_id="buyer not in database" purchase = db((db.purchase.buyer_id == form.vars.buyer_id)&
### check if product is in the database (db.purchase.product_id==form.vars.product_id)).select().first()
if len(db(db.products.id==form.vars.product_id).select())==0:
form.errors.product_id="product not in database" if purchase:
### if no errors # if list contains a record, update that record
if len(form.errors)==0: purchase.update_record(
### get a list of same purchases by same user quantity = purchase.quantity+form.vars.quantity)
purchases=db((db.purchases.buyer_id==form.vars.buyer_id)& else:
(db.purchases.product_id==form.vars.product_id)).select() # self insert a new record in table
### if list contains a record, update that record db.purchase.insert(buyer_id=form.vars.buyer_id,
if len(purchases)>0: product_id=form.vars.product_id,
purchases[0].update_record(quantity=purchases[0].quantity+form.vars.quantity) quantity=form.vars.quantity)
### or insert a new record in table response.flash = 'product purchased!'
else: elif form.errors:
db.purchases.insert(buyer_id=form.vars.buyer_id, response.flash = 'invalid values in form!'
product_id=form.vars.product_id,
quantity=form.vars.quantity) # now get a list of all purchases
response.flash="product purchased!" records = SQLTABLE(db(purchased).select(),headers='fieldname:capitalize')
if len(form.errors): response.flash="invalid valus in form!" return dict(form=form, records=records)
### now get a list of all purchases """.strip(),language='web2py',link=URL('global','vars'),_class='boxCode')}}<b>and view: database_examples/buy.html</b>
records=db(purchased).select(db.users.name,db.purchases.quantity,db.products.name) {{=CODE(open(os.path.join(request.folder,'views/database_examples/buy.html'),'r').read(),language='html',link=URL('global','vars'),_class='boxCode')}}
return dict(form=form,records=SQLTABLE(records),vars=form.vars,vars2=request.vars)
""".strip(),language='web2py',link=URL(r=request,c='global',f='vars'),_class='boxCode')}}<b>and view: database_examples/buy.html</b>
{{=CODE(open(os.path.join(request.folder,'views/database_examples/buy.html'),'r').read(),language='html',link=URL(r=request,c='global',f='vars'),_class='boxCode')}}
<p>Here is a rather sophisticated buy form. It checks that the buyer and the product are in the database and updates the corresponding record or inserts a new purchase. It also does a JOIN to list all purchases. <p>Here is a rather sophisticated buy form. It checks that the buyer and the product are in the database and updates the corresponding record or inserts a new purchase. It also does a JOIN to list all purchases.
<br/>Try it here: <a href="/{{=request.application}}/database_examples/buy">buy</a></p> <br/>Try it here: <a href="/{{=request.application}}/database_examples/buy">buy</a></p>
<h3>Example {{=c}}{{c+=1}}</h3><b>In controller: database_examples.py</b> <h3>Example {{=c}}{{c+=1}}</h3><b>In controller: database_examples.py</b>
{{=CODE(""" {{=CODE("""
def delete_purchased(): def delete_purchased():
db(db.purchases.id>0).delete() db(db.purchase.id > 0).delete()
redirect(URL('buy')) redirect(URL('buy'))
""".strip(),language='web2py',link=URL(r=request,c='global',f='vars'),_class='boxCode')}}Try it here: <a href="/{{=request.application}}/database_examples/delete_purchased">delete_purchased</a> """.strip(),language='web2py',link=URL('global','vars'),_class='boxCode')}}Try it here: <a href="/{{=request.application}}/database_examples/delete_purchased">delete_purchased</a>
<h3>Example {{=c}}{{c+=1}}</h3><b>In controller: database_examples.py</b> <h3>Example {{=c}}{{c+=1}}</h3><b>In controller: database_examples.py</b>
{{=CODE(""" {{=CODE("""
def reset_purchased(): def download():
db(db.purchases.id>0).update(quantity=0) return response.download(request,db)
redirect(URL('buy')) """.strip(),language='web2py',link=URL('global','vars'),_class='boxCode')}}
""".strip(),language='web2py',link=URL(r=request,c='global',f='vars'),_class='boxCode')}}
<p>This is an update on an SQLSet. (db.purchase.id>0 identifies the set containing only table db.purchases.)
<br/>Try it here: <a href="/{{=request.application}}/database_examples/reset_purchased">reset_purchased</a></p>
<h3>Example {{=c}}{{c+=1}}</h3><b>In controller: database_examples.py</b>
{{=CODE("""
def download():
return response.download(request,db)
""".strip(),language='web2py',link=URL(r=request,c='global',f='vars'),_class='boxCode')}}
<p>This controller allows users to download the uploaded pictures of the dogs. <p>This controller allows users to download the uploaded pictures of the dogs.
Remember the upload=URL(...'download'...) statement in the register_dog function. Notice that in the URL path /application/controller/function/a/b/etc a, b, etc are passed to the controller as request.args[0], request.args[1], etc. Since the URL is validated request.args[] always contain valid filenames and no '~' or '..' etc. This is useful to allow visitors to link uploaded files.</p> Remember the upload=URL(...'download'...) statement in the register_dog function. Notice that in the URL path /application/controller/function/a/b/etc a, b, etc are passed to the controller as request.args[0], request.args[1], etc. Since the URL is validated request.args[] always contain valid filenames and no '~' or '..' etc. This is useful to allow visitors to link uploaded files.</p>
@@ -510,79 +519,79 @@
<h3>Example {{=c}}{{c+=1}}</h3><b>In controller: cache_examples.py </b> <h3>Example {{=c}}{{c+=1}}</h3><b>In controller: cache_examples.py </b>
{{=CODE(""" {{=CODE("""
def cache_in_ram(): def cache_in_ram():
import time import time
t=cache.ram('time',lambda:time.ctime(),time_expire=5) t=cache.ram('time',lambda:time.ctime(),time_expire=5)
return dict(time=t,link=A('click to reload',_href=URL(r=request))) return dict(time=t,link=A('click to reload',_href=URL(r=request)))
""".strip(),language='web2py',link=URL(r=request,c='global',f='vars'),_class='boxCode')}} """.strip(),language='web2py',link=URL('global','vars'),_class='boxCode')}}
<p>The output of <tt>lambda:time.ctime()</tt> is cached in ram for 5 seconds. The string 'time' is used as cache key. <p>The output of <tt>lambda:time.ctime()</tt> is cached in ram for 5 seconds. The string 'time' is used as cache key.
<br/>Try it here: <a href="/{{=request.application}}/cache_examples/cache_in_ram">cache_in_ram</a></p> <br/>Try it here: <a href="/{{=request.application}}/cache_examples/cache_in_ram">cache_in_ram</a></p>
<h3>Example {{=c}}{{c+=1}}</h3><b>In controller: cache_examples.py </b> <h3>Example {{=c}}{{c+=1}}</h3><b>In controller: cache_examples.py </b>
{{=CODE(""" {{=CODE("""
def cache_on_disk(): def cache_on_disk():
import time import time
t=cache.disk('time',lambda:time.ctime(),time_expire=5) t=cache.disk('time',lambda:time.ctime(),time_expire=5)
return dict(time=t,link=A('click to reload',_href=URL(r=request))) return dict(time=t,link=A('click to reload',_href=URL(r=request)))
""".strip(),language='web2py',link=URL(r=request,c='global',f='vars'),_class='boxCode')}} """.strip(),language='web2py',link=URL('global','vars'),_class='boxCode')}}
<p>The output of <tt>lambda:time.ctime()</tt> is cached on disk (using the shelve module) for 5 seconds. <p>The output of <tt>lambda:time.ctime()</tt> is cached on disk (using the shelve module) for 5 seconds.
<br/>Try it here: <a href="/{{=request.application}}/cache_examples/cache_on_disk">cache_on_disk</a></p> <br/>Try it here: <a href="/{{=request.application}}/cache_examples/cache_on_disk">cache_on_disk</a></p>
<h3>Example {{=c}}{{c+=1}}</h3><b>In controller: cache_examples.py </b> <h3>Example {{=c}}{{c+=1}}</h3><b>In controller: cache_examples.py </b>
{{=CODE(""" {{=CODE("""
def cache_in_ram_and_disk(): def cache_in_ram_and_disk():
import time import time
t=cache.ram('time',lambda:cache.disk('time', t=cache.ram('time',lambda:cache.disk('time',
lambda:time.ctime(),time_expire=5),time_expire=5) lambda:time.ctime(),time_expire=5),time_expire=5)
return dict(time=t,link=A('click to reload',_href=URL(r=request))) return dict(time=t,link=A('click to reload',_href=URL(r=request)))
""".strip(),language='web2py',link=URL(r=request,c='global',f='vars'),_class='boxCode')}} """.strip(),language='web2py',link=URL('global','vars'),_class='boxCode')}}
<p>The output of <tt>lambda:time.ctime()</tt> is cached on disk (using the shelve module) and then in ram for 5 seconds. web2py looks in ram first and if not there it looks on disk. If it is not on disk it calls the function. This is useful in a multiprocess type of environment. The two times do not have to be the same. <p>The output of <tt>lambda:time.ctime()</tt> is cached on disk (using the shelve module) and then in ram for 5 seconds. web2py looks in ram first and if not there it looks on disk. If it is not on disk it calls the function. This is useful in a multiprocess type of environment. The two times do not have to be the same.
<br/>Try it here: <a href="/{{=request.application}}/cache_examples/cache_in_ram_and_disk">cache_in_ram_and_disk</a></p> <br/>Try it here: <a href="/{{=request.application}}/cache_examples/cache_in_ram_and_disk">cache_in_ram_and_disk</a></p>
<h3>Example {{=c}}{{c+=1}}</h3><b>In controller: cache_examples.py </b> <h3>Example {{=c}}{{c+=1}}</h3><b>In controller: cache_examples.py </b>
{{=CODE(""" {{=CODE("""
@cache(request.env.path_info,time_expire=5,cache_model=cache.ram) @cache(request.env.path_info,time_expire=5,cache_model=cache.ram)
def cache_controller_in_ram(): def cache_controller_in_ram():
import time import time
t=time.ctime() t=time.ctime()
return dict(time=t,link=A('click to reload',_href=URL(r=request)))""".strip(),language='web2py',link=URL(r=request,c='global',f='vars'),_class='boxCode')}} return dict(time=t,link=A('click to reload',_href=URL(r=request)))""".strip(),language='web2py',link=URL('global','vars'),_class='boxCode')}}
<p>Here the entire controller (dictionary) is cached in ram for 5 seconds. The result of a select cannot be cached unless it is first serialized into a table <tt>lambda:SQLTABLE(db().select(db.users.ALL)).xml()</tt>. You can read below for an even better way to do it. <p>Here the entire controller (dictionary) is cached in ram for 5 seconds. The result of a select cannot be cached unless it is first serialized into a table <tt>lambda:SQLTABLE(db().select(db.user.ALL)).xml()</tt>. You can read below for an even better way to do it.
<br/>Try it here: <a href="/{{=request.application}}/cache_examples/cache_controller_in_ram">cache_controller_in_ram</a></p> <br/>Try it here: <a href="/{{=request.application}}/cache_examples/cache_controller_in_ram">cache_controller_in_ram</a></p>
<h3>Example {{=c}}{{c+=1}}</h3><b>In controller: cache_examples.py </b> <h3>Example {{=c}}{{c+=1}}</h3><b>In controller: cache_examples.py </b>
{{=CODE(""" {{=CODE("""
@cache(request.env.path_info,time_expire=5,cache_model=cache.disk) @cache(request.env.path_info,time_expire=5,cache_model=cache.disk)
def cache_controller_on_disk(): def cache_controller_on_disk():
import time import time
t=time.ctime() t=time.ctime()
return dict(time=t,link=A('click to reload',_href=URL(r=request))) return dict(time=t,link=A('click to reload',_href=URL(r=request)))
""".strip(),language='web2py',link=URL(r=request,c='global',f='vars'),_class='boxCode')}} """.strip(),language='web2py',link=URL('global','vars'),_class='boxCode')}}
<p>Here the entire controller (dictionary) is cached on disk for 5 seconds. This will not work if the dictionary contains unpickleable objects. <p>Here the entire controller (dictionary) is cached on disk for 5 seconds. This will not work if the dictionary contains unpickleable objects.
<br/>Try it here: <a href="/{{=request.application}}/cache_examples/cache_controller_on_disk">cache_controller_on_disk</a></p> <br/>Try it here: <a href="/{{=request.application}}/cache_examples/cache_controller_on_disk">cache_controller_on_disk</a></p>
<h3>Example {{=c}}{{c+=1}}</h3><b>In controller: cache_examples.py </b> <h3>Example {{=c}}{{c+=1}}</h3><b>In controller: cache_examples.py </b>
{{=CODE(""" {{=CODE("""
@cache(request.env.path_info,time_expire=5,cache_model=cache.ram) @cache(request.env.path_info,time_expire=5,cache_model=cache.ram)
def cache_controller_and_view(): def cache_controller_and_view():
import time import time
t=time.ctime() t=time.ctime()
d=dict(time=t,link=A('click to reload',_href=URL(r=request))) d=dict(time=t,link=A('click to reload',_href=URL(r=request)))
return response.render(d) return response.render(d)
""".strip(),language='web2py',link=URL(r=request,c='global',f='vars'),_class='boxCode')}} """.strip(),language='web2py',link=URL('global','vars'),_class='boxCode')}}
<p><tt>response.render(d)</tt> renders the dictionary inside the controller, so everything is cached now for 5 seconds. This is best and fastest way of caching! <p><tt>response.render(d)</tt> renders the dictionary inside the controller, so everything is cached now for 5 seconds. This is best and fastest way of caching!
<br/>Try it here: <a href="/{{=request.application}}/cache_examples/cache_controller_and_view">cache_controller_and_view</a></p> <br/>Try it here: <a href="/{{=request.application}}/cache_examples/cache_controller_and_view">cache_controller_and_view</a></p>
<h3>Example {{=c}}{{c+=1}}</h3><b>In controller: cache_examples.py </b> <h3>Example {{=c}}{{c+=1}}</h3><b>In controller: cache_examples.py </b>
{{=CODE(""" {{=CODE("""
def cache_db_select(): def cache_db_select():
import time import time
db.users.insert(name='somebody',email='gluon@mdp.cti.depaul.edu') db.person.insert(name='somebody',email='gluon@mdp.cti.depaul.edu')
records=db().select(db.users.ALL,cache=(cache.ram,5)) records = db().select(db.person.ALL,cache=(cache.ram,5))
if len(records)>20: db(db.users.id>0).delete() if len(records)>20: db(db.person.id>0).delete()
return dict(records=records) return dict(records=records)
""".strip(),language='web2py',link=URL(r=request,c='global',f='vars'),_class='boxCode')}} """.strip(),language='web2py',link=URL('global','vars'),_class='boxCode')}}
<p>The results of a select are complex unpickleable objects that cannot be cached using the previous method, but the select command takes an argument <tt>cache=(cache_model,time_expire)</tt> and will cache the result of the query accordingly. Notice that the key is not necessary since key is generated based on the database name and the select string. <p>The results of a select are complex unpickleable objects that cannot be cached using the previous method, but the select command takes an argument <tt>cache=(cache_model,time_expire)</tt> and will cache the result of the query accordingly. Notice that the key is not necessary since key is generated based on the database name and the select string.
<br/>Try it here: <a href="/{{=request.application}}/cache_examples/cache_db_select">cache_db_select</a></p> <br/>Try it here: <a href="/{{=request.application}}/cache_examples/cache_db_select">cache_db_select</a></p>
@@ -591,40 +600,40 @@
<h3>Example {{=c}}{{c+=1}}</h3><b>In controller: ajax_examples.py</b> <h3>Example {{=c}}{{c+=1}}</h3><b>In controller: ajax_examples.py</b>
{{=CODE(""" {{=CODE("""
def index(): def index():
return dict() return dict()
def data(): def data():
if not session.m or len(session.m)==10: session.m=[] if not session.m or len(session.m)==10: session.m=[]
if request.vars.q: session.m.append(request.vars.q) if request.vars.q: session.m.append(request.vars.q)
session.m.sort() session.m.sort()
return TABLE(*[TR(v) for v in session.m]).xml() return TABLE(*[TR(v) for v in session.m]).xml()
""".strip(),language='web2py',link=URL(r=request,c='global',f='vars'),_class='boxCode')}} """.strip(),language='web2py',link=URL('global','vars'),_class='boxCode')}}
<b>In view: ajax_examples/index.html</b> <b>In view: ajax_examples/index.html</b>
{{=CODE(open(os.path.join(request.folder,'views/ajax_examples/index.html'),'r').read(),language='html',link=URL(r=request,c='global',f='vars'),_class='boxCode')}} {{=CODE(open(os.path.join(request.folder,'views/ajax_examples/index.html'),'r').read(),language='html',link=URL('global','vars'),_class='boxCode')}}
<p>The javascript function "ajax" is provided in "web2py_ajax.html" and included by "layout.html". It takes three arguments, a url, a list of ids and a target id. When called, it sends to the url (via a get) the values of the ids and display the response in the value (of innerHTML) of the target id. <p>The javascript function "ajax" is provided in "web2py_ajax.html" and included by "layout.html". It takes three arguments, a url, a list of ids and a target id. When called, it sends to the url (via a get) the values of the ids and display the response in the value (of innerHTML) of the target id.
<br/>Try it here: <a href="/{{=request.application}}/ajax_examples/index">index</a></p> <br/>Try it here: <a href="/{{=request.application}}/ajax_examples/index">index</a></p>
<h3>Example {{=c}}{{c+=1}}</h3><b>In controller: ajax_examples.py </b> <h3>Example {{=c}}{{c+=1}}</h3><b>In controller: ajax_examples.py </b>
{{=CODE(""" {{=CODE("""
def flash(): def flash():
response.flash='this text should appear!' response.flash='this text should appear!'
return dict() return dict()
""".strip(),language='web2py',link=URL(r=request,c='global',f='vars'),_class='boxCode')}} """.strip(),language='web2py',link=URL('global','vars'),_class='boxCode')}}
<p>Try it here: <a href="/{{=request.application}}/ajax_examples/flash">flash</a></p> <p>Try it here: <a href="/{{=request.application}}/ajax_examples/flash">flash</a></p>
<h3>Example {{=c}}{{c+=1}}</h3><b>In controller: ajax_examples.py </b> <h3>Example {{=c}}{{c+=1}}</h3><b>In controller: ajax_examples.py </b>
{{=CODE(""" {{=CODE("""
def fade(): def fade():
return dict() return dict()
""".strip(),language='web2py',link=URL(r=request,c='global',f='vars'),_class='boxCode')}} """.strip(),language='web2py',link=URL('global','vars'),_class='boxCode')}}
<b>In view: ajax_examples/fade.html </b><br/> <b>In view: ajax_examples/fade.html </b><br/>
{{=CODE(open(os.path.join(request.folder,'views/ajax_examples/fade.html'),'r').read(),language='html',link=URL(r=request,c='global',f='vars'),_class='boxCode')}} {{=CODE(open(os.path.join(request.folder,'views/ajax_examples/fade.html'),'r').read(),language='html',link=URL('global','vars'),_class='boxCode')}}
<p>Try it here: <a href="/{{=request.application}}/ajax_examples/fade">fade</a></p> <p>Try it here: <a href="/{{=request.application}}/ajax_examples/fade">fade</a></p>
<h3>Excel-like spreadsheet via Ajax</h3> <h3>Excel-like spreadsheet via Ajax</h3>
Web2py includes a widget that acts like an Excel-like spreadsheet and can be used to build forms Web2py includes a widget that acts like an Excel-like spreadsheet and can be used to build forms
[<a href="{{=URL(r=request,c='spreadsheet',f='index')}}">read more</a>]. [<a href="{{=URL('spreadsheet','index')}}">read more</a>].
<h2 id="testing_examples">Testing Examples</h2> <h2 id="testing_examples">Testing Examples</h2>
@@ -632,15 +641,15 @@
<h3>Example {{=c}}{{c+=1}}</h3> <h3>Example {{=c}}{{c+=1}}</h3>
<p>Using the Python doctest notation it is possible to write tests for all controller functions. Tests are then run via the administrative interface which generates a report. Here is an example of a test in the code: <p>Using the Python doctest notation it is possible to write tests for all controller functions. Tests are then run via the administrative interface which generates a report. Here is an example of a test in the code:
{{=CODE(""" {{=CODE("""
def index(): def index():
''' '''
This is a docstring. The following 3 lines are a doctest: This is a docstring. The following 3 lines are a doctest:
>>> request.vars.name='Max' >>> request.vars.name='Max'
>>> index() >>> index()
{'name': 'Max'} {'name': 'Max'}
''' '''
return dict(name=request.vars.name) return dict(name=request.vars.name)
""".strip(),language='web2py',link=URL(r=request,c='global',f='vars'),_class='boxCode')}} """.strip(),language='web2py',link=URL('global','vars'),_class='boxCode')}}
<p></p> <p></p>
<h2 id="streaming_examples">Streaming Examples</h2> <h2 id="streaming_examples">Streaming Examples</h2>
@@ -649,11 +658,11 @@
<h3 id="example_stream">Example {{=c}}{{c+=1}}</h3> <h3 id="example_stream">Example {{=c}}{{c+=1}}</h3>
<p>It is very easy in web2py to stream large files. Here is an example of a controller that does so:</p> <p>It is very easy in web2py to stream large files. Here is an example of a controller that does so:</p>
{{=CODE(""" {{=CODE("""
def streamer(): def streamer():
import os import os
path=os.path.join(request.folder,'private','largefile.mpeg4') path=os.path.join(request.folder,'private','largefile.mpeg4')
return response.stream(open(path,'rb'),chunk_size=4096) return response.stream(open(path,'rb'),chunk_size=4096)
""".strip(),language='web2py',link=URL(r=request,c='global',f='vars'),_class='boxCode')}} """.strip(),language='web2py',link=URL('global','vars'),_class='boxCode')}}
<p>By default all static files and files stored in 'upload' fields in the database are streamed when larger than 1MByte.</p> <p>By default all static files and files stored in 'upload' fields in the database are streamed when larger than 1MByte.</p>
</p>web2py automatically and transparently handles PARTIAL_CONTENT and RANGE requests.</p> </p>web2py automatically and transparently handles PARTIAL_CONTENT and RANGE requests.</p>
@@ -663,22 +672,22 @@
<h3>Example {{=c}}{{c+=1}}</h3> <h3>Example {{=c}}{{c+=1}}</h3>
<p>Web2py has native support for the XMLRPC protocol. Below is a controller function "handler" that exposes two functions, "add" and "sub" via XMLRPC. The controller "tester" executes the two function remotely via xmlrpc.</p> <p>Web2py has native support for the XMLRPC protocol. Below is a controller function "handler" that exposes two functions, "add" and "sub" via XMLRPC. The controller "tester" executes the two function remotely via xmlrpc.</p>
{{=CODE(""" {{=CODE("""
from gluon.tools import Service from gluon.tools import Service
service = Service(globals()) service = Service(globals())
@service.xmlrpc @service.xmlrpc
def add(a,b): return a+b def add(a,b): return a+b
@service.xmlrpc @service.xmlrpc
def sub(a,b): return a-b def sub(a,b): return a-b
def call(): return service() def call(): return service()
def tester(): def tester():
import xmlrpclib import xmlrpclib
server=xmlrpclib.ServerProxy('http://hostname:port/app/controller/call/xmlrpc') server=xmlrpclib.ServerProxy('http://hostname:port/app/controller/call/xmlrpc')
return str(server.add(3,4)+server.sub(3,4)) return str(server.add(3,4)+server.sub(3,4))
""".strip(),language='web2py',link=URL(r=request,c='global',f='vars'),_class='boxCode')}} """.strip(),language='web2py',link=URL('global','vars'),_class='boxCode')}}
</div> </div>
</div> </div>
@@ -43,11 +43,11 @@
{{end}} {{end}}
{{block right_sidebar}} {{block right_sidebar}}
<center> <div style="text-align:center">
<a href="http://web2py.com/book"><img src="{{=URL('static','images/tablet.png')}}" alt="Tablet" /></a> <a href="http://web2py.com/book"><img src="{{=URL('static','images/tablet.png')}}" alt="Tablet" /></a>
<br/> <br/>
<a class="button" href="{{=URL('download')}}">DOWNLOAD NOW<br/> <a class="button" href="{{=URL('download')}}">DOWNLOAD NOW<br/>
{{="%s.%s.%s (%s) %s" % request.env.web2py_version}} {{="%s.%s.%s (%s) %s" % request.env.web2py_version}}
</a> </a>
</center> </div>
{{end}} {{end}}
+4 -2
View File
@@ -71,8 +71,8 @@
<body> <body>
<div class="wrapper"><!-- for sticky footer --> <div class="wrapper"><!-- for sticky footer -->
<div class="flash">{{=response.flash or ''}}</div> <div class="flash">{{=response.flash or ''}}</div>
<div class="main"> <div class="header">
<div class="container header"> <div class="container">
<div class="sixteen columns"> <div class="sixteen columns">
<img src="{{=URL('static','images/web2py_logo.png')}}" /> <img src="{{=URL('static','images/web2py_logo.png')}}" />
<h5>{{=response.subtitle or ''}}</h5> <h5>{{=response.subtitle or ''}}</h5>
@@ -95,6 +95,8 @@
</div> </div>
</div> </div>
</div> </div>
</div>
<div class="main">
<div class="container mainbody"> <div class="container mainbody">
<div class="sixteen columns"> <div class="sixteen columns">
<div class="{{=middle_columns}} columns center"> <div class="{{=middle_columns}} columns center">
@@ -1,12 +1,10 @@
{{extend 'layout.html'}} {{extend 'layout.html'}}
<h1>If statement</h1> <h1>If statement</h1>
{{ {{a=10}}
a=10
}}
{{if a%2==0:}} {{if a%2==0:}}
<h2>{{=a}} is even</h2> <h2>{{=a}} is even</h2>
{{else:}} {{else:}}
<h2>{{=a}} is odd</h2> <h2>{{=a}} is odd</h2>
{{pass}} {{pass}}
+1 -1
View File
@@ -77,7 +77,7 @@ fieldset { padding: 16px; border-top: 1px #DEDEDE solid;}
fieldset legend {text-transform:uppercase; font-weight: bold; padding: 4px 16px 4px 16px; background: #f1f1f1;} fieldset legend {text-transform:uppercase; font-weight: bold; padding: 4px 16px 4px 16px; background: #f1f1f1;}
/* fix ie problem with menu */ /* fix ie problem with menu */
.ie-lte7 .topbar {z-index: 2; } .ie-lte7 .topbar .container {z-index: 2; }
td.w2p_fw {padding-bottom: 1em;} td.w2p_fw {padding-bottom: 1em;}
td.w2p_fl, td.w2p_fw, td.w2p_fc { vertical-align:top; } td.w2p_fl, td.w2p_fw, td.w2p_fc { vertical-align:top; }