fixed pep8 in apps
This commit is contained in:
@@ -23,7 +23,7 @@ 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')
|
||||
'::1', '127.0.0.1', '::ffff:127.0.0.1')
|
||||
except:
|
||||
hosts = (http_host, )
|
||||
|
||||
@@ -32,10 +32,10 @@ if request.env.http_x_forwarded_for or request.is_https:
|
||||
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)):
|
||||
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))))
|
||||
vars=dict(send=URL(args=request.args, vars=request.vars))))
|
||||
|
||||
ignore_rw = True
|
||||
response.view = 'appadmin.html'
|
||||
@@ -95,24 +95,23 @@ def get_query(request):
|
||||
return None
|
||||
|
||||
|
||||
def query_by_table_type(tablename,db,request=request):
|
||||
keyed = hasattr(db[tablename],'_primarykey')
|
||||
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)
|
||||
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)
|
||||
|
||||
@@ -127,7 +126,7 @@ def insert():
|
||||
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])
|
||||
return dict(form=form, table=db[table])
|
||||
|
||||
|
||||
# ##########################################################
|
||||
@@ -138,7 +137,8 @@ def insert():
|
||||
def download():
|
||||
import os
|
||||
db = get_database(request)
|
||||
return response.download(request,db)
|
||||
return response.download(request, db)
|
||||
|
||||
|
||||
def csv():
|
||||
import gluon.contenttype
|
||||
@@ -149,26 +149,27 @@ def csv():
|
||||
if not query:
|
||||
return None
|
||||
response.headers['Content-disposition'] = 'attachment; filename=%s_%s.csv'\
|
||||
% tuple(request.vars.query.split('.')[:2])
|
||||
return str(db(query,ignore_common_filters=True).select())
|
||||
% tuple(request.vars.query.split('.')[:2])
|
||||
return str(db(query, ignore_common_filters=True).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'):
|
||||
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'))
|
||||
match.group('table'), match.group('field'),
|
||||
match.group('value'))
|
||||
else:
|
||||
request.vars.query = session.last_query
|
||||
query = get_query(request)
|
||||
@@ -192,14 +193,15 @@ def select():
|
||||
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:'),
|
||||
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',
|
||||
or '')), TR(T('Delete:'), INPUT(_name='delete_check',
|
||||
_class='delete', _type='checkbox', value=False), ''),
|
||||
TR('', '', INPUT(_type='submit', _value=T('submit')))),
|
||||
_action=URL(r=request,args=request.args))
|
||||
_action=URL(r=request, args=request.args))
|
||||
|
||||
tb = None
|
||||
if form.accepts(request.vars, formname=None):
|
||||
@@ -211,28 +213,30 @@ def select():
|
||||
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))
|
||||
% form.vars.update_fields))
|
||||
response.flash = T('%s %%{row} updated', nrows)
|
||||
elif form.vars.delete_check:
|
||||
db(query).delete()
|
||||
response.flash = T('%s %%{row} deleted', nrows)
|
||||
nrows = db(query).count()
|
||||
if orderby:
|
||||
rows = db(query,ignore_common_filters=True).select(limitby=(start, stop), orderby=eval_in_global_env(orderby))
|
||||
rows = db(query, ignore_common_filters=True).select(limitby=(
|
||||
start, stop), orderby=eval_in_global_env(orderby))
|
||||
else:
|
||||
rows = db(query,ignore_common_filters=True).select(limitby=(start, stop))
|
||||
rows = db(query, ignore_common_filters=True).select(
|
||||
limitby=(start, stop))
|
||||
except Exception, e:
|
||||
import traceback
|
||||
tb = traceback.format_exc()
|
||||
(rows, nrows) = ([], 0)
|
||||
response.flash = DIV(T('Invalid Query'),PRE(str(e)))
|
||||
response.flash = DIV(T('Invalid Query'), PRE(str(e)))
|
||||
# begin handle upload csv
|
||||
csv_table = table or request.vars.table
|
||||
if csv_table:
|
||||
formcsv = FORM(str(T('or import from csv file'))+" ",
|
||||
INPUT(_type='file',_name='csvfile'),
|
||||
INPUT(_type='hidden',_value=csv_table,_name='table'),
|
||||
INPUT(_type='submit',_value=T('import')))
|
||||
formcsv = FORM(str(T('or import from csv file')) + " ",
|
||||
INPUT(_type='file', _name='csvfile'),
|
||||
INPUT(_type='hidden', _value=csv_table, _name='table'),
|
||||
INPUT(_type='submit', _value=T('import')))
|
||||
else:
|
||||
formcsv = None
|
||||
if formcsv and formcsv.process().accepted:
|
||||
@@ -241,7 +245,7 @@ def select():
|
||||
request.vars.csvfile.file)
|
||||
response.flash = T('data uploaded')
|
||||
except Exception, e:
|
||||
response.flash = DIV(T('unable to parse csv file'),PRE(str(e)))
|
||||
response.flash = DIV(T('unable to parse csv file'), PRE(str(e)))
|
||||
# end handle upload csv
|
||||
|
||||
return dict(
|
||||
@@ -252,9 +256,9 @@ def select():
|
||||
nrows=nrows,
|
||||
rows=rows,
|
||||
query=request.vars.query,
|
||||
formcsv = formcsv,
|
||||
tb = tb,
|
||||
)
|
||||
formcsv=formcsv,
|
||||
tb=tb,
|
||||
)
|
||||
|
||||
|
||||
# ##########################################################
|
||||
@@ -264,14 +268,16 @@ def select():
|
||||
|
||||
def update():
|
||||
(db, table) = get_table(request)
|
||||
keyed = hasattr(db[table],'_primarykey')
|
||||
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]], ignore_common_filters=True).select().first()
|
||||
record = db(db[table][key[0]] == request.vars[key[
|
||||
0]], ignore_common_filters=True).select().first()
|
||||
else:
|
||||
record = db(db[table].id == request.args(2),ignore_common_filters=True).select().first()
|
||||
record = db(db[table].id == request.args(
|
||||
2), ignore_common_filters=True).select().first()
|
||||
|
||||
if not record:
|
||||
qry = query_by_table_type(table, db)
|
||||
@@ -281,20 +287,21 @@ def update():
|
||||
|
||||
if keyed:
|
||||
for k in db[table]._primarykey:
|
||||
db[table][k].writable=False
|
||||
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',
|
||||
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]))
|
||||
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])
|
||||
return dict(form=form, table=db[table])
|
||||
|
||||
|
||||
# ##########################################################
|
||||
@@ -305,11 +312,15 @@ def update():
|
||||
def state():
|
||||
return dict()
|
||||
|
||||
|
||||
def ccache():
|
||||
form = FORM(
|
||||
P(TAG.BUTTON(T("Clear CACHE?"), _type="submit", _name="yes", _value="yes")),
|
||||
P(TAG.BUTTON(T("Clear RAM"), _type="submit", _name="ram", _value="ram")),
|
||||
P(TAG.BUTTON(T("Clear DISK"), _type="submit", _name="disk", _value="disk")),
|
||||
P(TAG.BUTTON(
|
||||
T("Clear CACHE?"), _type="submit", _name="yes", _value="yes")),
|
||||
P(TAG.BUTTON(
|
||||
T("Clear RAM"), _type="submit", _name="ram", _value="ram")),
|
||||
P(TAG.BUTTON(
|
||||
T("Clear DISK"), _type="submit", _name="disk", _value="disk")),
|
||||
)
|
||||
|
||||
if form.accepts(request.vars, session):
|
||||
@@ -333,11 +344,16 @@ def ccache():
|
||||
redirect(URL(r=request))
|
||||
|
||||
try:
|
||||
from guppy import hpy; hp=hpy()
|
||||
from guppy import hpy
|
||||
hp = hpy()
|
||||
except ImportError:
|
||||
hp = False
|
||||
|
||||
import shelve, os, copy, time, math
|
||||
import shelve
|
||||
import os
|
||||
import copy
|
||||
import time
|
||||
import math
|
||||
from gluon import portalocker
|
||||
|
||||
ram = {
|
||||
@@ -382,9 +398,10 @@ def ccache():
|
||||
ram['keys'].append((key, GetInHMS(time.time() - value[0])))
|
||||
|
||||
locker = open(os.path.join(request.folder,
|
||||
'cache/cache.lock'), 'a')
|
||||
'cache/cache.lock'), 'a')
|
||||
portalocker.lock(locker, portalocker.LOCK_EX)
|
||||
disk_storage = shelve.open(os.path.join(request.folder, 'cache/cache.shelve'))
|
||||
disk_storage = shelve.open(
|
||||
os.path.join(request.folder, 'cache/cache.shelve'))
|
||||
try:
|
||||
for key, value in disk_storage.items():
|
||||
if isinstance(value, dict):
|
||||
@@ -415,7 +432,8 @@ def ccache():
|
||||
total['misses'] = ram['misses'] + disk['misses']
|
||||
total['keys'] = ram['keys'] + disk['keys']
|
||||
try:
|
||||
total['ratio'] = total['hits'] * 100 / (total['hits'] + total['misses'])
|
||||
total['ratio'] = total['hits'] * 100 / (total['hits'] +
|
||||
total['misses'])
|
||||
except (KeyError, ZeroDivisionError):
|
||||
total['ratio'] = 0
|
||||
|
||||
|
||||
@@ -5,35 +5,39 @@ import gluon.contrib.shell
|
||||
import gluon.dal
|
||||
import gluon.html
|
||||
import gluon.validators
|
||||
import code, thread
|
||||
import code
|
||||
import thread
|
||||
from gluon.debug import communicate, web_debugger, qdb_debugger
|
||||
import pydoc
|
||||
|
||||
|
||||
if DEMO_MODE or MULTI_USER_MODE:
|
||||
session.flash = T('disabled in demo mode')
|
||||
redirect(URL('default','site'))
|
||||
redirect(URL('default', 'site'))
|
||||
|
||||
FE = 10 ** 9
|
||||
|
||||
FE=10**9
|
||||
|
||||
def index():
|
||||
app = request.args(0) or 'admin'
|
||||
reset()
|
||||
# read buffer
|
||||
data = communicate()
|
||||
return dict(app=app,data=data)
|
||||
return dict(app=app, data=data)
|
||||
|
||||
|
||||
def callback():
|
||||
app = request.args[0]
|
||||
command = request.vars.statement
|
||||
session['debug_commands:'+app].append(command)
|
||||
session['debug_commands:' + app].append(command)
|
||||
output = communicate(command)
|
||||
k = len(session['debug_commands:'+app]) - 1
|
||||
k = len(session['debug_commands:' + app]) - 1
|
||||
return '[%i] %s%s\n' % (k + 1, command, output)
|
||||
|
||||
|
||||
def reset():
|
||||
app = request.args(0) or 'admin'
|
||||
session['debug_commands:'+app] = []
|
||||
session['debug_commands:' + app] = []
|
||||
return 'done'
|
||||
|
||||
|
||||
@@ -50,9 +54,9 @@ def interact():
|
||||
filename = web_debugger.filename
|
||||
lineno = web_debugger.lineno
|
||||
if filename:
|
||||
lines = dict([(i+1, l) for (i, l) in enumerate(
|
||||
[l.strip("\n").strip("\r") for l
|
||||
in open(filename).readlines()])])
|
||||
lines = dict([(i + 1, l) for (i, l) in enumerate(
|
||||
[l.strip("\n").strip("\r") for l
|
||||
in open(filename).readlines()])])
|
||||
filename = os.path.basename(filename)
|
||||
else:
|
||||
lines = {}
|
||||
@@ -64,8 +68,8 @@ def interact():
|
||||
f_globals = {}
|
||||
for name, value in env['globals'].items():
|
||||
if name not in gluon.html.__all__ and \
|
||||
name not in gluon.validators.__all__ and \
|
||||
name not in gluon.dal.__all__:
|
||||
name not in gluon.validators.__all__ and \
|
||||
name not in gluon.dal.__all__:
|
||||
f_globals[name] = pydoc.text.repr(value)
|
||||
else:
|
||||
f_locals = {}
|
||||
@@ -81,37 +85,43 @@ def interact():
|
||||
f_globals=f_globals, f_locals=f_locals,
|
||||
exception=web_debugger.exception_info)
|
||||
|
||||
|
||||
def step():
|
||||
web_debugger.do_step()
|
||||
redirect(URL("interact"))
|
||||
|
||||
|
||||
def next():
|
||||
web_debugger.do_next()
|
||||
redirect(URL("interact"))
|
||||
|
||||
|
||||
def cont():
|
||||
web_debugger.do_continue()
|
||||
redirect(URL("interact"))
|
||||
|
||||
|
||||
def ret():
|
||||
web_debugger.do_return()
|
||||
redirect(URL("interact"))
|
||||
|
||||
|
||||
def stop():
|
||||
web_debugger.do_quit()
|
||||
redirect(URL("interact"))
|
||||
|
||||
|
||||
def execute():
|
||||
app = request.args[0]
|
||||
command = request.vars.statement
|
||||
session['debug_commands:'+app].append(command)
|
||||
session['debug_commands:' + app].append(command)
|
||||
try:
|
||||
output = web_debugger.do_exec(command)
|
||||
if output is None:
|
||||
output = ""
|
||||
except Exception, e:
|
||||
output = T("Exception %s") % str(e)
|
||||
k = len(session['debug_commands:'+app]) - 1
|
||||
output = T("Exception %s") % str(e)
|
||||
k = len(session['debug_commands:' + app]) - 1
|
||||
return '[%i] %s%s\n' % (k + 1, command, output)
|
||||
|
||||
|
||||
@@ -122,8 +132,8 @@ def breakpoints():
|
||||
files = listdir(apath('', r=request), '.*\.py$')
|
||||
files = [filename for filename in files
|
||||
if filename and 'languages' not in filename
|
||||
and not filename.startswith("admin")
|
||||
and not filename.startswith("examples")]
|
||||
and not filename.startswith("admin")
|
||||
and not filename.startswith("examples")]
|
||||
|
||||
form = SQLFORM.factory(
|
||||
Field('filename', requires=IS_IN_SET(files), label=T("Filename")),
|
||||
@@ -133,17 +143,17 @@ def breakpoints():
|
||||
comment=T("deleted after first hit")),
|
||||
Field('condition', 'string', label=T("Condition"),
|
||||
comment=T("honored only if the expression evaluates to true")),
|
||||
)
|
||||
)
|
||||
|
||||
if form.accepts(request.vars, session):
|
||||
filename = os.path.join(request.env['applications_parent'],
|
||||
'applications', form.vars.filename)
|
||||
err = qdb_debugger.do_set_breakpoint(filename,
|
||||
form.vars.lineno,
|
||||
form.vars.temporary,
|
||||
form.vars.condition)
|
||||
form.vars.lineno,
|
||||
form.vars.temporary,
|
||||
form.vars.condition)
|
||||
response.flash = T("Set Breakpoint on %s at line %s: %s") % (
|
||||
filename, form.vars.lineno, err or T('successful'))
|
||||
filename, form.vars.lineno, err or T('successful'))
|
||||
|
||||
for item in request.vars:
|
||||
if item[:7] == 'delete_':
|
||||
@@ -153,7 +163,7 @@ def breakpoints():
|
||||
'path': bp[1], 'lineno': bp[2],
|
||||
'temporary': bp[3], 'enabled': bp[4], 'hits': bp[5],
|
||||
'condition': bp[6]}
|
||||
for bp in qdb_debugger.do_list_breakpoint()]
|
||||
for bp in qdb_debugger.do_list_breakpoint()]
|
||||
|
||||
return dict(breakpoints=breakpoints, form=form)
|
||||
|
||||
@@ -185,13 +195,13 @@ def toggle_breakpoint():
|
||||
if filename == bp_filename and lineno == bp_lineno:
|
||||
err = qdb_debugger.do_clear_breakpoint(filename, lineno)
|
||||
response.flash = T("Removed Breakpoint on %s at line %s", (
|
||||
filename, lineno))
|
||||
filename, lineno))
|
||||
ok = False
|
||||
break
|
||||
else:
|
||||
err = qdb_debugger.do_set_breakpoint(filename, lineno)
|
||||
response.flash = T("Set Breakpoint on %s at line %s: %s") % (
|
||||
filename, lineno, err or T('successful'))
|
||||
filename, lineno, err or T('successful'))
|
||||
ok = True
|
||||
else:
|
||||
response.flash = T("Unable to determine the line number!")
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -9,83 +9,92 @@ try:
|
||||
import shutil
|
||||
from gluon.fileutils import read_file, write_file
|
||||
except:
|
||||
session.flash='sorry, only on Unix systems'
|
||||
redirect(URL(request.application,'default','site'))
|
||||
session.flash = 'sorry, only on Unix systems'
|
||||
redirect(URL(request.application, 'default', 'site'))
|
||||
|
||||
if MULTI_USER_MODE and not is_manager():
|
||||
session.flash = 'Not Authorized'
|
||||
redirect(URL('default','site'))
|
||||
redirect(URL('default', 'site'))
|
||||
|
||||
forever = 10 ** 8
|
||||
|
||||
forever=10**8
|
||||
|
||||
def kill():
|
||||
p = cache.ram('gae_upload',lambda:None,forever)
|
||||
if not p or p.poll()!=None:
|
||||
p = cache.ram('gae_upload', lambda: None, forever)
|
||||
if not p or p.poll() is not None:
|
||||
return 'oops'
|
||||
os.kill(p.pid, signal.SIGKILL)
|
||||
cache.ram('gae_upload',lambda:None,-1)
|
||||
cache.ram('gae_upload', lambda: None, -1)
|
||||
|
||||
|
||||
class EXISTS(object):
|
||||
def __init__(self, error_message='file not found'):
|
||||
self.error_message = error_message
|
||||
|
||||
def __call__(self, value):
|
||||
if os.path.exists(value):
|
||||
return (value,None)
|
||||
return (value,self.error_message)
|
||||
return (value, None)
|
||||
return (value, self.error_message)
|
||||
|
||||
|
||||
def deploy():
|
||||
regex = re.compile('^\w+$')
|
||||
apps = sorted(file for file in os.listdir(apath(r=request)) if regex.match(file))
|
||||
apps = sorted(
|
||||
file for file in os.listdir(apath(r=request)) if regex.match(file))
|
||||
form = SQLFORM.factory(
|
||||
Field('appcfg',default=GAE_APPCFG,label=T('Path to appcfg.py'),
|
||||
Field('appcfg', default=GAE_APPCFG, label=T('Path to appcfg.py'),
|
||||
requires=EXISTS(error_message=T('file not found'))),
|
||||
Field('google_application_id',requires=IS_MATCH('[\w\-]+'),label=T('Google Application Id')),
|
||||
Field('applications','list:string',
|
||||
requires=IS_IN_SET(apps,multiple=True),
|
||||
Field('google_application_id', requires=IS_MATCH(
|
||||
'[\w\-]+'), label=T('Google Application Id')),
|
||||
Field('applications', 'list:string',
|
||||
requires=IS_IN_SET(apps, multiple=True),
|
||||
label=T('web2py apps to deploy')),
|
||||
Field('email',requires=IS_EMAIL(),label=T('GAE Email')),
|
||||
Field('password','password',requires=IS_NOT_EMPTY(),label=T('GAE Password')))
|
||||
cmd = output = errors= ""
|
||||
if form.accepts(request,session):
|
||||
Field('email', requires=IS_EMAIL(), label=T('GAE Email')),
|
||||
Field('password', 'password', requires=IS_NOT_EMPTY(), label=T('GAE Password')))
|
||||
cmd = output = errors = ""
|
||||
if form.accepts(request, session):
|
||||
try:
|
||||
kill()
|
||||
except:
|
||||
pass
|
||||
ignore_apps = [item for item in apps \
|
||||
if not item in form.vars.applications]
|
||||
ignore_apps = [item for item in apps
|
||||
if not item in form.vars.applications]
|
||||
regex = re.compile('\(applications/\(.*')
|
||||
yaml = apath('../app.yaml', r=request)
|
||||
if not os.path.exists(yaml):
|
||||
example = apath('../app.example.yaml', r=request)
|
||||
shutil.copyfile(example,yaml)
|
||||
shutil.copyfile(example, yaml)
|
||||
data = read_file(yaml)
|
||||
data = re.sub('application:.*','application: %s' % form.vars.google_application_id,data)
|
||||
data = regex.sub('(applications/(%s)/.*)|' % '|'.join(ignore_apps),data)
|
||||
data = re.sub('application:.*', 'application: %s' %
|
||||
form.vars.google_application_id, data)
|
||||
data = regex.sub(
|
||||
'(applications/(%s)/.*)|' % '|'.join(ignore_apps), data)
|
||||
write_file(yaml, data)
|
||||
|
||||
path = request.env.applications_parent
|
||||
cmd = '%s --email=%s --passin update %s' % \
|
||||
(form.vars.appcfg, form.vars.email, path)
|
||||
p = cache.ram('gae_upload',
|
||||
lambda s=subprocess,c=cmd:s.Popen(c, shell=True,
|
||||
stdin=s.PIPE,
|
||||
stdout=s.PIPE,
|
||||
stderr=s.PIPE, close_fds=True),-1)
|
||||
p.stdin.write(form.vars.password+'\n')
|
||||
lambda s=subprocess, c=cmd: s.Popen(c, shell=True,
|
||||
stdin=s.PIPE,
|
||||
stdout=s.PIPE,
|
||||
stderr=s.PIPE, close_fds=True), -1)
|
||||
p.stdin.write(form.vars.password + '\n')
|
||||
fcntl.fcntl(p.stdout.fileno(), fcntl.F_SETFL, os.O_NONBLOCK)
|
||||
fcntl.fcntl(p.stderr.fileno(), fcntl.F_SETFL, os.O_NONBLOCK)
|
||||
return dict(form=form,command=cmd)
|
||||
return dict(form=form, command=cmd)
|
||||
|
||||
|
||||
def callback():
|
||||
p = cache.ram('gae_upload',lambda:None,forever)
|
||||
if not p or p.poll()!=None:
|
||||
p = cache.ram('gae_upload', lambda: None, forever)
|
||||
if not p or p.poll() is not None:
|
||||
return '<done/>'
|
||||
try:
|
||||
output = p.stdout.read()
|
||||
except:
|
||||
output=''
|
||||
output = ''
|
||||
try:
|
||||
errors = p.stderr.read()
|
||||
except:
|
||||
errors=''
|
||||
return (output+errors).replace('\n','<br/>')
|
||||
errors = ''
|
||||
return (output + errors).replace('\n', '<br/>')
|
||||
|
||||
@@ -2,10 +2,10 @@ from gluon.fileutils import read_file, write_file
|
||||
|
||||
if DEMO_MODE or MULTI_USER_MODE:
|
||||
session.flash = T('disabled in demo mode')
|
||||
redirect(URL('default','site'))
|
||||
redirect(URL('default', 'site'))
|
||||
if not have_mercurial:
|
||||
session.flash=T("Sorry, could not find mercurial installed")
|
||||
redirect(URL('default','design',args=request.args(0)))
|
||||
session.flash = T("Sorry, could not find mercurial installed")
|
||||
redirect(URL('default', 'design', args=request.args(0)))
|
||||
|
||||
_hgignore_content = """\
|
||||
syntax: glob
|
||||
@@ -22,6 +22,7 @@ sessions/*
|
||||
errors/*
|
||||
"""
|
||||
|
||||
|
||||
def hg_repo(path):
|
||||
import os
|
||||
uio = ui.ui()
|
||||
@@ -37,13 +38,14 @@ def hg_repo(path):
|
||||
write_file(hgignore, _hgignore_content)
|
||||
return repo
|
||||
|
||||
|
||||
def commit():
|
||||
app = request.args(0)
|
||||
path = apath(app, r=request)
|
||||
repo = hg_repo(path)
|
||||
form = FORM('Comment:',INPUT(_name='comment',requires=IS_NOT_EMPTY()),
|
||||
INPUT(_type='submit',_value=T('Commit')))
|
||||
if form.accepts(request.vars,session):
|
||||
form = FORM('Comment:', INPUT(_name='comment', requires=IS_NOT_EMPTY()),
|
||||
INPUT(_type='submit', _value=T('Commit')))
|
||||
if form.accepts(request.vars, session):
|
||||
oldid = repo[repo.lookup('.')]
|
||||
addremove(repo)
|
||||
repo.commit(text=form.vars.comment)
|
||||
@@ -51,32 +53,33 @@ def commit():
|
||||
response.flash = 'no changes'
|
||||
try:
|
||||
files = TABLE(*[TR(file) for file in repo[repo.lookup('.')].files()])
|
||||
changes = TABLE(TR(TH('revision'),TH('description')))
|
||||
changes = TABLE(TR(TH('revision'), TH('description')))
|
||||
for change in repo.changelog:
|
||||
ctx=repo.changectx(change)
|
||||
ctx = repo.changectx(change)
|
||||
revision, description = ctx.rev(), ctx.description()
|
||||
changes.append(TR(A(revision,_href=URL('revision',
|
||||
args=(app,revision))),
|
||||
changes.append(TR(A(revision, _href=URL('revision',
|
||||
args=(app, revision))),
|
||||
description))
|
||||
except:
|
||||
files = []
|
||||
changes = []
|
||||
return dict(form=form,files=files,changes=changes,repo=repo)
|
||||
return dict(form=form, files=files, changes=changes, repo=repo)
|
||||
|
||||
|
||||
def revision():
|
||||
app = request.args(0)
|
||||
path = apath(app, r=request)
|
||||
repo = hg_repo(path)
|
||||
revision = request.args(1)
|
||||
ctx=repo.changectx(revision)
|
||||
form=FORM(INPUT(_type='submit',_value=T('Revert')))
|
||||
ctx = repo.changectx(revision)
|
||||
form = FORM(INPUT(_type='submit', _value=T('Revert')))
|
||||
if form.accepts(request.vars):
|
||||
hg.update(repo, revision)
|
||||
session.flash = "reverted to revision %s" % ctx.rev()
|
||||
redirect(URL('default','design',args=app))
|
||||
redirect(URL('default', 'design', args=app))
|
||||
return dict(
|
||||
files=ctx.files(),
|
||||
rev=str(ctx.rev()),
|
||||
desc=ctx.description(),
|
||||
form=form
|
||||
)
|
||||
)
|
||||
|
||||
@@ -3,31 +3,34 @@ try:
|
||||
from distutils import dir_util
|
||||
except ImportError:
|
||||
session.flash = T('requires distutils, but not installed')
|
||||
redirect(URL('default','site'))
|
||||
redirect(URL('default', 'site'))
|
||||
try:
|
||||
from git import *
|
||||
except ImportError:
|
||||
session.flash = T('requires python-git, but not installed')
|
||||
redirect(URL('default','site'))
|
||||
redirect(URL('default', 'site'))
|
||||
|
||||
|
||||
def deploy():
|
||||
apps = sorted(file for file in os.listdir(apath(r=request)))
|
||||
form = SQLFORM.factory(
|
||||
Field('osrepo',default='/tmp',label=T('Path to local openshift repo root.'),
|
||||
requires=EXISTS(error_message=T('directory not found'))),
|
||||
Field('osname',default='web2py',label=T('WSGI reference name')),
|
||||
Field('applications','list:string',
|
||||
requires=IS_IN_SET(apps,multiple=True),
|
||||
Field(
|
||||
'osrepo', default='/tmp', label=T('Path to local openshift repo root.'),
|
||||
requires=EXISTS(error_message=T('directory not found'))),
|
||||
Field('osname', default='web2py', label=T('WSGI reference name')),
|
||||
Field('applications', 'list:string',
|
||||
requires=IS_IN_SET(apps, multiple=True),
|
||||
label=T('web2py apps to deploy')))
|
||||
|
||||
cmd = output = errors= ""
|
||||
if form.accepts(request,session):
|
||||
cmd = output = errors = ""
|
||||
if form.accepts(request, session):
|
||||
try:
|
||||
kill()
|
||||
except:
|
||||
pass
|
||||
|
||||
ignore_apps = [item for item in apps if not item in form.vars.applications]
|
||||
ignore_apps = [
|
||||
item for item in apps if not item in form.vars.applications]
|
||||
regex = re.compile('\(applications/\(.*')
|
||||
w2p_origin = os.getcwd()
|
||||
osrepo = form.vars.osrepo
|
||||
@@ -38,23 +41,25 @@ def deploy():
|
||||
assert repo.bare == False
|
||||
|
||||
for i in form.vars.applications:
|
||||
appsrc = os.path.join(apath(r=request),i)
|
||||
appdest = os.path.join(osrepo,'wsgi',osname,'applications',i)
|
||||
dir_util.copy_tree(appsrc,appdest)
|
||||
appsrc = os.path.join(apath(r=request), i)
|
||||
appdest = os.path.join(osrepo, 'wsgi', osname, 'applications', i)
|
||||
dir_util.copy_tree(appsrc, appdest)
|
||||
#shutil.copytree(appsrc,appdest)
|
||||
index.add(['wsgi/'+osname+'/applications/'+i])
|
||||
index.add(['wsgi/' + osname + '/applications/' + i])
|
||||
new_commit = index.commit("Deploy from Web2py IDE")
|
||||
|
||||
origin = repo.remotes.origin
|
||||
origin.push
|
||||
origin.push()
|
||||
#Git code ends here
|
||||
return dict(form=form,command=cmd)
|
||||
return dict(form=form, command=cmd)
|
||||
|
||||
|
||||
class EXISTS(object):
|
||||
def __init__(self, error_message='file not found'):
|
||||
self.error_message = error_message
|
||||
|
||||
def __call__(self, value):
|
||||
if os.path.exists(value):
|
||||
return (value,None)
|
||||
return (value,self.error_message)
|
||||
return (value, None)
|
||||
return (value, self.error_message)
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
response.files=response.files[:3]
|
||||
response.menu=[]
|
||||
response.files = response.files[:3]
|
||||
response.menu = []
|
||||
|
||||
|
||||
def index():
|
||||
return locals()
|
||||
|
||||
|
||||
def about():
|
||||
return locals()
|
||||
|
||||
@@ -1,25 +1,29 @@
|
||||
import sys
|
||||
import cStringIO
|
||||
import gluon.contrib.shell
|
||||
import code, thread
|
||||
import code
|
||||
import thread
|
||||
from gluon.shell import env
|
||||
|
||||
if DEMO_MODE or MULTI_USER_MODE:
|
||||
session.flash = T('disabled in demo mode')
|
||||
redirect(URL('default','site'))
|
||||
redirect(URL('default', 'site'))
|
||||
|
||||
FE = 10 ** 9
|
||||
|
||||
FE=10**9
|
||||
|
||||
def index():
|
||||
app = request.args(0) or 'admin'
|
||||
reset()
|
||||
return dict(app=app)
|
||||
|
||||
|
||||
def callback():
|
||||
app = request.args[0]
|
||||
command = request.vars.statement
|
||||
escape = command[:1]!='!'
|
||||
history = session['history:'+app] = session.get('history:'+app,gluon.contrib.shell.History())
|
||||
escape = command[:1] != '!'
|
||||
history = session['history:' + app] = session.get(
|
||||
'history:' + app, gluon.contrib.shell.History())
|
||||
if not escape:
|
||||
command = command[1:]
|
||||
if command == '%reset':
|
||||
@@ -27,19 +31,20 @@ def callback():
|
||||
return '*** reset ***'
|
||||
elif command[0] == '%':
|
||||
try:
|
||||
command=session['commands:'+app][int(command[1:])]
|
||||
command = session['commands:' + app][int(command[1:])]
|
||||
except ValueError:
|
||||
return ''
|
||||
session['commands:'+app].append(command)
|
||||
environ=env(app,True)
|
||||
output = gluon.contrib.shell.run(history,command,environ)
|
||||
k = len(session['commands:'+app]) - 1
|
||||
session['commands:' + app].append(command)
|
||||
environ = env(app, True)
|
||||
output = gluon.contrib.shell.run(history, command, environ)
|
||||
k = len(session['commands:' + app]) - 1
|
||||
#output = PRE(output)
|
||||
#return TABLE(TR('In[%i]:'%k,PRE(command)),TR('Out[%i]:'%k,output))
|
||||
return 'In [%i] : %s%s\n' % (k + 1, command, output)
|
||||
|
||||
|
||||
def reset():
|
||||
app = request.args(0) or 'admin'
|
||||
session['commands:'+app] = []
|
||||
session['history:'+app] = gluon.contrib.shell.History()
|
||||
session['commands:' + app] = []
|
||||
session['history:' + app] = gluon.contrib.shell.History()
|
||||
return 'done'
|
||||
|
||||
@@ -2,10 +2,12 @@ import os
|
||||
from gluon.settings import global_settings, read_file
|
||||
#
|
||||
|
||||
|
||||
def index():
|
||||
app = request.args(0)
|
||||
return dict(app=app)
|
||||
|
||||
|
||||
def profiler():
|
||||
"""
|
||||
to use the profiler start web2py with -F profiler.log
|
||||
@@ -19,11 +21,11 @@ def profiler():
|
||||
else:
|
||||
size = 0
|
||||
if os.path.exists(filename):
|
||||
data = read_file('profiler.log','rb')
|
||||
if size<len(data):
|
||||
data = read_file('profiler.log', 'rb')
|
||||
if size < len(data):
|
||||
data = data[size:]
|
||||
else:
|
||||
size=0
|
||||
size = 0
|
||||
size += len(data)
|
||||
response.cookies[KEY] = size
|
||||
return data
|
||||
|
||||
@@ -33,7 +33,7 @@ def list_apps():
|
||||
@service.jsonrpc
|
||||
def list_files(app, pattern='.*\.py$'):
|
||||
files = listdir(apath('%s/' % app, r=request), pattern)
|
||||
return [x.replace('\\','/') for x in files]
|
||||
return [x.replace('\\', '/') for x in files]
|
||||
|
||||
|
||||
@service.jsonrpc
|
||||
@@ -43,7 +43,7 @@ def read_file(filename, b64=False):
|
||||
try:
|
||||
data = f.read()
|
||||
if not b64:
|
||||
data = data.replace('\r','')
|
||||
data = data.replace('\r', '')
|
||||
else:
|
||||
data = base64.b64encode(data)
|
||||
finally:
|
||||
@@ -82,6 +82,7 @@ def install(app_name, filename, data, overwrite=True):
|
||||
|
||||
return installed
|
||||
|
||||
|
||||
@service.jsonrpc
|
||||
def attach_debugger(host='localhost', port=6000, authkey='secret password'):
|
||||
import gluon.contrib.qdb as qdb
|
||||
@@ -124,6 +125,7 @@ def detach_debugger():
|
||||
gluon.debug.qdb_debugger = None
|
||||
return True
|
||||
|
||||
|
||||
def call():
|
||||
session.forget()
|
||||
return service()
|
||||
|
||||
@@ -1,64 +1,73 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
import os, uuid, re, pickle, urllib, glob
|
||||
import os
|
||||
import uuid
|
||||
import re
|
||||
import pickle
|
||||
import urllib
|
||||
import glob
|
||||
from gluon.admin import app_create, plugin_install
|
||||
from gluon.fileutils import abspath, read_file, write_file
|
||||
|
||||
def reset(session):
|
||||
session.app={
|
||||
'name':'',
|
||||
'params':[('title','My New App'),
|
||||
('subtitle','powered by web2py'),
|
||||
('author','you'),
|
||||
('author_email','you@example.com'),
|
||||
('keywords',''),
|
||||
('description',''),
|
||||
('layout_theme','Default'),
|
||||
('database_uri','sqlite://storage.sqlite'),
|
||||
('security_key',str(uuid.uuid4())),
|
||||
('email_server','localhost'),
|
||||
('email_sender','you@example.com'),
|
||||
('email_login',''),
|
||||
('login_method','local'),
|
||||
('login_config',''),
|
||||
('plugins',[])],
|
||||
'tables':['auth_user'],
|
||||
'table_auth_user':['username','first_name',
|
||||
'last_name','email','password'],
|
||||
'pages':['index','error'],
|
||||
'page_index':'# Welcome to my new app',
|
||||
'page_error':'# Error: the document does not exist',
|
||||
}
|
||||
|
||||
if not session.app: reset(session)
|
||||
def reset(session):
|
||||
session.app = {
|
||||
'name': '',
|
||||
'params': [('title', 'My New App'),
|
||||
('subtitle', 'powered by web2py'),
|
||||
('author', 'you'),
|
||||
('author_email', 'you@example.com'),
|
||||
('keywords', ''),
|
||||
('description', ''),
|
||||
('layout_theme', 'Default'),
|
||||
('database_uri', 'sqlite://storage.sqlite'),
|
||||
('security_key', str(uuid.uuid4())),
|
||||
('email_server', 'localhost'),
|
||||
('email_sender', 'you@example.com'),
|
||||
('email_login', ''),
|
||||
('login_method', 'local'),
|
||||
('login_config', ''),
|
||||
('plugins', [])],
|
||||
'tables': ['auth_user'],
|
||||
'table_auth_user': ['username', 'first_name',
|
||||
'last_name', 'email', 'password'],
|
||||
'pages': ['index', 'error'],
|
||||
'page_index': '# Welcome to my new app',
|
||||
'page_error': '# Error: the document does not exist',
|
||||
}
|
||||
|
||||
if not session.app:
|
||||
reset(session)
|
||||
|
||||
|
||||
def listify(x):
|
||||
if not isinstance(x,(list,tuple)):
|
||||
if not isinstance(x, (list, tuple)):
|
||||
return x and [x] or []
|
||||
return x
|
||||
|
||||
|
||||
def clean(name):
|
||||
return re.sub('\W+','_',name.strip().lower())
|
||||
return re.sub('\W+', '_', name.strip().lower())
|
||||
|
||||
|
||||
def index():
|
||||
response.view='wizard/step.html'
|
||||
response.view = 'wizard/step.html'
|
||||
reset(session)
|
||||
apps=os.listdir(os.path.join(request.folder,'..'))
|
||||
form=SQLFORM.factory(Field('name',requires=[IS_NOT_EMPTY(),
|
||||
IS_ALPHANUMERIC()]))
|
||||
apps = os.listdir(os.path.join(request.folder, '..'))
|
||||
form = SQLFORM.factory(Field('name', requires=[IS_NOT_EMPTY(),
|
||||
IS_ALPHANUMERIC()]))
|
||||
if form.accepts(request.vars):
|
||||
app = form.vars.name
|
||||
session.app['name'] = app
|
||||
if MULTI_USER_MODE and db(db.app.name==app)\
|
||||
(db.app.owner!=auth.user.id).count():
|
||||
if MULTI_USER_MODE and db(db.app.name == app)(db.app.owner != auth.user.id).count():
|
||||
session.flash = 'App belongs already to other user'
|
||||
elif app in apps:
|
||||
meta = os.path.normpath(\
|
||||
meta = os.path.normpath(
|
||||
os.path.join(os.path.normpath(request.folder),
|
||||
'..',app,'wizard.metadata'))
|
||||
'..', app, 'wizard.metadata'))
|
||||
if os.path.exists(meta):
|
||||
try:
|
||||
metafile = open(meta,'rb')
|
||||
metafile = open(meta, 'rb')
|
||||
try:
|
||||
session.app = pickle.load(metafile)
|
||||
finally:
|
||||
@@ -67,14 +76,14 @@ def index():
|
||||
except:
|
||||
session.flash = T("The app exists, was NOT created by wizard, continue to overwrite!")
|
||||
redirect(URL('step1'))
|
||||
return dict(step='Start',form=form)
|
||||
return dict(step='Start', form=form)
|
||||
|
||||
|
||||
def step1():
|
||||
from gluon.contrib.simplejson import loads
|
||||
import urllib
|
||||
if not session.themes:
|
||||
url=LAYOUTS_APP+'/default/layouts.json'
|
||||
url = LAYOUTS_APP + '/default/layouts.json'
|
||||
try:
|
||||
data = urllib.urlopen(url).read()
|
||||
session.themes = ['Default'] + loads(data)['layouts']
|
||||
@@ -82,145 +91,158 @@ def step1():
|
||||
session.themes = ['Default']
|
||||
themes = session.themes
|
||||
if not session.plugins:
|
||||
url = PLUGINS_APP+'/default/plugins.json'
|
||||
url = PLUGINS_APP + '/default/plugins.json'
|
||||
try:
|
||||
data = urllib.urlopen(url).read()
|
||||
session.plugins = loads(data)['plugins']
|
||||
except:
|
||||
session.plugins = []
|
||||
plugins = [x.split('.')[2] for x in session.plugins]
|
||||
response.view='wizard/step.html'
|
||||
response.view = 'wizard/step.html'
|
||||
params = dict(session.app['params'])
|
||||
form=SQLFORM.factory(
|
||||
Field('title',default=params.get('title',None),
|
||||
requires=IS_NOT_EMPTY()),
|
||||
Field('subtitle',default=params.get('subtitle',None)),
|
||||
Field('author',default=params.get('author',None)),
|
||||
Field('author_email',default=params.get('author_email',None)),
|
||||
Field('keywords',default=params.get('keywords',None)),
|
||||
Field('description','text',
|
||||
default=params.get('description',None)),
|
||||
Field('layout_theme',requires=IS_IN_SET(themes),
|
||||
default=params.get('layout_theme',themes[0])),
|
||||
Field('database_uri',default=params.get('database_uri',None)),
|
||||
Field('security_key',default=params.get('security_key',None)),
|
||||
Field('email_server',default=params.get('email_server',None)),
|
||||
Field('email_sender',default=params.get('email_sender',None)),
|
||||
Field('email_login',default=params.get('email_login',None)),
|
||||
Field('login_method',requires=IS_IN_SET(('local','janrain')),
|
||||
default=params.get('login_method','local')),
|
||||
Field('login_config',default=params.get('login_config',None)),
|
||||
Field('plugins','list:string',requires=IS_IN_SET(plugins,multiple=True)))
|
||||
form = SQLFORM.factory(
|
||||
Field('title', default=params.get('title', None),
|
||||
requires=IS_NOT_EMPTY()),
|
||||
Field('subtitle', default=params.get('subtitle', None)),
|
||||
Field('author', default=params.get('author', None)),
|
||||
Field(
|
||||
'author_email', default=params.get('author_email', None)),
|
||||
Field('keywords', default=params.get('keywords', None)),
|
||||
Field('description', 'text',
|
||||
default=params.get('description', None)),
|
||||
Field('layout_theme', requires=IS_IN_SET(themes),
|
||||
default=params.get('layout_theme', themes[0])),
|
||||
Field(
|
||||
'database_uri', default=params.get('database_uri', None)),
|
||||
Field(
|
||||
'security_key', default=params.get('security_key', None)),
|
||||
Field(
|
||||
'email_server', default=params.get('email_server', None)),
|
||||
Field(
|
||||
'email_sender', default=params.get('email_sender', None)),
|
||||
Field('email_login', default=params.get('email_login', None)),
|
||||
Field('login_method', requires=IS_IN_SET(('local', 'janrain')),
|
||||
default=params.get('login_method', 'local')),
|
||||
Field(
|
||||
'login_config', default=params.get('login_config', None)),
|
||||
Field('plugins', 'list:string', requires=IS_IN_SET(plugins, multiple=True)))
|
||||
|
||||
if form.accepts(request.vars):
|
||||
session.app['params']=[(key,form.vars.get(key,None))
|
||||
for key,value in session.app['params']]
|
||||
session.app['params'] = [(key, form.vars.get(key, None))
|
||||
for key, value in session.app['params']]
|
||||
redirect(URL('step2'))
|
||||
return dict(step='1: Setting Parameters',form=form)
|
||||
return dict(step='1: Setting Parameters', form=form)
|
||||
|
||||
|
||||
def step2():
|
||||
response.view='wizard/step.html'
|
||||
form=SQLFORM.factory(Field('table_names','list:string',
|
||||
default=session.app['tables']))
|
||||
response.view = 'wizard/step.html'
|
||||
form = SQLFORM.factory(Field('table_names', 'list:string',
|
||||
default=session.app['tables']))
|
||||
if form.accepts(request.vars):
|
||||
table_names = [clean(t) for t in listify(form.vars.table_names) \
|
||||
if t.strip()]
|
||||
if [t for t in table_names if t.startswith('auth_') and \
|
||||
not t=='auth_user']:
|
||||
table_names = [clean(t) for t in listify(form.vars.table_names)
|
||||
if t.strip()]
|
||||
if [t for t in table_names if t.startswith('auth_') and
|
||||
not t == 'auth_user']:
|
||||
form.error.table_names = \
|
||||
T('invalid table names (auth_* tables already defined)')
|
||||
else:
|
||||
session.app['tables']=table_names
|
||||
session.app['tables'] = table_names
|
||||
for table in session.app['tables']:
|
||||
if not 'table_'+table in session.app:
|
||||
session.app['table_'+table]=['name']
|
||||
if not table=='auth_user':
|
||||
name = table+'_manage'
|
||||
if not 'table_' + table in session.app:
|
||||
session.app['table_' + table] = ['name']
|
||||
if not table == 'auth_user':
|
||||
name = table + '_manage'
|
||||
if not name in session.app['pages']:
|
||||
session.app['pages'].append(name)
|
||||
session.app['page_'+name] = \
|
||||
session.app['page_' + name] = \
|
||||
'## Manage %s\n\n{{=form}}' % (table)
|
||||
if session.app['tables']:
|
||||
redirect(URL('step3',args=0))
|
||||
redirect(URL('step3', args=0))
|
||||
else:
|
||||
redirect(URL('step4'))
|
||||
return dict(step='2: Tables',form=form)
|
||||
return dict(step='2: Tables', form=form)
|
||||
|
||||
|
||||
def step3():
|
||||
response.view='wizard/step.html'
|
||||
n=int(request.args(0) or 0)
|
||||
m=len(session.app['tables'])
|
||||
if n>=m: redirect(URL('step2'))
|
||||
table=session.app['tables'][n]
|
||||
form=SQLFORM.factory(Field('field_names','list:string',
|
||||
default=session.app.get('table_'+table,[])))
|
||||
response.view = 'wizard/step.html'
|
||||
n = int(request.args(0) or 0)
|
||||
m = len(session.app['tables'])
|
||||
if n >= m:
|
||||
redirect(URL('step2'))
|
||||
table = session.app['tables'][n]
|
||||
form = SQLFORM.factory(Field('field_names', 'list:string',
|
||||
default=session.app.get('table_' + table, [])))
|
||||
if form.accepts(request.vars) and form.vars.field_names:
|
||||
fields=listify(form.vars.field_names)
|
||||
if table=='auth_user':
|
||||
for field in ['first_name','last_name','username','email','password']:
|
||||
fields = listify(form.vars.field_names)
|
||||
if table == 'auth_user':
|
||||
for field in ['first_name', 'last_name', 'username', 'email', 'password']:
|
||||
if not field in fields:
|
||||
fields.append(field)
|
||||
session.app['table_'+table]=[t.strip().lower()
|
||||
for t in listify(form.vars.field_names)
|
||||
if t.strip()]
|
||||
session.app['table_' + table] = [t.strip().lower()
|
||||
for t in listify(form.vars.field_names)
|
||||
if t.strip()]
|
||||
try:
|
||||
tables=sort_tables(session.app['tables'])
|
||||
tables = sort_tables(session.app['tables'])
|
||||
except RuntimeError:
|
||||
response.flash=T('invalid circular reference')
|
||||
response.flash = T('invalid circular reference')
|
||||
else:
|
||||
if n<m-1:
|
||||
redirect(URL('step3',args=n+1))
|
||||
if n < m - 1:
|
||||
redirect(URL('step3', args=n + 1))
|
||||
else:
|
||||
redirect(URL('step4'))
|
||||
return dict(step='3: Fields for table "%s" (%s of %s)' \
|
||||
% (table,n+1,m),table=table,form=form)
|
||||
return dict(step='3: Fields for table "%s" (%s of %s)'
|
||||
% (table, n + 1, m), table=table, form=form)
|
||||
|
||||
|
||||
def step4():
|
||||
response.view='wizard/step.html'
|
||||
form=SQLFORM.factory(Field('pages','list:string',
|
||||
default=session.app['pages']))
|
||||
response.view = 'wizard/step.html'
|
||||
form = SQLFORM.factory(Field('pages', 'list:string',
|
||||
default=session.app['pages']))
|
||||
if form.accepts(request.vars):
|
||||
session.app['pages']=[clean(t)
|
||||
for t in listify(form.vars.pages)
|
||||
if t.strip()]
|
||||
session.app['pages'] = [clean(t)
|
||||
for t in listify(form.vars.pages)
|
||||
if t.strip()]
|
||||
if session.app['pages']:
|
||||
redirect(URL('step5',args=0))
|
||||
redirect(URL('step5', args=0))
|
||||
else:
|
||||
redirect(URL('step6'))
|
||||
return dict(step='4: Pages',form=form)
|
||||
return dict(step='4: Pages', form=form)
|
||||
|
||||
|
||||
def step5():
|
||||
response.view='wizard/step.html'
|
||||
n=int(request.args(0) or 0)
|
||||
m=len(session.app['pages'])
|
||||
if n>=m: redirect(URL('step4'))
|
||||
page=session.app['pages'][n]
|
||||
markmin_url='http://web2py.com/examples/static/markmin.html'
|
||||
form=SQLFORM.factory(Field('content','text',
|
||||
default=session.app.get('page_'+page,[]),
|
||||
comment=A('use markmin',
|
||||
_href=markmin_url,_target='_blank')),
|
||||
formstyle='table2cols')
|
||||
response.view = 'wizard/step.html'
|
||||
n = int(request.args(0) or 0)
|
||||
m = len(session.app['pages'])
|
||||
if n >= m:
|
||||
redirect(URL('step4'))
|
||||
page = session.app['pages'][n]
|
||||
markmin_url = 'http://web2py.com/examples/static/markmin.html'
|
||||
form = SQLFORM.factory(Field('content', 'text',
|
||||
default=session.app.get('page_' + page, []),
|
||||
comment=A('use markmin',
|
||||
_href=markmin_url, _target='_blank')),
|
||||
formstyle='table2cols')
|
||||
if form.accepts(request.vars):
|
||||
session.app['page_'+page]=form.vars.content
|
||||
if n<m-1:
|
||||
redirect(URL('step5',args=n+1))
|
||||
session.app['page_' + page] = form.vars.content
|
||||
if n < m - 1:
|
||||
redirect(URL('step5', args=n + 1))
|
||||
else:
|
||||
redirect(URL('step6'))
|
||||
return dict(step='5: View for page "%s" (%s of %s)' % (page,n+1,m),form=form)
|
||||
return dict(step='5: View for page "%s" (%s of %s)' % (page, n + 1, m), form=form)
|
||||
|
||||
|
||||
def step6():
|
||||
response.view='wizard/step.html'
|
||||
response.view = 'wizard/step.html'
|
||||
params = dict(session.app['params'])
|
||||
app = session.app['name']
|
||||
form=SQLFORM.factory(
|
||||
Field('generate_model','boolean',default=True),
|
||||
Field('generate_controller','boolean',default=True),
|
||||
Field('generate_views','boolean',default=True),
|
||||
Field('generate_menu','boolean',default=True),
|
||||
Field('apply_layout','boolean',default=True),
|
||||
Field('erase_database','boolean',default=True),
|
||||
Field('populate_database','boolean',default=True))
|
||||
form = SQLFORM.factory(
|
||||
Field('generate_model', 'boolean', default=True),
|
||||
Field('generate_controller', 'boolean', default=True),
|
||||
Field('generate_views', 'boolean', default=True),
|
||||
Field('generate_menu', 'boolean', default=True),
|
||||
Field('apply_layout', 'boolean', default=True),
|
||||
Field('erase_database', 'boolean', default=True),
|
||||
Field('populate_database', 'boolean', default=True))
|
||||
if form.accepts(request.vars):
|
||||
if DEMO_MODE:
|
||||
session.flash = T('Application cannot be generated in demo mode')
|
||||
@@ -228,159 +250,173 @@ def step6():
|
||||
create(form.vars)
|
||||
session.flash = 'Application %s created' % app
|
||||
redirect(URL('generated'))
|
||||
return dict(step='6: Generate app "%s"' % app,form=form)
|
||||
return dict(step='6: Generate app "%s"' % app, form=form)
|
||||
|
||||
|
||||
def generated():
|
||||
return dict(app=session.app['name'])
|
||||
|
||||
|
||||
def sort_tables(tables):
|
||||
import re
|
||||
regex = re.compile('(%s)' % '|'.join(tables))
|
||||
is_auth_user = 'auth_user' in tables
|
||||
d={}
|
||||
d = {}
|
||||
for table in tables:
|
||||
d[table]=[]
|
||||
d[table] = []
|
||||
for field in session.app['table_%s' % table]:
|
||||
d[table]+=regex.findall(field)
|
||||
tables=[]
|
||||
d[table] += regex.findall(field)
|
||||
tables = []
|
||||
if is_auth_user:
|
||||
tables.append('auth_user')
|
||||
def append(table,trail=[]):
|
||||
|
||||
def append(table, trail=[]):
|
||||
if table in trail:
|
||||
raise RuntimeError
|
||||
for t in d[table]:
|
||||
# if not t==table: (problem, no dropdown for self references)
|
||||
append(t,trail=trail+[table])
|
||||
append(t, trail=trail + [table])
|
||||
if not table in tables:
|
||||
tables.append(table)
|
||||
for table in d: append(table)
|
||||
for table in d:
|
||||
append(table)
|
||||
return tables
|
||||
|
||||
def make_table(table,fields):
|
||||
rawtable=table
|
||||
if table!='auth_user': table='t_'+table
|
||||
s=''
|
||||
s+='\n'+'#'*40+'\n'
|
||||
s+="db.define_table('%s',\n" % table
|
||||
first_field='id'
|
||||
|
||||
def make_table(table, fields):
|
||||
rawtable = table
|
||||
if table != 'auth_user':
|
||||
table = 't_' + table
|
||||
s = ''
|
||||
s += '\n' + '#' * 40 + '\n'
|
||||
s += "db.define_table('%s',\n" % table
|
||||
first_field = 'id'
|
||||
for field in fields:
|
||||
items=[x.lower() for x in field.split()]
|
||||
items = [x.lower() for x in field.split()]
|
||||
has = {}
|
||||
keys = []
|
||||
for key in ['notnull','unique','integer','double','boolean','float',
|
||||
'boolean', 'date','time','datetime','text','wiki',
|
||||
'html','file','upload','image','true',
|
||||
'hidden','readonly','writeonly','multiple',
|
||||
'notempty','required']:
|
||||
for key in ['notnull', 'unique', 'integer', 'double', 'boolean', 'float',
|
||||
'boolean', 'date', 'time', 'datetime', 'text', 'wiki',
|
||||
'html', 'file', 'upload', 'image', 'true',
|
||||
'hidden', 'readonly', 'writeonly', 'multiple',
|
||||
'notempty', 'required']:
|
||||
if key in items[1:]:
|
||||
keys.append(key)
|
||||
has[key] = True
|
||||
tables = session.app['tables']
|
||||
refs = [t for t in tables if t in items]
|
||||
items = items[:1] + [x for x in items[1:] \
|
||||
if not x in keys and not x in tables]
|
||||
items = items[:1] + [x for x in items[1:]
|
||||
if not x in keys and not x in tables]
|
||||
barename = name = '_'.join(items)
|
||||
if table[:2]=='t_': name='f_'+name
|
||||
if first_field=='id': first_field=name
|
||||
if table[:2] == 't_': name = 'f_' + name
|
||||
if first_field == 'id':
|
||||
first_field = name
|
||||
|
||||
### determine field type
|
||||
ftype='string'
|
||||
deftypes={'integer':'integer','double':'double','boolean':'boolean',
|
||||
'float':'double','bool':'boolean',
|
||||
'date':'date','time':'time','datetime':'datetime',
|
||||
'text':'text','file':'upload','image':'upload',
|
||||
'upload':'upload','wiki':'text', 'html':'text'}
|
||||
for key,t in deftypes.items():
|
||||
ftype = 'string'
|
||||
deftypes = {'integer': 'integer', 'double': 'double', 'boolean': 'boolean',
|
||||
'float': 'double', 'bool': 'boolean',
|
||||
'date': 'date', 'time': 'time', 'datetime': 'datetime',
|
||||
'text': 'text', 'file': 'upload', 'image': 'upload',
|
||||
'upload': 'upload', 'wiki': 'text', 'html': 'text'}
|
||||
for key, t in deftypes.items():
|
||||
if key in has:
|
||||
ftype = t
|
||||
if refs:
|
||||
key = refs[0]
|
||||
if not key=='auth_user': key='t_'+key
|
||||
if not key == 'auth_user':
|
||||
key = 't_' + key
|
||||
if 'multiple' in has:
|
||||
ftype='list:reference %s' % key
|
||||
ftype = 'list:reference %s' % key
|
||||
else:
|
||||
ftype='reference %s' % key
|
||||
if ftype=='string' and 'multiple' in has:
|
||||
ftype='list:string'
|
||||
elif ftype=='integer' and 'multiple' in has:
|
||||
ftype='list:integer'
|
||||
elif name=='password':
|
||||
ftype='password'
|
||||
s+=" Field('%s', type='%s'" % (name, ftype)
|
||||
ftype = 'reference %s' % key
|
||||
if ftype == 'string' and 'multiple' in has:
|
||||
ftype = 'list:string'
|
||||
elif ftype == 'integer' and 'multiple' in has:
|
||||
ftype = 'list:integer'
|
||||
elif name == 'password':
|
||||
ftype = 'password'
|
||||
s += " Field('%s', type='%s'" % (name, ftype)
|
||||
|
||||
### determine field attributes
|
||||
if 'notnull' in has or 'notempty' in has or 'required' in has:
|
||||
s+=', notnull=True'
|
||||
s += ', notnull=True'
|
||||
if 'unique' in has:
|
||||
s+=', unique=True'
|
||||
if ftype=='boolean' and 'true' in has:
|
||||
s+=",\n default=True"
|
||||
s += ', unique=True'
|
||||
if ftype == 'boolean' and 'true' in has:
|
||||
s += ",\n default=True"
|
||||
|
||||
### determine field representation
|
||||
elif 'wiki' in has:
|
||||
s+=",\n represent=lambda x, row: MARKMIN(x)"
|
||||
s+=",\n comment='WIKI (markmin)'"
|
||||
s += ",\n represent=lambda x, row: MARKMIN(x)"
|
||||
s += ",\n comment='WIKI (markmin)'"
|
||||
elif 'html' in has:
|
||||
s+=",\n represent=lambda x, row: XML(x,sanitize=True)"
|
||||
s+=",\n comment='HTML (sanitized)'"
|
||||
s += ",\n represent=lambda x, row: XML(x,sanitize=True)"
|
||||
s += ",\n comment='HTML (sanitized)'"
|
||||
### determine field access
|
||||
if name=='password' or 'writeonly' in has:
|
||||
s+=",\n readable=False"
|
||||
if name == 'password' or 'writeonly' in has:
|
||||
s += ",\n readable=False"
|
||||
elif 'hidden' in has:
|
||||
s+=",\n writable=False, readable=False"
|
||||
s += ",\n writable=False, readable=False"
|
||||
elif 'readonly' in has:
|
||||
s+=",\n writable=False"
|
||||
s += ",\n writable=False"
|
||||
|
||||
### make up a label
|
||||
s+=",\n label=T('%s')),\n" % \
|
||||
s += ",\n label=T('%s')),\n" % \
|
||||
' '.join(x.capitalize() for x in barename.split('_'))
|
||||
if table=='auth_user':
|
||||
s+=" Field('created_on','datetime',default=request.now,\n"
|
||||
s+=" label=T('Created On'),writable=False,readable=False),\n"
|
||||
s+=" Field('modified_on','datetime',default=request.now,\n"
|
||||
s+=" label=T('Modified On'),writable=False,readable=False,\n"
|
||||
s+=" update=request.now),\n"
|
||||
s+=" Field('registration_key',default='',\n"
|
||||
s+=" writable=False,readable=False),\n"
|
||||
s+=" Field('reset_password_key',default='',\n"
|
||||
s+=" writable=False,readable=False),\n"
|
||||
s+=" Field('registration_id',default='',\n"
|
||||
s+=" writable=False,readable=False),\n"
|
||||
if table == 'auth_user':
|
||||
s += " Field('created_on','datetime',default=request.now,\n"
|
||||
s += " label=T('Created On'),writable=False,readable=False),\n"
|
||||
s += " Field('modified_on','datetime',default=request.now,\n"
|
||||
s += " label=T('Modified On'),writable=False,readable=False,\n"
|
||||
s += " update=request.now),\n"
|
||||
s += " Field('registration_key',default='',\n"
|
||||
s += " writable=False,readable=False),\n"
|
||||
s += " Field('reset_password_key',default='',\n"
|
||||
s += " writable=False,readable=False),\n"
|
||||
s += " Field('registration_id',default='',\n"
|
||||
s += " writable=False,readable=False),\n"
|
||||
elif 'auth_user' in session.app['tables']:
|
||||
s+=" auth.signature,\n"
|
||||
s+=" format='%("+first_field+")s',\n"
|
||||
s+=" migrate=settings.migrate)\n\n"
|
||||
if table=='auth_user':
|
||||
s+="""
|
||||
db.auth_user.first_name.requires = IS_NOT_EMPTY(error_message=auth.messages.is_empty)
|
||||
db.auth_user.last_name.requires = IS_NOT_EMPTY(error_message=auth.messages.is_empty)
|
||||
db.auth_user.password.requires = CRYPT(key=auth.settings.hmac_key, min_length=4)
|
||||
s += " auth.signature,\n"
|
||||
s += " format='%(" + first_field + ")s',\n"
|
||||
s += " migrate=settings.migrate)\n\n"
|
||||
if table == 'auth_user':
|
||||
s += """
|
||||
db.auth_user.first_name.requires = IS_NOT_EMPTY(
|
||||
error_message=auth.messages.is_empty)
|
||||
db.auth_user.last_name.requires = IS_NOT_EMPTY(
|
||||
error_message=auth.messages.is_empty)
|
||||
db.auth_user.password.requires = CRYPT(
|
||||
key=auth.settings.hmac_key, min_length=4)
|
||||
db.auth_user.username.requires = IS_NOT_IN_DB(db, db.auth_user.username)
|
||||
db.auth_user.email.requires = (IS_EMAIL(error_message=auth.messages.invalid_email),
|
||||
db.auth_user.email.requires = (
|
||||
IS_EMAIL(error_message=auth.messages.invalid_email),
|
||||
IS_NOT_IN_DB(db, db.auth_user.email))
|
||||
"""
|
||||
else:
|
||||
s+="db.define_table('%s_archive',db.%s,Field('current_record','reference %s',readable=False,writable=False))\n" % (table,table,table)
|
||||
s += "db.define_table('%s_archive',db.%s,Field('current_record','reference %s',readable=False,writable=False))\n" % (table, table, table)
|
||||
return s
|
||||
|
||||
|
||||
def fix_db(filename):
|
||||
params = dict(session.app['params'])
|
||||
content = read_file(filename,'rb')
|
||||
content = read_file(filename, 'rb')
|
||||
if 'auth_user' in session.app['tables']:
|
||||
auth_user = make_table('auth_user',session.app['table_auth_user'])
|
||||
auth_user = make_table('auth_user', session.app['table_auth_user'])
|
||||
content = content.replace('sqlite://storage.sqlite',
|
||||
params['database_uri'])
|
||||
content = content.replace('auth.define_tables()',\
|
||||
auth_user+'auth.define_tables(migrate = settings.migrate)')
|
||||
params['database_uri'])
|
||||
content = content.replace('auth.define_tables()',
|
||||
auth_user + 'auth.define_tables(migrate = settings.migrate)')
|
||||
content += """
|
||||
mail.settings.server = settings.email_server
|
||||
mail.settings.sender = settings.email_sender
|
||||
mail.settings.login = settings.email_login
|
||||
"""
|
||||
if params['login_method']=='janrain':
|
||||
content+="""
|
||||
if params['login_method'] == 'janrain':
|
||||
content += """
|
||||
from gluon.contrib.login_methods.rpx_account import RPXAccount
|
||||
auth.settings.actions_disabled=['register','change_password','request_reset_password']
|
||||
auth.settings.actions_disabled=['register','change_password',
|
||||
'request_reset_password']
|
||||
auth.settings.login_form = RPXAccount(request,
|
||||
api_key = settings.login_config.split(':')[-1],
|
||||
domain = settings.login_config.split(':')[0],
|
||||
@@ -388,14 +424,15 @@ auth.settings.login_form = RPXAccount(request,
|
||||
"""
|
||||
write_file(filename, content, 'wb')
|
||||
|
||||
|
||||
def make_menu(pages):
|
||||
s=''
|
||||
s+='response.title = settings.title\n'
|
||||
s+='response.subtitle = settings.subtitle\n'
|
||||
s+="response.meta.author = '%(author)s <%(author_email)s>' % settings\n"
|
||||
s+='response.meta.keywords = settings.keywords\n'
|
||||
s+='response.meta.description = settings.description\n'
|
||||
s+='response.menu = [\n'
|
||||
s = ''
|
||||
s += 'response.title = settings.title\n'
|
||||
s += 'response.subtitle = settings.subtitle\n'
|
||||
s += "response.meta.author = '%(author)s <%(author_email)s>' % settings\n"
|
||||
s += 'response.meta.keywords = settings.keywords\n'
|
||||
s += 'response.meta.description = settings.description\n'
|
||||
s += 'response.menu = [\n'
|
||||
for page in pages:
|
||||
if not page.startswith('error'):
|
||||
if page.endswith('_manage'):
|
||||
@@ -403,65 +440,70 @@ def make_menu(pages):
|
||||
else:
|
||||
page_name = page
|
||||
page_name = ' '.join(x.capitalize() for x in page_name.split('_'))
|
||||
s+="(T('%s'),URL('default','%s')==URL(),URL('default','%s'),[]),\n" \
|
||||
% (page_name,page,page)
|
||||
s+=']'
|
||||
s += "(T('%s'),URL('default','%s')==URL(),URL('default','%s'),[]),\n" \
|
||||
% (page_name, page, page)
|
||||
s += ']'
|
||||
return s
|
||||
|
||||
def make_page(page,contents):
|
||||
if 'auth_user' in session.app['tables'] and not page in ('index','error'):
|
||||
s="@auth.requires_login()\ndef %s():\n" % page
|
||||
|
||||
def make_page(page, contents):
|
||||
if 'auth_user' in session.app['tables'] and not page in ('index', 'error'):
|
||||
s = "@auth.requires_login()\ndef %s():\n" % page
|
||||
else:
|
||||
s="def %s():\n" % page
|
||||
items = page.rsplit('_',1)
|
||||
if items[0] in session.app['tables'] and len(items)==2 and items[1]=='manage':
|
||||
s+=" form = SQLFORM.smartgrid(db.t_%s,onupdate=auth.archive)\n" % items[0]
|
||||
s+=" return locals()\n\n"
|
||||
s = "def %s():\n" % page
|
||||
items = page.rsplit('_', 1)
|
||||
if items[0] in session.app['tables'] and len(items) == 2 and items[1] == 'manage':
|
||||
s += " form = SQLFORM.smartgrid(db.t_%s,onupdate=auth.archive)\n" % items[0]
|
||||
s += " return locals()\n\n"
|
||||
else:
|
||||
s+=" return dict()\n\n"
|
||||
s += " return dict()\n\n"
|
||||
return s
|
||||
|
||||
def make_view(page,contents):
|
||||
s="{{extend 'layout.html'}}\n\n"
|
||||
s+=str(MARKMIN(contents))
|
||||
|
||||
def make_view(page, contents):
|
||||
s = "{{extend 'layout.html'}}\n\n"
|
||||
s += str(MARKMIN(contents))
|
||||
return s
|
||||
|
||||
|
||||
def populate(tables):
|
||||
s = 'from gluon.contrib.populate import populate\n'
|
||||
s+= 'if db(db.auth_user).isempty():\n'
|
||||
s += 'if db(db.auth_user).isempty():\n'
|
||||
for table in sort_tables(tables):
|
||||
t=table=='auth_user' and 'auth_user' or 't_'+table
|
||||
s+=" populate(db.%s,10)\n" % t
|
||||
t = table == 'auth_user' and 'auth_user' or 't_' + table
|
||||
s += " populate(db.%s,10)\n" % t
|
||||
return s
|
||||
|
||||
|
||||
def create(options):
|
||||
if DEMO_MODE:
|
||||
session.flash = T('disabled in demo mode')
|
||||
redirect(URL('step6'))
|
||||
params = dict(session.app['params'])
|
||||
app = session.app['name']
|
||||
if app_create(app,request,force=True,key=params['security_key']):
|
||||
if app_create(app, request, force=True, key=params['security_key']):
|
||||
if MULTI_USER_MODE:
|
||||
db.app.insert(name=app,owner=auth.user.id)
|
||||
db.app.insert(name=app, owner=auth.user.id)
|
||||
else:
|
||||
session.flash = 'Failure to create application'
|
||||
redirect(URL('step6'))
|
||||
|
||||
### save metadata in newapp/wizard.metadata
|
||||
try:
|
||||
meta = os.path.join(request.folder,'..',app,'wizard.metadata')
|
||||
file=open(meta,'wb')
|
||||
pickle.dump(session.app,file)
|
||||
meta = os.path.join(request.folder, '..', app, 'wizard.metadata')
|
||||
file = open(meta, 'wb')
|
||||
pickle.dump(session.app, file)
|
||||
file.close()
|
||||
except IOError:
|
||||
session.flash = 'Failure to write wizard metadata'
|
||||
redirect(URL('step6'))
|
||||
|
||||
### apply theme
|
||||
if options.apply_layout and params['layout_theme']!='Default':
|
||||
if options.apply_layout and params['layout_theme'] != 'Default':
|
||||
try:
|
||||
fn = 'web2py.plugin.layout_%s.w2p' % params['layout_theme']
|
||||
theme = urllib.urlopen(LAYOUTS_APP+'/static/plugin_layouts/plugins/'+fn)
|
||||
theme = urllib.urlopen(
|
||||
LAYOUTS_APP + '/static/plugin_layouts/plugins/' + fn)
|
||||
plugin_install(app, theme, request, fn)
|
||||
except:
|
||||
session.flash = T("unable to download layout")
|
||||
@@ -469,55 +511,58 @@ def create(options):
|
||||
### apply plugins
|
||||
for plugin in params['plugins']:
|
||||
try:
|
||||
plugin_name = 'web2py.plugin.'+plugin+'.w2p'
|
||||
stream = urllib.urlopen(PLUGINS_APP+'/static/'+plugin_name)
|
||||
plugin_name = 'web2py.plugin.' + plugin + '.w2p'
|
||||
stream = urllib.urlopen(PLUGINS_APP + '/static/' + plugin_name)
|
||||
plugin_install(app, stream, request, plugin_name)
|
||||
except Exception, e:
|
||||
session.flash = T("unable to download plugin: %s" % plugin)
|
||||
|
||||
### write configuration file into newapp/models/0.py
|
||||
model = os.path.join(request.folder,'..',app,'models','0.py')
|
||||
model = os.path.join(request.folder, '..', app, 'models', '0.py')
|
||||
file = open(model, 'wb')
|
||||
try:
|
||||
file.write("from gluon.storage import Storage\n")
|
||||
file.write("settings = Storage()\n\n")
|
||||
file.write("settings.migrate = True\n")
|
||||
for key,value in session.app['params']:
|
||||
file.write("settings.%s = %s\n" % (key,repr(value)))
|
||||
for key, value in session.app['params']:
|
||||
file.write("settings.%s = %s\n" % (key, repr(value)))
|
||||
finally:
|
||||
file.close()
|
||||
|
||||
### write configuration file into newapp/models/menu.py
|
||||
if options.generate_menu:
|
||||
model = os.path.join(request.folder,'..',app,'models','menu.py')
|
||||
file = open(model,'wb')
|
||||
model = os.path.join(request.folder, '..', app, 'models', 'menu.py')
|
||||
file = open(model, 'wb')
|
||||
try:
|
||||
file.write(make_menu(session.app['pages']))
|
||||
finally:
|
||||
file.close()
|
||||
|
||||
### customize the auth_user table
|
||||
model = os.path.join(request.folder,'..',app,'models','db.py')
|
||||
model = os.path.join(request.folder, '..', app, 'models', 'db.py')
|
||||
fix_db(model)
|
||||
|
||||
### create newapp/models/db_wizard.py
|
||||
if options.generate_model:
|
||||
model = os.path.join(request.folder,'..',app,'models','db_wizard.py')
|
||||
file = open(model,'wb')
|
||||
model = os.path.join(
|
||||
request.folder, '..', app, 'models', 'db_wizard.py')
|
||||
file = open(model, 'wb')
|
||||
try:
|
||||
file.write('### we prepend t_ to tablenames and f_ to fieldnames for disambiguity\n\n')
|
||||
tables = sort_tables(session.app['tables'])
|
||||
for table in tables:
|
||||
if table=='auth_user': continue
|
||||
file.write(make_table(table,session.app['table_'+table]))
|
||||
if table == 'auth_user':
|
||||
continue
|
||||
file.write(make_table(table, session.app['table_' + table]))
|
||||
finally:
|
||||
file.close()
|
||||
|
||||
model = os.path.join(request.folder,'..',app,
|
||||
'models','db_wizard_populate.py')
|
||||
if os.path.exists(model): os.unlink(model)
|
||||
model = os.path.join(request.folder, '..', app,
|
||||
'models', 'db_wizard_populate.py')
|
||||
if os.path.exists(model):
|
||||
os.unlink(model)
|
||||
if options.populate_database and session.app['tables']:
|
||||
file = open(model,'wb')
|
||||
file = open(model, 'wb')
|
||||
try:
|
||||
file.write(populate(session.app['tables']))
|
||||
finally:
|
||||
@@ -525,8 +570,9 @@ def create(options):
|
||||
|
||||
### create newapp/controllers/default.py
|
||||
if options.generate_controller:
|
||||
controller = os.path.join(request.folder,'..',app,'controllers','default.py')
|
||||
file = open(controller,'wb')
|
||||
controller = os.path.join(
|
||||
request.folder, '..', app, 'controllers', 'default.py')
|
||||
file = open(controller, 'wb')
|
||||
try:
|
||||
file.write("""# -*- coding: utf-8 -*-
|
||||
### required - do no delete
|
||||
@@ -536,21 +582,24 @@ def call(): return service()
|
||||
### end requires
|
||||
""")
|
||||
for page in session.app['pages']:
|
||||
file.write(make_page(page,session.app.get('page_'+page,'')))
|
||||
file.write(
|
||||
make_page(page, session.app.get('page_' + page, '')))
|
||||
finally:
|
||||
file.close()
|
||||
|
||||
### create newapp/views/default/*.html
|
||||
if options.generate_views:
|
||||
for page in session.app['pages']:
|
||||
view = os.path.join(request.folder,'..',app,'views','default',page+'.html')
|
||||
file = open(view,'wb')
|
||||
view = os.path.join(
|
||||
request.folder, '..', app, 'views', 'default', page + '.html')
|
||||
file = open(view, 'wb')
|
||||
try:
|
||||
file.write(make_view(page,session.app.get('page_'+page,'')))
|
||||
file.write(
|
||||
make_view(page, session.app.get('page_' + page, '')))
|
||||
finally:
|
||||
file.close()
|
||||
|
||||
if options.erase_database:
|
||||
path = os.path.join(request.folder,'..',app,'databases','*')
|
||||
path = os.path.join(request.folder, '..', app, 'databases', '*')
|
||||
for file in glob.glob(path):
|
||||
os.unlink(file)
|
||||
|
||||
Reference in New Issue
Block a user