def process_signup():
email = bottle.request.forms.get("email")
username = bottle.request.forms.get("username")
password = bottle.request.forms.get("password")
verify = bottle.request.forms.get("verify")
# set these up in case we have an error case
errors = {'username': cgi.escape(username), 'email': cgi.escape(email)}
if validate_signup(username, password, verify, email, errors):
if not users.add_user(username, password, email):
# this was a duplicate
errors['username_error'] = ("Username already in use. " +
"Please choose another")
return bottle.template("signup", errors)
session_id = sessions.start_session(username)
print session_id
bottle.response.set_cookie("session", session_id)
bottle.redirect("/welcome")
else:
print "user did not validate"
return bottle.template("signup", errors)
python类template()的实例源码
def present_welcome():
# check for a cookie, if present, then extract value
cookie = bottle.request.get_cookie("session")
username = sessions.get_username(cookie) # see if user is logged in
if username is None:
print "welcome: can't identify user...redirecting to signup"
bottle.redirect("/signup")
return bottle.template("welcome", {'username': username})
# Helper Functions
# extracts the tag from the tags form element. An experienced python
# programmer could do this in fewer lines, no doubt
def index_tpl(**kwargs):
return template('index', **kwargs)
def show_main_page(user=None):
user = user or get_logged_in_user()
if user is None:
return template('login', null=None)
heading = 'Posts from people you follow'
posts = pubsub.posts_for_user(user)
return dict(user=user, posts=posts, heading=heading, comb=comb)
def post_message():
user = get_logged_in_user()
if user is None:
return template('login', null=None)
text = request.forms.get('text', '')
if text:
pubsub.post_message(user, text)
return show_main_page(user)
def prepare(self, **options):
from mako.template import Template
from mako.lookup import TemplateLookup
from plim import preprocessor
options.update({'input_encoding':self.encoding})
options.setdefault('format_exceptions', bool(DEBUG))
lookup = TemplateLookup(directories=self.lookup, **options)
if self.source:
self.tpl = Template(self.source, preprocessor = preprocessor, lookup=lookup, **options)
else:
self.tpl = Template(uri=self.name, preprocessor = preprocessor, filename=self.filename, lookup=lookup, **options)
def stpl(tsk):
ps = tsk.inputs[0].abspath()
pt = tsk.outputs[0].abspath()
bld = tsk.generator.bld
lookup,name=os.path.split(ps)
st=bottle.template(name,template_lookup=[lookup], company = bld.env.company, guiname=bld.env.guiname, version=bld.env.version,
dllname=bld.env.dllname, maxfuni=bld.env.maxfuni)
with codecs.open(pt,mode='w',encoding="utf-8") as f: f.write(st)
os.chmod(pt, 493)
# copy files that already exist
def stpl(tsk):
ps = tsk.inputs[0].abspath()
pt = tsk.outputs[0].abspath()
bld = tsk.generator.bld
lookup,name=os.path.split(ps)
st=bottle.template(name,template_lookup=[lookup], company = bld.env.company, guiname=bld.env.guiname, version=bld.env.version,
dllname=bld.env.dllname, maxfuni=bld.env.maxfuni)
with codecs.open(pt,mode='w',encoding="utf-8") as f: f.write(st)
os.chmod(pt, 493)
# copy files that already exist
def show_message(msg):
"""Display a message if the msg value is greater than 2 characters
in the path.
"""
valid_length = len(msg) >= MIN_MSG_LENGTH
valid_name = re.match('^[a-z\-]+$', msg.lower()) is not None
if valid_length and valid_name:
return template(TEMPLATE_STRING, h1=msg)
else:
error_msg = "Sorry, only alpha characters and hyphens allowed."
raise Exception(error_msg)
def get_service_journal_page(service):
if service in config.sections():
if get_service_action(service, 'status')['status'] == 'not-found':
abort(400,'Sorry, but service \'{}\' unit not found in system.'.format(config.get(service, 'title')))
journal_lines = get_service_journal(service, 100)
return template('journal', hostname=gethostname(), service=config.get(service, 'title'), journal=journal_lines['journal'])
else:
abort(400, 'Sorry, but \'{}\' is not defined in config.'.format(service))
# Serve static content
def homepage():
return template(stpl.homepage, {'conf': conf})
def reload_cron():
worker.load_crontab()
previous = request.headers.get('Referer', '/')
return template(stpl.reload_cron, previous=previous)
def log():
mode = request.query.get('mode', 'cron')
sort = request.query.get('sort', 'new')
page = int(request.query.page or 1)
data = []
if os.path.exists(conf.log):
with open(conf.log, 'rb') as f:
lines = map(lambda s: s.decode('utf8'), f.readlines())
data = [line for line in lines
if line.startswith(mode.title())]
data = data[::-1] if sort == 'new' else data
neg_sort = {
'new': {'sort': 'old', 'title': '????'},
'old': {'sort': 'new', 'title': '????'}
}
neg_mode = {
'cron': {'mode': 'task', 'title': '????'},
'task': {'mode': 'cron', 'title': '????'}
}
context = {
'title': '?? %s ??' % mode.title(),
'data': data[(page - 1) * 10: page * 10],
'mode': mode,
'page': page,
'count': len(data),
'sort': neg_sort[sort],
'other': neg_mode[mode]
}
return template(stpl.log, context)
def index():
return template("index")
def showmyapps():
user = root.authorized()
uid = users(user=user).id
app = root.active_app()
result = db((apps.id == app_user.appid) & (uid == app_user.uid)).select(orderby=apps.name)
if user == "admin":
configurable = True
else:
configurable = False
params = { 'configurable': configurable, 'user': user, 'app': app }
return template('myapps', params, rows=result)
def app_edit(appid):
user = root.authorized()
if user != 'admin':
return template('error', err="must be admin to edit app")
cid = request.forms.cid
app = request.forms.app
result = db(apps.name==app).select().first()
params = {'app': app, 'cid': cid}
return template('app_edit', params, rows=result)
def getaddapp():
user = root.authorized()
if user != 'admin':
return template('error', err="must be admin to add app")
return template('appconfig/addapp')
def appconfig_status():
root.authorized()
status = dict()
app = request.query.app
# check db file
appname = apps(name=app).name
if appname:
status['command'] = 1
else:
status['command'] = 0
# check template file
if os.path.exists("views/apps/"+app+".tpl"):
status['template'] = 1
else:
status['template'] = 0
# check inputs file
extension = {'namelist':'.in', 'ini':'.ini', 'xml':'.xml', 'json':'.json', 'yaml':'.yaml', 'toml':'.toml'}
if os.path.exists(os.path.join(apprw.apps_dir, app,
app + extension[root.myapps[app].input_format])):
status['inputs'] = 1
else:
status['inputs'] = 0
# check app binary
if os.path.exists(os.path.join(apprw.apps_dir, app, app)):
status['binary'] = 1
else:
status['binary'] = 0
# check plots
appid = apps(name=app).id
result = db(plots.appid==appid).select().first()
if result:
status['plots'] = 1
else:
status['plots'] = 0
return json.dumps(status)
def appconfig_exe(step="upload"):
user = root.authorized()
if user != 'admin':
return template('error', err="must be admin to configure app")
if step == "upload":
appname = request.forms.appname
params = {'appname': appname}
return template('appconfig/exe_upload', params)
elif step == "test":
appname = request.forms.appname
upload = request.files.upload
if not upload:
return template('appconfig/error',
err="no file selected. press back button and try again")
name, ext = os.path.splitext(upload.filename)
# if ext not in ('.exe','.sh','.xml','.json',):
# return 'ERROR: File extension apps not allowed.'
try:
save_path_dir = os.path.join(apprw.apps_dir, name)
if not os.path.exists(save_path_dir):
os.makedirs(save_path_dir)
save_path = os.path.join(save_path_dir, name) + ext
if os.path.isfile(save_path):
timestr = time.strftime("%Y%m%d-%H%M%S")
shutil.move(save_path, save_path+"."+timestr)
upload.save(save_path)
os.chmod(save_path, 0700)
# process = subprocess.Popen(["otool -L", save_path], stdout=subprocess.PIPE, stdin=subprocess.PIPE)
# contents = process.readlines()
contents = "SUCCESS"
params = {'appname': appname, 'contents': contents}
return template('appconfig/exe_test', params)
except IOError:
exc_type, exc_value, exc_traceback = sys.exc_info()
print traceback.print_exception(exc_type, exc_value, exc_traceback)
return "IOerror:", IOError
else:
return "ERROR: must be already a file"
def get_register():
return template('register')