Python flask 模块,render_template() 实例源码
我们从Python开源项目中,提取了以下49个代码示例,用于说明如何使用flask.render_template()。
def query():
if(request.method == 'POST'):
organisation = request.form['organisation']
email_address = request.form['email_address']
filename = organisation + ".html"
info = db.session.query(User.github_username, User.name).filter_by(organisation = organisation).all()
if(info == []):
job = q.enqueue_call(
func="main.save_info", args=(organisation, email_address, ), result_ttl=5000, timeout=600
)
flash("We shall notify you at " + email_address + " when the processing is complete")
else:
lists = []
for i in info:
lists.append([str(i.github_username), str(i.name)])
get_nodes.creating_objs(lists, organisation)
return render_template(filename, organisation=str(organisation)+'.json')
return render_template('query.html')
def dashboard():
topic_dict = dict()
if '/convey/stages' in topic_cache:
topic_dict['/convey/stages'] = topic_cache['/convey/stages']
else:
topic_dict['/convey/stages'] = "Empty Cache"
if '/sortarm/stages' in topic_cache:
topic_dict['/sortarm/stages'] = topic_cache['/sortarm/stages']
else:
topic_dict['/sortarm/stages'] = "Empty Cache"
if '/invarm/stages' in topic_cache:
topic_dict['/invarm/stages'] = topic_cache['/invarm/stages']
else:
topic_dict['/invarm/stages'] = "Empty Cache"
return render_template('topic.html', topic_dict=topic_dict)
def twittercallback():
verification = request.args["oauth_verifier"]
auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
try:
auth.request_token = session["request_token"]
except KeyError:
flash("Please login again", "danger")
return redirect(url_for("bp.home"))
try:
auth.get_access_token(verification)
except tweepy.TweepError:
flash("Failed to get access token", "danger")
return redirect(url_for("bp.home"))
session["access_token"] = auth.access_token
session["access_token_secret"] = auth.access_token_secret
return render_template("twittercallback.html", form=HashtagForm())
def webpage():
url = request.args.get('url')
if not url:
# redirect with url query param so that user can navigate back later
next_rec = service.get_next_unlabelled()
if next_rec:
return redirect("/?url=%s" % (urllib.quote(next_rec['url'])))
else:
featured_content = "No Unlabelled Record Found."
else:
featured_content = get_next(url)
data = {
'featured_content': featured_content,
'status': service.overall_status()
}
return render_template('index.html', **data)
def add():
if request.method == 'POST':
if request.form['submit'] == 'Add':
addr = request.form['addr'].lstrip().rstrip()
f = io.open('blastlist.txt', 'a', encoding="utf-8")
f.write(addr.decode('utf-8') + u'\r\n')
f.close()
return render_template('listadded.html',addr=addr)
elif request.form['submit'] == 'Remove':
addr = request.form['addr'].lstrip().rstrip()
f = io.open('blastlist.txt', 'r', encoding="utf-8")
lines = f.readlines()
f.close()
f = io.open('blastlist.txt', 'w', encoding="utf-8")
for line in lines:
if addr not in line:
f.write(line.decode('utf-8'))
f.close()
return render_template('listremoved.html',addr=addr)
def get_profile(user_id):
session = db.session
user, results = get_profile_data(session, user_id)
user_games = session.query(Game).filter(
sqla.or_(
Game.winner_id == user_id,
Game.loser_id == user_id,
),
Game.deleted_at.is_(None)
).order_by(Game.created_at).all()
return flask.render_template('user.html',
title=user.name,
user=user,
results=results,
auth_url=get_google_authorization_url(),
user_games=[game_dict(session, game) for game in user_games],
active_users=get_active_users(session) # used in base for 'Add Game'
)
def index():
form = NameForm()
if form.validate_on_submit():
user = User.query.filter_by(username=form.name.data).first()
if user is None:
user = User(username=form.name.data)
db.session.add(user)
session['kNown'] = False
if app.config['FLASKY_ADMIN']:
send_email(app.config['FLASKY_ADMIN'], 'New User',
'mail/new_user', user=user)
else:
session['kNown'] = True
session['name'] = form.name.data
from.name.data = ''
return redirect(url_for('index'))
return render_template('index.html', form=form, name=session.get('name'),
kNown=session.get('kNown', False))
def internal_server_error(error):
logger.error(error)
logger.error(traceback.format_exc())
if "username" in session:
if "500" in session and "500_title" in session:
reason = session['500']
title = session['500_title']
session.pop('500', None)
session.pop('500_title', None)
else:
reason = '''The server encountered something unexpected that didn't allow it to complete the request. We apologize.You can go back to
<a href="/dashboard/">dashboard</a> or <a href="/logout">log out</a>'''
title = 'Internal Server Error'
return render_template('error/500.html', mysession = session, reason = reason, title = title)
else:
return redirect('/login/')
def search():
q = request.args.get('q')
if not q:
q=''
f = request.args.get('f')
try:
p = int(request.args.get('p'))
except:
p = 0
try:
fmt=request.args.get('f')
print(fmt)
except:
fmt=""
count,context = nweb.search(q,100,100*int(str(p)))
# what kind of output are we looking for?
if fmt == 'hostlist':
print("printing hostlist because "+fmt)
return render_template("hostlist.html",query=q, numresults=count, page=p, hosts=context)
# default output (a pretty webpage)
return render_template("search2.html", hosts=context)
def index():
icao_identifier = request.args.get('airport')
try:
date = dateparser.parse(request.args.get('date', datetime.date.today().isoformat())).date()
except ValueError:
date = datetime.date.today()
if icao_identifier:
try:
result = do_lookup(icao_identifier, date)
except Exception as e:
result = {'airport': icao_identifier,
'date': date.isoformat(),
'error': str(e)}
return render_template('index.html', dev_mode=dev_mode, result=result), 400
else:
result = None
return render_template('index.html', result=result)
def login():
""" This login function checks if the username & password
match the admin.db; if the authentication is successful,
it passes the id of the user into login_user() """
if request.method == "POST" and \
"username" in request.form and \
"password" in request.form:
username = request.form["username"]
password = request.form["password"]
user = User.get(username)
# If we found a user based on username then compare that the submitted
# password matches the password in the database. The password is stored
# is a slated hash format,so you must hash the password before comparing it.
if user and hash_pass(password) == user.password:
login_user(user, remember=True)
# FIXME! Get this to work properly...
# return redirect(request.args.get("next") or url_for("index"))
return redirect(url_for("index"))
else:
flash(u"Invalid username,please try again.")
return render_template("login.html")
def min_omw_concepts(ss=None, ili_id=None):
if ili_id:
ss_ids = f_ss_id_by_ili_id(ili_id)
else:
ss_ids = [ss]
pos = fetch_pos()
langs_id, langs_code = fetch_langs()
ss, senses, defs, exes, links = fetch_ss_basic(ss_ids)
ssrels = fetch_ssrel()
return jsonify(result=render_template('min_omw_concept.html',
pos = pos,
langs = langs_id,
senses=senses,
ss=ss,
links=links,
ssrels=ssrels,
defs=defs,
exes=exes))
def omw_welcome(name=None):
lang_id, lang_code = fetch_langs()
src_Meta=fetch_src_Meta()
### sort by language,project version (Newest first)
src_sort=od()
keys=list(src_Meta.keys())
keys.sort(key=lambda x: src_Meta[x]['version'],reverse=True)
keys.sort(key=lambda x: src_Meta[x]['id'])
keys.sort(key=lambda x: lang_id[lang_code['code'][src_Meta[x]['language']]][1])
for k in keys:
src_sort[k] = src_Meta[k]
return render_template('omw_welcome.html',
src_Meta=src_sort,
lang_id=lang_id,
lang_code=lang_code,
licenses=licenses)
def search_ili(q=None):
if q:
query = q
else:
query = request.form['query']
src_id = fetch_src()
kind_id = fetch_kind()
status_id = fetch_status()
ili = dict()
for c in query_omw("""SELECT * FROM ili WHERE def GLOB ?
""", [query]):
ili[c['id']] = (kind_id[c['kind_id']], c['def'],
src_id[c['origin_src_id']], c['src_key'],
status_id[c['status_id']], c['superseded_by_id'],
c['t'])
rsumm, up_who, down_who = f_rate_summary(list(ili.keys()))
return render_template('concept-list.html', ili=ili,
rsumm=rsumm, up_who=up_who, down_who=down_who)
def omw_sense(sID=None):
langs_id, langs_code = fetch_langs()
pos = fetch_pos()
sense = fetch_sense(sID)
forms=fetch_forms(sense[3])
selected_lang = request.cookies.get('selected_lang')
labels= fetch_labels(selected_lang,[sense[4]])
src_Meta= fetch_src_Meta()
src_sid=fetch_src_for_s_id([sID])
return render_template('omw_sense.html',
s_id = sID,
sense = sense,
forms=forms,
labels = labels,
src_sid = src_sid,
src_Meta = src_Meta)
# URIs FOR ORIGINAL CONCEPT KEYS,BY INDIVIDUAL SOURCES
def omw_wn(src=None):
if src:
try:
proj = src[:src.index('-')]
ver = src[src.index('-')+1:]
src_id = f_src_id_by_proj_ver(proj, ver)
except:
src_id = None
srcs_Meta = fetch_src_Meta()
src_info = srcs_Meta[src_id]
return render_template('omw_wn.html',
wn = src,
src_id=src_id,
src_info=src_info,
ssrel_stats=fetch_ssrel_stats(src_id),
pos_stats= fetch_src_id_pos_stats(src_id),
src_stats=fetch_src_id_stats(src_id),
licenses=licenses)
def omw_wn_latex(src=None):
if src:
try:
proj = src[:src.index('-')]
ver = src[src.index('-')+1:]
src_id = f_src_id_by_proj_ver(proj, ver)
except:
src_id = None
srcs_Meta = fetch_src_Meta()
src_info = srcs_Meta[src_id]
return render_template('omw_wn_latex.html',
src_stats=fetch_src_id_stats(src_id))
def home():
"""
Homepage. nothing here yet.
Could do some stats if we wanted.
"""
all_items = get_all_items()
items = []
for item in all_items:
items.append({
'info_hash': item['info_hash'],
'peers': len(item['peers']),
'completed': item['completed']
})
return render_template('index.html', items=items)
def main_teacher():
tm = teachers_model.Teachers(flask.session['id'])
if request.method == 'POST':
cm = courses_model.Courses()
if "close" in request.form.keys():
cid = request.form["close"]
cm.cid = cid
cm.close_session(cm.get_active_session())
elif "open" in request.form.keys():
cid = request.form["open"]
cm.cid = cid
cm.open_session()
courses = tm.get_courses_with_session()
empty = True if len(courses) == 0 else False
context = dict(data=courses)
return render_template('main_teacher.html', empty=empty, **context)
def login():
db = UserDb(app.config['LOCAL_DB'])
form = request.form
user = form.get('user')
pwd = form.get('pwd')
password = db.login(user)
del db
if pwd == password:
# ??????
session.permanent = True
# session????
app.permanent_session_lifetime = timedelta(minutes=30)
session.update(dict(user=user))
return render_template('index.html')
elif password is None:
return render_template('login.html', info="??????!")
else:
return render_template('login.html', info="?????!")
def upuser(userid):
if current_user.id == userid or current_user.role == '0':
form = UserEditForm()
if form.validate_on_submit():
user = users.query.filter_by(id=userid).first()
if user is not None and user.verify_password(form.oldpassword.data):
user.password = form.password.data
db.session.add(user)
db.session.commit()
flash(u'??????!')
return render_template('useredit.html',form=form)
user = users.query.filter_by(id=userid).first()
form.username.data = user.username
form.name.data = user.name
return render_template('useredit.html',form=form)
else:
abort(403)
def customer():
if request.method == 'POST':
try:
customer_id = request.form['customer_id']
customer_oper = request.form['customer_oper']
customer = customers.query.filter_by(id=customer_id).first()
if customer_oper == 'stop_back':
customer.customers_status = 1
else:
customer.customers_status = 0
db.session.add(customer)
db.session.commit()
return u"???????"
except Exception, e:
print e
return u"???????"
else:
customer_all = customers.query.all()
return render_template('customers.html',customers=customer_all)
def create_app():
app = Flask(__name__)
app.config.from_object(config_dict[FLASK_CONfigURATION])
app.secret_key = secret_key
Bootstrap(app)
assets = Environment(app)
js_files = Bundle('justgage.js', 'raphael-2.1.4.min.js', filters='rjsmin', output='gen/minified.js')
assets.register('js_files', js_files)
nav.init_app(app)
from .blueprints import bp
app.register_blueprint(bp)
global celery
celery = make_celery(app)
@app.errorhandler(404)
def fournotfour(_):
return render_template("404page.html"), 404
@app.errorhandler(500)
def fivezerozero(_):
return render_template("500page.html"), 500
return app
def changepass():
if request.method == 'POST':
# process password change
if request.form['pass1'] == request.form['pass2']:
change_password(session['username'], request.form['pass1'])
log_action(session['uid'], 8)
session.pop('logged_in', None)
session.pop('uid', None)
session.pop('priv', None)
session.pop('username', None)
flash('Your password has been changed. Please login using your new password.')
return redirect(url_for('home'))
else:
flash('The passwords you entered do not match. Please try again.')
return render_template('changepass.html')
return render_template('changepass.html')
#
# EDIT USER PAGE
#
def adduser():
if request.method == 'POST':
if request.form['pass1'] == request.form['pass2']:
if user_exists(request.form['username']) == False:
# create the user
admin = 0
if request.form['status'] == 'admin':
admin = 1
create_user(request.form['username'], request.form['pass1'], admin)
log_action(session['uid'], 10)
flash(request.form['username'] + ' has been created.')
return render_template('adduser.html', acp=session['priv'], username=session['username'])
else:
flash('The username you entered is already in use.')
return render_template('adduser.html', username=session['username'])
else:
flash('The passwords you entered do not match. Please try again.')
return render_template('adduser.html', username=session['username'])
return render_template('adduser.html', username=session['username'])
def index():
if request.args.get('code'):
unlock_code = request.args.get('code')
# unlock,new password
re = s.query(RecoveryEmail).filter(RecoveryEmail.password_code==unlock_code).one_or_none()
if re:
jid = re.jid
re.password_code = None
s.merge(re)
s.commit()
# set new password and send email
email_address = re.email
password = ''.join(random.SystemRandom().choice(string.ascii_lowercase + string.ascii_uppercase + string.digits) for _ in range(10))
p = subprocess.Popen(['/usr/bin/prosodyctl', 'passwd', jid], stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.STDOUT)
args = bytes("%s\n%s\n" % (password, password), encoding='utf8')
p.communicate(args)
sendMail(email_address, 'new password', password)
content = render_template('success.html', message='password was sent')
else:
content = render_template('error.html', message='link invalid')
else:
content = render_template('index.html')
return content
def index(pattern=None):
"""Renders index.html page with a list of benchmarks."""
filter_regex = None
if pattern:
filter_regex = re.compile(urllib.parse.unquote(pattern))
min_time_to_lookup = datetime.Now() - timedelta(days=_MAX_DAYS_WITHOUT_RUN)
client = datastore.Client()
query = client.query(kind='Test')
query.add_filter('start', '>', min_time_to_lookup)
fetched = list(query.fetch())
test_names = {} # maps test name to encoded test name
for fetched_result in fetched:
if fetched_result['test'] in test_names:
continue # already added
if not filter_regex or re.search(pattern, fetched_result['test']):
test_names[fetched_result['test']] = urllib.parse.quote(
fetched_result['test'], safe='')
# convert test_names to list and sort
test_names = sorted(test_names.items(), key=itemgetter(1), reverse=True)
return render_template('index.html', tests=test_names)
def index():
"""Primary index function.
This function handles searching and the main page. If ``q`` is passed in a query
string,e.g. ``http://localhost?q=gabriel+dropout``,then a search will be performed.
If request path is ``search``,e.g. ``http://localhost/search``,then the navigation
menu will not be rendered.
Should there be no shows returned from the backend,``front_end.do_first_time_setup``
will be called to scrape shows from the source.
Returns:
A rendered template,either ``first_time.html`` for the first run or ``default.html`` otherwise.
"""
log.debug("Entering index,attempting to get shows.")
watching, airing, specials, movies = fe.get_shows_for_display(request.args.get('q',None))
standalone = True if request.path.strip('/') == 'search' else False
logged_in = fe.check_login_id(escape(session['logged_in'])) if 'logged_in' in session else False
if not watching and not airing and not specials and not movies:
log.debug("No shows found in any category. Starting first time startup.")
fe.do_first_time_setup()
return render_template('first_time.html', logged_in=logged_in)
return render_template('default.html', watching=watching, airing=airing, specials=specials, movies=movies, standalone=standalone, logged_in=logged_in)
def index():
site_info = site_get()
article_id = request.args.get('article_id',0)
article_dict = []
temp_dict = {}
packet_dict = {}
packet_list = Packet.query.filter_by().all()
if packet_list is not None:
for temp in packet_list:
temp_dict = temp.__dict__
del temp_dict["_sa_instance_state"]
packet_dict[str(temp_dict['id'])] = temp_dict['packet_name']
tempdict = {}
article_list = Article.query.filter_by(show = 1).all()
if article_list is not None:
for temp in article_list:
tempdict = temp.__dict__
article_dict.append([tempdict["id"],tempdict["title"],tempdict["timestamp"].strftime('%Y-%m-%d'),tempdict["body"][:150]])
return render_template('index.html', **locals())
def article():
site_info = site_get()
article_id = request.args.get('article_id',0)
if article_id != 0:
article = Article.query.filter_by(id = article_id).first()
if article is not None:
article = article.__dict__
article_id = article['id']
title = article['title']
packet_id = article['packet_id']
show = article['show']
timestamp = article['timestamp']
body = article['body'][:-1]
else:
return redirect(url_for('main.index'))
return render_template('article.html', **locals())
def edit():
site_info = site_get()
article_id = request.args.get('article_id',0)
temp_dict = {}
packet_dict = {}
packet_list = Packet.query.filter_by().all()
if packet_list is not None:
for temp in packet_list:
temp_dict = temp.__dict__
del temp_dict["_sa_instance_state"]
packet_dict[str(temp_dict['id'])] = temp_dict['packet_name']
#packet_dict = dict( packet_dict.items() + tempdict.items() )
if article_id != 0:
article = Article.query.filter_by(id = article_id).first()
#print article
if article is not None:
article = article.__dict__
title = article['title']
packet_id = article['packet_id']
show = article['show']
body = article['body']
return render_template('admin/edit.html', **locals())
def outputjson():
site_info = site_get()
tempdict = {}
tempjson = "["
info_list = Article.query.filter_by().all()
for item in info_list:
tempdict = item.__dict__
del tempdict["_sa_instance_state"]
value = json.dumps(tempdict,cls=CJsonEncoder)
tempjson += value + ",\n"
tempjson = tempjson[:-2] + "]"
filename = 'page_list_'+str(time.strftime("%Y%m%d"))+'.txt'
output = open(filename,'w')
output.write(tempjson)
output.close()
flash(u'?????????????')
return render_template('admin/output.html', **locals())
def test_escaping(self):
text = '<p>Hello World!'
app = flask.Flask(__name__)
@app.route('/')
def index():
return flask.render_template('escaping_template.html', text=text,
html=flask.Markup(text))
lines = app.test_client().get('/').data.splitlines()
self.assert_equal(lines, [
b'<p>Hello World!',
b'<p>Hello World!',
b'<p>Hello World!',
b'<p>Hello World!'
])
def test_template_rendered(self):
app = flask.Flask(__name__)
@app.route('/')
def index():
return flask.render_template('simple_template.html', whiskey=42)
recorded = []
def record(sender, template, context):
recorded.append((template, context))
flask.template_rendered.connect(record, app)
try:
app.test_client().get('/')
self.assert_equal(len(recorded), 1)
template, context = recorded[0]
self.assert_equal(template.name, 'simple_template.html')
self.assert_equal(context['whiskey'], 42)
finally:
flask.template_rendered.disconnect(record, app)
def test_memory_consumption(self):
app = flask.Flask(__name__)
@app.route('/')
def index():
return flask.render_template('simple_template.html', whiskey=42)
def fire():
with app.test_client() as c:
rv = c.get('/')
self.assert_equal(rv.status_code, 200)
self.assert_equal(rv.data, b'<h1>42</h1>')
# Trigger caches
fire()
# This test only works on cpython 2.7.
if sys.version_info >= (2, 7) and \
not hasattr(sys, 'pypy_translation_info'):
with self.assert_no_leak():
for x in range(10):
fire()
def unsubscribe(email):
return render_template('unsubscribe.html',email=email)
def tail():
if request.method == 'POST':
fi = request.form['file']
if os.path.isfile(fi):
n = int(request.form['n'])
le = io.open(fi, encoding='utf-8')
taildata = le.read()[-n:]
le.close()
else:
taildata = "No such file."
return render_template('tail.html',taildata=taildata)
def wladd():
if request.method == 'POST':
addr = request.form['addr'].lstrip().rstrip()
f = io.open('static/whitelist.txt', encoding="utf-8")
f.write(addr.decode('utf-8') + u'\r\n')
f.close()
return render_template('wladd.html')
def unsub():
if request.method == 'POST':
addr = request.form['addr'].lstrip().rstrip()
f = io.open('unsubscribers.txt', encoding="utf-8")
f.write(addr.decode('utf-8') + u'\r\n')
f.close()
f = io.open('static/whitelist.txt', encoding="utf-8")
lines = f.readlines()
f.close()
f = io.open('static/whitelist.txt', encoding="utf-8")
for line in lines:
if addr not in line:
f.write(line.decode('utf-8'))
f.close()
return render_template('unsubscribed.html',addr=addr)