added tagcloud
This commit is contained in:
@@ -0,0 +1,26 @@
|
||||
|
||||
|
||||
|
||||
|
||||
def index():
|
||||
return dict()
|
||||
|
||||
|
||||
def data():
|
||||
if not session.m or len(session.m) == 10:
|
||||
session.m = []
|
||||
if request.vars.q:
|
||||
session.m.append(request.vars.q)
|
||||
session.m.sort()
|
||||
return TABLE(*[TR(v) for v in session.m]).xml()
|
||||
|
||||
|
||||
def flash():
|
||||
response.flash = 'this text should appear!'
|
||||
return dict()
|
||||
|
||||
|
||||
def fade():
|
||||
return dict()
|
||||
|
||||
|
||||
@@ -0,0 +1,430 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
# ##########################################################
|
||||
# ## make sure administrator is on localhost
|
||||
# ###########################################################
|
||||
|
||||
import os
|
||||
import socket
|
||||
import datetime
|
||||
import copy
|
||||
import gluon.contenttype
|
||||
import gluon.fileutils
|
||||
|
||||
# ## critical --- make a copy of the environment
|
||||
|
||||
global_env = copy.copy(globals())
|
||||
global_env['datetime'] = datetime
|
||||
|
||||
http_host = request.env.http_host.split(':')[0]
|
||||
remote_addr = request.env.remote_addr
|
||||
try:
|
||||
hosts = (http_host, socket.gethostname(),
|
||||
socket.gethostbyname(http_host),
|
||||
'::1','127.0.0.1','::ffff:127.0.0.1')
|
||||
except:
|
||||
hosts = (http_host, )
|
||||
|
||||
if request.env.http_x_forwarded_for or request.env.wsgi_url_scheme\
|
||||
in ['https', 'HTTPS']:
|
||||
session.secure()
|
||||
elif (remote_addr not in hosts) and (remote_addr != "127.0.0.1"):
|
||||
raise HTTP(200, T('appadmin is disabled because insecure channel'))
|
||||
|
||||
if (request.application=='admin' and not session.authorized) or \
|
||||
(request.application!='admin' and not gluon.fileutils.check_credentials(request)):
|
||||
redirect(URL('admin', 'default', 'index',
|
||||
vars=dict(send=URL(args=request.args,vars=request.vars))))
|
||||
|
||||
ignore_rw = True
|
||||
response.view = 'appadmin.html'
|
||||
response.menu = [[T('design'), False, URL('admin', 'default', 'design',
|
||||
args=[request.application])], [T('db'), False,
|
||||
URL('index')], [T('state'), False,
|
||||
URL('state')], [T('cache'), False,
|
||||
URL('ccache')]]
|
||||
|
||||
# ##########################################################
|
||||
# ## auxiliary functions
|
||||
# ###########################################################
|
||||
|
||||
|
||||
def get_databases(request):
|
||||
dbs = {}
|
||||
for (key, value) in global_env.items():
|
||||
cond = False
|
||||
try:
|
||||
cond = isinstance(value, GQLDB)
|
||||
except:
|
||||
cond = isinstance(value, SQLDB)
|
||||
if cond:
|
||||
dbs[key] = value
|
||||
return dbs
|
||||
|
||||
|
||||
databases = get_databases(None)
|
||||
|
||||
|
||||
def eval_in_global_env(text):
|
||||
exec ('_ret=%s' % text, {}, global_env)
|
||||
return global_env['_ret']
|
||||
|
||||
|
||||
def get_database(request):
|
||||
if request.args and request.args[0] in databases:
|
||||
return eval_in_global_env(request.args[0])
|
||||
else:
|
||||
session.flash = T('invalid request')
|
||||
redirect(URL('index'))
|
||||
|
||||
|
||||
def get_table(request):
|
||||
db = get_database(request)
|
||||
if len(request.args) > 1 and request.args[1] in db.tables:
|
||||
return (db, request.args[1])
|
||||
else:
|
||||
session.flash = T('invalid request')
|
||||
redirect(URL('index'))
|
||||
|
||||
|
||||
def get_query(request):
|
||||
try:
|
||||
return eval_in_global_env(request.vars.query)
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
|
||||
def query_by_table_type(tablename,db,request=request):
|
||||
keyed = hasattr(db[tablename],'_primarykey')
|
||||
if keyed:
|
||||
firstkey = db[tablename][db[tablename]._primarykey[0]]
|
||||
cond = '>0'
|
||||
if firstkey.type in ['string', 'text']:
|
||||
cond = '!=""'
|
||||
qry = '%s.%s.%s%s' % (request.args[0], request.args[1], firstkey.name, cond)
|
||||
else:
|
||||
qry = '%s.%s.id>0' % tuple(request.args[:2])
|
||||
return qry
|
||||
|
||||
|
||||
|
||||
# ##########################################################
|
||||
# ## list all databases and tables
|
||||
# ###########################################################
|
||||
|
||||
|
||||
def index():
|
||||
return dict(databases=databases)
|
||||
|
||||
|
||||
# ##########################################################
|
||||
# ## insert a new record
|
||||
# ###########################################################
|
||||
|
||||
|
||||
def insert():
|
||||
(db, table) = get_table(request)
|
||||
form = SQLFORM(db[table], ignore_rw=ignore_rw)
|
||||
if form.accepts(request.vars, session):
|
||||
response.flash = T('new record inserted')
|
||||
return dict(form=form,table=db[table])
|
||||
|
||||
|
||||
# ##########################################################
|
||||
# ## list all records in table and insert new record
|
||||
# ###########################################################
|
||||
|
||||
|
||||
def download():
|
||||
import os
|
||||
db = get_database(request)
|
||||
return response.download(request,db)
|
||||
|
||||
def csv():
|
||||
import gluon.contenttype
|
||||
response.headers['Content-Type'] = \
|
||||
gluon.contenttype.contenttype('.csv')
|
||||
db = get_database(request)
|
||||
query = get_query(request)
|
||||
if not query:
|
||||
return None
|
||||
response.headers['Content-disposition'] = 'attachment; filename=%s_%s.csv'\
|
||||
% tuple(request.vars.query.split('.')[:2])
|
||||
return str(db(query).select())
|
||||
|
||||
|
||||
def import_csv(table, file):
|
||||
table.import_from_csv_file(file)
|
||||
|
||||
def select():
|
||||
import re
|
||||
db = get_database(request)
|
||||
dbname = request.args[0]
|
||||
regex = re.compile('(?P<table>\w+)\.(?P<field>\w+)=(?P<value>\d+)')
|
||||
if len(request.args)>1 and hasattr(db[request.args[1]],'_primarykey'):
|
||||
regex = re.compile('(?P<table>\w+)\.(?P<field>\w+)=(?P<value>.+)')
|
||||
if request.vars.query:
|
||||
match = regex.match(request.vars.query)
|
||||
if match:
|
||||
request.vars.query = '%s.%s.%s==%s' % (request.args[0],
|
||||
match.group('table'), match.group('field'),
|
||||
match.group('value'))
|
||||
else:
|
||||
request.vars.query = session.last_query
|
||||
query = get_query(request)
|
||||
if request.vars.start:
|
||||
start = int(request.vars.start)
|
||||
else:
|
||||
start = 0
|
||||
nrows = 0
|
||||
stop = start + 100
|
||||
table = None
|
||||
rows = []
|
||||
orderby = request.vars.orderby
|
||||
if orderby:
|
||||
orderby = dbname + '.' + orderby
|
||||
if orderby == session.last_orderby:
|
||||
if orderby[0] == '~':
|
||||
orderby = orderby[1:]
|
||||
else:
|
||||
orderby = '~' + orderby
|
||||
session.last_orderby = orderby
|
||||
session.last_query = request.vars.query
|
||||
form = FORM(TABLE(TR(T('Query:'), '', INPUT(_style='width:400px',
|
||||
_name='query', _value=request.vars.query or '',
|
||||
requires=IS_NOT_EMPTY(error_message=T("Cannot be empty")))), TR(T('Update:'),
|
||||
INPUT(_name='update_check', _type='checkbox',
|
||||
value=False), INPUT(_style='width:400px',
|
||||
_name='update_fields', _value=request.vars.update_fields
|
||||
or '')), TR(T('Delete:'), INPUT(_name='delete_check',
|
||||
_class='delete', _type='checkbox', value=False), ''),
|
||||
TR('', '', INPUT(_type='submit', _value='submit'))),
|
||||
_action=URL(r=request,args=request.args))
|
||||
if request.vars.csvfile != None:
|
||||
try:
|
||||
import_csv(db[request.vars.table],
|
||||
request.vars.csvfile.file)
|
||||
response.flash = T('data uploaded')
|
||||
except Exception, e:
|
||||
response.flash = DIV(T('unable to parse csv file'),PRE(str(e)))
|
||||
if form.accepts(request.vars, formname=None):
|
||||
# regex = re.compile(request.args[0] + '\.(?P<table>\w+)\.id\>0')
|
||||
regex = re.compile(request.args[0] + '\.(?P<table>\w+)\..+')
|
||||
|
||||
match = regex.match(form.vars.query.strip())
|
||||
if match:
|
||||
table = match.group('table')
|
||||
try:
|
||||
nrows = db(query).count()
|
||||
if form.vars.update_check and form.vars.update_fields:
|
||||
db(query).update(**eval_in_global_env('dict(%s)'
|
||||
% form.vars.update_fields))
|
||||
response.flash = T('%s rows updated', nrows)
|
||||
elif form.vars.delete_check:
|
||||
db(query).delete()
|
||||
response.flash = T('%s rows deleted', nrows)
|
||||
nrows = db(query).count()
|
||||
if orderby:
|
||||
rows = db(query).select(limitby=(start, stop),
|
||||
orderby=eval_in_global_env(orderby))
|
||||
else:
|
||||
rows = db(query).select(limitby=(start, stop))
|
||||
except Exception, e:
|
||||
(rows, nrows) = ([], 0)
|
||||
response.flash = DIV(T('Invalid Query'),PRE(str(e)))
|
||||
return dict(
|
||||
form=form,
|
||||
table=table,
|
||||
start=start,
|
||||
stop=stop,
|
||||
nrows=nrows,
|
||||
rows=rows,
|
||||
query=request.vars.query,
|
||||
)
|
||||
|
||||
|
||||
# ##########################################################
|
||||
# ## edit delete one record
|
||||
# ###########################################################
|
||||
|
||||
|
||||
def update():
|
||||
(db, table) = get_table(request)
|
||||
keyed = hasattr(db[table],'_primarykey')
|
||||
record = None
|
||||
if keyed:
|
||||
key = [f for f in request.vars if f in db[table]._primarykey]
|
||||
if key:
|
||||
record = db(db[table][key[0]] == request.vars[key[0]]).select().first()
|
||||
else:
|
||||
record = db(db[table].id == request.args(2)).select().first()
|
||||
|
||||
if not record:
|
||||
qry = query_by_table_type(table, db)
|
||||
session.flash = T('record does not exist')
|
||||
redirect(URL('select', args=request.args[:1],
|
||||
vars=dict(query=qry)))
|
||||
|
||||
if keyed:
|
||||
for k in db[table]._primarykey:
|
||||
db[table][k].writable=False
|
||||
|
||||
form = SQLFORM(db[table], record, deletable=True, delete_label=T('Check to delete'),
|
||||
ignore_rw=ignore_rw and not keyed,
|
||||
linkto=URL('select',
|
||||
args=request.args[:1]), upload=URL(r=request,
|
||||
f='download', args=request.args[:1]))
|
||||
|
||||
if form.accepts(request.vars, session):
|
||||
session.flash = T('done!')
|
||||
qry = query_by_table_type(table, db)
|
||||
redirect(URL('select', args=request.args[:1],
|
||||
vars=dict(query=qry)))
|
||||
return dict(form=form,table=db[table])
|
||||
|
||||
|
||||
# ##########################################################
|
||||
# ## get global variables
|
||||
# ###########################################################
|
||||
|
||||
|
||||
def state():
|
||||
return dict()
|
||||
|
||||
def ccache():
|
||||
form = FORM(
|
||||
P(TAG.BUTTON("Clear CACHE?", _type="submit", _name="yes", _value="yes")),
|
||||
P(TAG.BUTTON("Clear RAM", _type="submit", _name="ram", _value="ram")),
|
||||
P(TAG.BUTTON("Clear DISK", _type="submit", _name="disk", _value="disk")),
|
||||
)
|
||||
|
||||
if form.accepts(request.vars, session):
|
||||
clear_ram = False
|
||||
clear_disk = False
|
||||
session.flash = ""
|
||||
if request.vars.yes:
|
||||
clear_ram = clear_disk = True
|
||||
if request.vars.ram:
|
||||
clear_ram = True
|
||||
if request.vars.disk:
|
||||
clear_disk = True
|
||||
|
||||
if clear_ram:
|
||||
cache.ram.clear()
|
||||
session.flash += "Ram Cleared "
|
||||
if clear_disk:
|
||||
cache.disk.clear()
|
||||
session.flash += "Disk Cleared"
|
||||
|
||||
redirect(URL(r=request))
|
||||
|
||||
try:
|
||||
from guppy import hpy; hp=hpy()
|
||||
except ImportError:
|
||||
hp = False
|
||||
|
||||
import shelve, os, copy, time, math
|
||||
from gluon import portalocker
|
||||
|
||||
ram = {
|
||||
'entries': 0,
|
||||
'bytes': 0,
|
||||
'objects': 0,
|
||||
'hits': 0,
|
||||
'misses': 0,
|
||||
'ratio': 0,
|
||||
'oldest': time.time(),
|
||||
'keys': []
|
||||
}
|
||||
disk = copy.copy(ram)
|
||||
total = copy.copy(ram)
|
||||
disk['keys'] = []
|
||||
total['keys'] = []
|
||||
|
||||
def GetInHMS(seconds):
|
||||
hours = math.floor(seconds / 3600)
|
||||
seconds -= hours * 3600
|
||||
minutes = math.floor(seconds / 60)
|
||||
seconds -= minutes * 60
|
||||
seconds = math.floor(seconds)
|
||||
|
||||
return (hours, minutes, seconds)
|
||||
|
||||
for key, value in cache.ram.storage.items():
|
||||
if isinstance(value, dict):
|
||||
ram['hits'] = value['hit_total'] - value['misses']
|
||||
ram['misses'] = value['misses']
|
||||
try:
|
||||
ram['ratio'] = ram['hits'] * 100 / value['hit_total']
|
||||
except (KeyError, ZeroDivisionError):
|
||||
ram['ratio'] = 0
|
||||
else:
|
||||
if hp:
|
||||
ram['bytes'] += hp.iso(value[1]).size
|
||||
ram['objects'] += hp.iso(value[1]).count
|
||||
ram['entries'] += 1
|
||||
if value[0] < ram['oldest']:
|
||||
ram['oldest'] = value[0]
|
||||
ram['keys'].append((key, GetInHMS(time.time() - value[0])))
|
||||
|
||||
locker = open(os.path.join(request.folder,
|
||||
'cache/cache.lock'), 'a')
|
||||
portalocker.lock(locker, portalocker.LOCK_EX)
|
||||
disk_storage = shelve.open(os.path.join(request.folder, 'cache/cache.shelve'))
|
||||
try:
|
||||
for key, value in disk_storage.items():
|
||||
if isinstance(value, dict):
|
||||
disk['hits'] = value['hit_total'] - value['misses']
|
||||
disk['misses'] = value['misses']
|
||||
try:
|
||||
disk['ratio'] = disk['hits'] * 100 / value['hit_total']
|
||||
except (KeyError, ZeroDivisionError):
|
||||
disk['ratio'] = 0
|
||||
else:
|
||||
if hp:
|
||||
disk['bytes'] += hp.iso(value[1]).size
|
||||
disk['objects'] += hp.iso(value[1]).count
|
||||
disk['entries'] += 1
|
||||
if value[0] < disk['oldest']:
|
||||
disk['oldest'] = value[0]
|
||||
disk['keys'].append((key, GetInHMS(time.time() - value[0])))
|
||||
|
||||
finally:
|
||||
portalocker.unlock(locker)
|
||||
locker.close()
|
||||
disk_storage.close()
|
||||
|
||||
total['entries'] = ram['entries'] + disk['entries']
|
||||
total['bytes'] = ram['bytes'] + disk['bytes']
|
||||
total['objects'] = ram['objects'] + disk['objects']
|
||||
total['hits'] = ram['hits'] + disk['hits']
|
||||
total['misses'] = ram['misses'] + disk['misses']
|
||||
total['keys'] = ram['keys'] + disk['keys']
|
||||
try:
|
||||
total['ratio'] = total['hits'] * 100 / (total['hits'] + total['misses'])
|
||||
except (KeyError, ZeroDivisionError):
|
||||
total['ratio'] = 0
|
||||
|
||||
if disk['oldest'] < ram['oldest']:
|
||||
total['oldest'] = disk['oldest']
|
||||
else:
|
||||
total['oldest'] = ram['oldest']
|
||||
|
||||
ram['oldest'] = GetInHMS(time.time() - ram['oldest'])
|
||||
disk['oldest'] = GetInHMS(time.time() - disk['oldest'])
|
||||
total['oldest'] = GetInHMS(time.time() - total['oldest'])
|
||||
|
||||
def key_table(keys):
|
||||
return TABLE(
|
||||
TR(TD(B('Key')), TD(B('Time in Cache (h:m:s)'))),
|
||||
*[TR(TD(k[0]), TD('%02d:%02d:%02d' % k[1])) for k in keys],
|
||||
**dict(_class='cache-keys',
|
||||
_style="border-collapse: separate; border-spacing: .5em;"))
|
||||
|
||||
ram['keys'] = key_table(ram['keys'])
|
||||
disk['keys'] = key_table(disk['keys'])
|
||||
total['keys'] = key_table(total['keys'])
|
||||
|
||||
return dict(form=form, total=total,
|
||||
ram=ram, disk=disk, object_stats=hp != False)
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
|
||||
import time
|
||||
|
||||
|
||||
def cache_in_ram():
|
||||
"""cache the output of the lambda function in ram"""
|
||||
|
||||
t = cache.ram('time', lambda : time.ctime(), time_expire=5)
|
||||
return dict(time=t, link=A('click to reload', _href=URL(r=request)))
|
||||
|
||||
|
||||
def cache_on_disk():
|
||||
"""cache the output of the lambda function on disk"""
|
||||
|
||||
t = cache.disk('time', lambda : time.ctime(), time_expire=5)
|
||||
return dict(time=t, link=A('click to reload', _href=URL(r=request)))
|
||||
|
||||
|
||||
def cache_in_ram_and_disk():
|
||||
"""cache the output of the lambda function on disk and in ram"""
|
||||
|
||||
t = cache.ram('time', lambda : cache.disk('time', lambda : \
|
||||
time.ctime(), time_expire=5), time_expire=5)
|
||||
return dict(time=t, link=A('click to reload', _href=URL(r=request)))
|
||||
|
||||
|
||||
@cache(request.env.path_info, time_expire=5, cache_model=cache.ram)
|
||||
def cache_controller_in_ram():
|
||||
"""cache the output of the controller in ram"""
|
||||
|
||||
t = time.ctime()
|
||||
return dict(time=t, link=A('click to reload', _href=URL(r=request)))
|
||||
|
||||
|
||||
@cache(request.env.path_info, time_expire=5, cache_model=cache.disk)
|
||||
def cache_controller_on_disk():
|
||||
"""cache the output of the controller on disk"""
|
||||
|
||||
t = time.ctime()
|
||||
return dict(time=t, link=A('click to reload', _href=URL(r=request)))
|
||||
|
||||
|
||||
@cache(request.env.path_info, time_expire=5, cache_model=cache.ram)
|
||||
def cache_controller_and_view():
|
||||
"""cache the output of the controller rendered by the view in ram"""
|
||||
|
||||
t = time.ctime()
|
||||
d = dict(time=t, link=A('click to reload', _href=URL(r=request)))
|
||||
return response.render(d)
|
||||
|
||||
|
||||
def cache_db_select():
|
||||
"""cache the database select in ram for 5 seconds"""
|
||||
|
||||
db.users.insert(name='somebody', email='gluon@mdp.cti.depaul.edu')
|
||||
records = db().select(db.users.ALL, cache=(cache.ram, 5))
|
||||
if len(records) > 20:
|
||||
db(dba.users.id > 0).delete()
|
||||
return dict(records=records)
|
||||
|
||||
|
||||
@@ -0,0 +1,152 @@
|
||||
from gluon.fileutils import read_file
|
||||
|
||||
response.menu = [['Register User', False, URL(r=request,
|
||||
f='register_user')], ['Register Dog', False,
|
||||
URL('register_dog')], ['Register Product'
|
||||
, False, URL('register_product')],
|
||||
['Buy product', False, URL('buy')]]
|
||||
|
||||
|
||||
def register_user():
|
||||
""" simple user registration form with validation and database.insert()
|
||||
also lists all records currently in the table"""
|
||||
|
||||
# ## create an insert form from the table
|
||||
|
||||
form = SQLFORM(db.users)
|
||||
|
||||
# ## if form correct perform the insert
|
||||
|
||||
if form.accepts(request.vars, session):
|
||||
response.flash = 'new record inserted'
|
||||
|
||||
# ## and get a list of all users
|
||||
|
||||
records = SQLTABLE(db().select(db.users.ALL))
|
||||
return dict(form=form, records=records)
|
||||
|
||||
|
||||
def register_dog():
|
||||
""" simple user registration form with validation and database.insert()
|
||||
also lists all records currently in the table"""
|
||||
|
||||
form = SQLFORM(db.dogs)
|
||||
if form.accepts(request.vars, session):
|
||||
response.flash = 'new record inserted'
|
||||
download = URL('download') # to see the picture
|
||||
records = SQLTABLE(db().select(db.dogs.ALL), upload=download)
|
||||
return dict(form=form, records=records)
|
||||
|
||||
|
||||
def register_product():
|
||||
""" simple user registration form with validation and database.insert()
|
||||
also lists all records currently in the table"""
|
||||
|
||||
form = SQLFORM(db.products)
|
||||
if form.accepts(request.vars, session):
|
||||
response.flash = 'new record inserted'
|
||||
records = SQLTABLE(db().select(db.products.ALL))
|
||||
return dict(form=form, records=records)
|
||||
|
||||
|
||||
def buy():
|
||||
""" uses a form to query who is buying what. validates form and
|
||||
updates existing record or inserts new record in purchases """
|
||||
|
||||
buyerRecords = db().select(db.users.ALL)
|
||||
buyerOptions = []
|
||||
for row in buyerRecords:
|
||||
buyerOptions.append(OPTION(row.name, _value=row.id))
|
||||
|
||||
productRecords = db().select(db.products.ALL)
|
||||
productOptions = []
|
||||
for row in productRecords:
|
||||
productOptions.append(OPTION(row.name, _value=row.id))
|
||||
|
||||
form = FORM(TABLE(
|
||||
TR('Buyer id:',
|
||||
SELECT(buyerOptions,_name='buyer_id')),
|
||||
TR('Product id:',
|
||||
SELECT(productOptions,_name='product_id')),
|
||||
TR('Quantity:',
|
||||
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!'
|
||||
|
||||
# ## now get a list of all purchases
|
||||
|
||||
# quick fix to make it runnable on gae
|
||||
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():
|
||||
""" delete all records in purchases """
|
||||
|
||||
db(db.purchases.id > 0).delete()
|
||||
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():
|
||||
""" used to download uploaded files """
|
||||
|
||||
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')
|
||||
|
||||
|
||||
@@ -0,0 +1,74 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
from gluon.fileutils import read_file
|
||||
|
||||
response.title = T('web2py Web Framework')
|
||||
response.keywords = T('web2py, Python, Web Framework')
|
||||
response.description = T('web2py Web Framework')
|
||||
|
||||
session.forget()
|
||||
|
||||
@cache('index')
|
||||
def index():
|
||||
return response.render()
|
||||
|
||||
@cache('what')
|
||||
def what():
|
||||
import urllib;
|
||||
try:
|
||||
images = XML(urllib.urlopen('http://web2py.com/poweredby/default/images').read())
|
||||
except:
|
||||
images = []
|
||||
return response.render(images=images)
|
||||
|
||||
@cache('download')
|
||||
def download():
|
||||
return response.render()
|
||||
|
||||
@cache('who')
|
||||
def who():
|
||||
return response.render()
|
||||
|
||||
@cache('support')
|
||||
def support():
|
||||
return response.render()
|
||||
|
||||
@cache('documentation')
|
||||
def documentation():
|
||||
return response.render()
|
||||
|
||||
@cache('usergroups')
|
||||
def usergroups():
|
||||
return response.render()
|
||||
|
||||
def contact():
|
||||
redirect(URL('default','usergroups'))
|
||||
|
||||
@cache('videos')
|
||||
def videos():
|
||||
return response.render()
|
||||
|
||||
def security():
|
||||
redirect('http://www.web2py.com/book/default/chapter/01#security')
|
||||
|
||||
def api():
|
||||
redirect('http://web2py.com/book/default/chapter/04#API')
|
||||
|
||||
@cache('license')
|
||||
def license():
|
||||
import os
|
||||
filename = os.path.join(request.env.gluon_parent, 'LICENSE')
|
||||
return response.render(dict(license=MARKMIN(read_file(filename))))
|
||||
|
||||
def version():
|
||||
return 'Version %s.%s.%s (%s) %s' % request.env.web2py_version
|
||||
|
||||
@cache('examples')
|
||||
def examples():
|
||||
return response.render()
|
||||
|
||||
@cache('changelog')
|
||||
def changelog():
|
||||
import os
|
||||
filename = os.path.join(request.env.gluon_parent, 'CHANGELOG')
|
||||
return response.render(dict(changelog=MARKMIN(read_file(filename))))
|
||||
@@ -0,0 +1,27 @@
|
||||
|
||||
|
||||
|
||||
def form():
|
||||
""" a simple entry form with various types of objects """
|
||||
|
||||
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('Admin', INPUT(_type='checkbox', _name='admin')),
|
||||
TR('Sure?', SELECT('yes', 'no', _name='sure',
|
||||
requires=IS_IN_SET(['yes', 'no']))),
|
||||
TR('Profile', TEXTAREA(_name='profile',
|
||||
value='write something here')),
|
||||
TR('', INPUT(_type='submit', _value='SUBMIT')),
|
||||
))
|
||||
if form.process().accepted:
|
||||
response.flash = 'form accepted'
|
||||
elif form.errors:
|
||||
response.flash = 'form is invalid'
|
||||
else:
|
||||
response.flash = 'please fill the form'
|
||||
return dict(form=form, vars=form.vars)
|
||||
|
||||
|
||||
@@ -0,0 +1,81 @@
|
||||
|
||||
session.forget()
|
||||
|
||||
response.menu = [['home', False, '/%s/default/index'
|
||||
% request.application], ['docs', True,
|
||||
'/%s/global/vars' % request.application]]
|
||||
|
||||
|
||||
def vars():
|
||||
"""the running controller function!"""
|
||||
|
||||
if not request.args:
|
||||
(
|
||||
doc,
|
||||
keys,
|
||||
t,
|
||||
c,
|
||||
d,
|
||||
value,
|
||||
) = (
|
||||
'Global variables',
|
||||
globals(),
|
||||
None,
|
||||
None,
|
||||
(),
|
||||
None,
|
||||
)
|
||||
(title, args) = ('globals()', '')
|
||||
elif len(request.args) < 3:
|
||||
args = '.'.join(request.args)
|
||||
try:
|
||||
doc = eval(args + '.__doc__')
|
||||
except:
|
||||
doc = 'no documentation'
|
||||
try:
|
||||
keys = eval('dir(%s)' % args)
|
||||
except:
|
||||
keys = []
|
||||
t = eval('type(%s)' % args)
|
||||
try:
|
||||
c = eval('%s.__class__' % args)
|
||||
except:
|
||||
c = None
|
||||
try:
|
||||
d = eval('%s.__bases__' % args)
|
||||
except:
|
||||
d = None
|
||||
title = args
|
||||
args += '.'
|
||||
else:
|
||||
raise HTTP(400)
|
||||
attributes = {}
|
||||
for key in keys:
|
||||
a = args + key
|
||||
if eval('isinstance(%s,SQLDB)' % a) or a == 'vars':
|
||||
continue
|
||||
try:
|
||||
doc1 = eval(a + '.__doc__')
|
||||
except:
|
||||
doc1 = 'no documentation'
|
||||
t1 = eval('type(%s)' % a)
|
||||
try:
|
||||
c1 = eval('%s.__class__' % a)
|
||||
except:
|
||||
c1 = None
|
||||
try:
|
||||
d1 = eval('%s.__bases__' % a)
|
||||
except:
|
||||
d1 = ()
|
||||
attributes[a] = (doc1, t1, c1, d1)
|
||||
return dict(
|
||||
title=title,
|
||||
args=args,
|
||||
t=t,
|
||||
c=c,
|
||||
d=d,
|
||||
doc=doc,
|
||||
attributes=attributes,
|
||||
)
|
||||
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
|
||||
|
||||
|
||||
def civilized():
|
||||
response.menu = [['civilized', True, URL('civilized'
|
||||
)], ['slick', False, URL('slick')],
|
||||
['basic', False, URL('basic')]]
|
||||
response.flash = 'you clicked on civilized'
|
||||
return dict(message='you clicked on civilized')
|
||||
|
||||
|
||||
def slick():
|
||||
response.menu = [['civilized', False, URL('civilized'
|
||||
)], ['slick', True, URL('slick')],
|
||||
['basic', False, URL('basic')]]
|
||||
response.flash = 'you clicked on slick'
|
||||
return dict(message='you clicked on slick')
|
||||
|
||||
|
||||
def basic():
|
||||
response.menu = [['civilized', False, URL('civilized'
|
||||
)], ['slick', False, URL('slick')],
|
||||
['basic', True, URL('basic')]]
|
||||
response.flash = 'you clicked on basic'
|
||||
return dict(message='you clicked on basic')
|
||||
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
|
||||
|
||||
|
||||
def counter():
|
||||
""" every time you reload, it increases the session.counter """
|
||||
|
||||
if not session.counter:
|
||||
session.counter = 0
|
||||
session.counter += 1
|
||||
return dict(counter=session.counter)
|
||||
|
||||
|
||||
@@ -0,0 +1,140 @@
|
||||
def hello1():
|
||||
""" simple page without template """
|
||||
|
||||
return 'Hello World'
|
||||
|
||||
|
||||
def hello2():
|
||||
""" simple page without template but with internationalization """
|
||||
|
||||
return T('Hello World')
|
||||
|
||||
|
||||
def hello3():
|
||||
""" page rendered by template simple_examples/index3.html or generic.html"""
|
||||
|
||||
return dict(message='Hello World')
|
||||
|
||||
|
||||
def hello4():
|
||||
""" page rendered by template simple_examples/index3.html or generic.html"""
|
||||
|
||||
response.view = 'simple_examples/hello3.html'
|
||||
return dict(message=T('Hello World'))
|
||||
|
||||
|
||||
def hello5():
|
||||
""" generates full page in controller """
|
||||
|
||||
return HTML(BODY(H1(T('Hello World'), _style='color: red;'))).xml() # .xml to serialize
|
||||
|
||||
|
||||
def hello6():
|
||||
""" page rendered with a flash"""
|
||||
|
||||
response.flash = 'Hello World in a flash!'
|
||||
return dict(message=T('Hello World'))
|
||||
|
||||
|
||||
def status():
|
||||
""" page that shows internal status"""
|
||||
response.view = 'generic.html'
|
||||
return dict(request=request, session=session, response=response)
|
||||
|
||||
|
||||
def redirectme():
|
||||
""" redirects to /{{=request.application}}/{{=request.controller}}/hello3 """
|
||||
|
||||
redirect(URL('hello3'))
|
||||
|
||||
|
||||
def raisehttp():
|
||||
""" returns an HTTP 400 ERROR page """
|
||||
|
||||
raise HTTP(400, 'internal error')
|
||||
|
||||
|
||||
def raiseexception():
|
||||
""" generates an exeption, logs the event and returns a ticket number """
|
||||
|
||||
1 / 0
|
||||
return 'oops'
|
||||
|
||||
|
||||
def servejs():
|
||||
""" serves a js document """
|
||||
|
||||
import gluon.contenttype
|
||||
response.headers['Content-Type'] = \
|
||||
gluon.contenttype.contenttype('.js')
|
||||
return 'alert("This is a Javascript document, it is not supposed to run!");'
|
||||
|
||||
|
||||
def makejson():
|
||||
import gluon.contrib.simplejson as sj
|
||||
return sj.dumps(['foo', {'bar': ('baz', None, 1.0, 2)}])
|
||||
|
||||
|
||||
def makertf():
|
||||
import gluon.contrib.pyrtf as q
|
||||
doc = q.Document()
|
||||
section = q.Section()
|
||||
doc.Sections.append(section)
|
||||
section.append('Section Title')
|
||||
section.append('web2py is great. ' * 100)
|
||||
response.headers['Content-Type'] = 'text/rtf'
|
||||
return q.dumps(doc)
|
||||
|
||||
|
||||
def rss_aggregator():
|
||||
import datetime
|
||||
import gluon.contrib.rss2 as rss2
|
||||
import gluon.contrib.feedparser as feedparser
|
||||
d = feedparser.parse('http://rss.slashdot.org/Slashdot/slashdot/to')
|
||||
|
||||
rss = rss2.RSS2(title=d.channel.title, link=d.channel.link,
|
||||
description=d.channel.description,
|
||||
lastBuildDate=datetime.datetime.now(),
|
||||
items=[rss2.RSSItem(title=entry.title,
|
||||
link=entry.link, description=entry.description,
|
||||
pubDate=datetime.datetime.now()) for entry in
|
||||
d.entries])
|
||||
response.headers['Content-Type'] = 'application/rss+xml'
|
||||
return rss2.dumps(rss)
|
||||
|
||||
|
||||
|
||||
def ajaxwiki():
|
||||
default="""
|
||||
# section
|
||||
|
||||
## subsection
|
||||
|
||||
### sub subsection
|
||||
|
||||
- **bold** text
|
||||
- ''italic''
|
||||
- [[link http://google.com]]
|
||||
|
||||
``
|
||||
def index: return 'hello world'
|
||||
``
|
||||
|
||||
-----------
|
||||
Quoted text
|
||||
-----------
|
||||
|
||||
---------
|
||||
0 | 0 | 1
|
||||
0 | 2 | 0
|
||||
3 | 0 | 0
|
||||
---------
|
||||
"""
|
||||
form = FORM(TEXTAREA(_id='text',_name='text',value=default),
|
||||
INPUT(_type='button',
|
||||
_value='markmin',
|
||||
_onclick="ajax('ajaxwiki_onclick',['text'],'html')"))
|
||||
return dict(form=form, html=DIV(_id='html'))
|
||||
|
||||
def ajaxwiki_onclick():
|
||||
return MARKMIN(request.vars.text).xml()
|
||||
@@ -0,0 +1,9 @@
|
||||
from gluon.contrib.spreadsheet import Sheet
|
||||
|
||||
def callback():
|
||||
return cache.ram('sheet1',lambda:None,None).process(request)
|
||||
|
||||
def index():
|
||||
sheet = cache.ram('sheet1',lambda:Sheet(10,10,URL('callback')),0)
|
||||
#sheet.cell('r0c3',value='=r0c0+r0c1+r0c2',readonly=True)
|
||||
return dict(sheet=sheet)
|
||||
@@ -0,0 +1,35 @@
|
||||
|
||||
|
||||
|
||||
def variables():
|
||||
return dict(a=10, b=20)
|
||||
|
||||
|
||||
def test_for():
|
||||
return dict()
|
||||
|
||||
|
||||
def test_if():
|
||||
return dict()
|
||||
|
||||
|
||||
def test_try():
|
||||
return dict()
|
||||
|
||||
|
||||
def test_def():
|
||||
return dict()
|
||||
|
||||
|
||||
def escape():
|
||||
return dict(message='<h1>text is scaped</h1>')
|
||||
|
||||
|
||||
def xml():
|
||||
return dict(message=XML('<h1>text is not escaped</h1>'))
|
||||
|
||||
|
||||
def beautify():
|
||||
return dict(message=BEAUTIFY(request))
|
||||
|
||||
|
||||
Reference in New Issue
Block a user