本文整理汇总了Python中flask.url_for方法的典型用法代码示例。如果您正苦于以下问题:Python flask.url_for方法的具体用法?Python flask.url_for怎么用?Python flask.url_for使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类flask
的用法示例。
在下文中一共展示了flask.url_for方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: save_session
# 需要导入模块: import flask [as 别名]
# 或者: from flask import url_for [as 别名]
def save_session(self, app, session, response):
"""Save session to Redis."""
domain = self.get_cookie_domain(app)
path = url_for('main', _external=False)
if not session:
self.redis.delete(self.prefix + session.sid)
if session.modified:
response.delete_cookie(app.session_cookie_name,
domain=domain, path=path)
else:
redis_exp = self.get_redis_expiration_time(app, session)
cookie_exp = self.get_expiration_time(app, session)
if session.modified:
val = self.serializer.dumps(dict(session))
self.redis.setex(self.prefix + session.sid,
int(redis_exp.total_seconds()), val)
else:
self.redis.expire(self.prefix + session.sid,
int(redis_exp.total_seconds()))
response.set_cookie(app.session_cookie_name, session.sid,
expires=cookie_exp, httponly=True,
domain=domain, path=path, secure=True)
示例2: portfolio_main
# 需要导入模块: import flask [as 别名]
# 或者: from flask import url_for [as 别名]
def portfolio_main():
transactions = Trades.query.filter_by(user_id=current_user.username)
if transactions.count() == 0:
return redirect(url_for("main.get_started"))
# For now pass only static positions, will update prices and other
# data through javascript after loaded. This improves load time
# and refresh speed.
# Get positions and prepare df for delivery
df = positions()
df.set_index('trade_asset_ticker', inplace=True)
df = df[df['is_currency'] == 0].sort_index(ascending=True)
df = df.to_dict(orient='index')
if df is None:
return redirect(url_for("main.get_started"))
return render_template("portfolio.html",
title="Portfolio Dashboard",
portfolio_data=df)
示例3: get_random_edit
# 需要导入模块: import flask [as 别名]
# 或者: from flask import url_for [as 别名]
def get_random_edit():
# Check first that we are logged in
access_token =flask.session.get('access_token', None)
if not access_token:
return flask.redirect(flask.url_for('login', next_url=flask.url_for('get_random_edit')))
# Then, redirect to a random cached edit
for page_name in list_cache_contents():
# Randomly skip or pick the current one, about 1 % chance.
if random() > 0.01:
continue
cache_fname = "cache/"+to_cache_name(page_name)
with open(cache_fname, 'r') as f:
page_json = json.load(f)
proposed_edits = page_json.get('proposed_edits', [])
proposed_edits = [template_edit for template_edit in proposed_edits if (template_edit['classification'] != 'rejected')]
if proposed_edits:
edit_idx = randint(0, len(proposed_edits)-1)
orig_hash = proposed_edits[edit_idx]['orig_hash']
return flask.redirect(
flask.url_for('review_one_edit', name=page_name, edit=orig_hash))
return flask.redirect(flask.url_for('index'))
示例4: login
# 需要导入模块: import flask [as 别名]
# 或者: from flask import url_for [as 别名]
def login():
"""Initiate an OAuth login.
Call the MediaWiki server to get request secrets and then redirect
the
user to the MediaWiki server to sign the request.
"""
consumer_token = mwoauth.ConsumerToken(
app.config['CONSUMER_KEY'], app.config['CONSUMER_SECRET'])
try:
redirect, request_token = mwoauth.initiate(
app.config['OAUTH_MWURI'], consumer_token)
except Exception:
app.logger.exception('mwoauth.initiate failed')
return flask.redirect(flask.url_for('index'))
else:
flask.session['request_token'] = dict(zip(
request_token._fields, request_token))
return flask.redirect(redirect)
示例5: stream_url
# 需要导入模块: import flask [as 别名]
# 或者: from flask import url_for [as 别名]
def stream_url():
url = flask.request.args.get('url')
r = requests.get(url)
# If it's just an HTML page served over HTTPS, no problem
if url.startswith('https://') and ( 'text/html' in r.headers['Content-Type'] ):
return flask.redirect(flask.url_for('redirect_to_url', url=url))
response = flask.make_response()
response.data = r.content
response.headers['Content-Type'] = r.headers['Content-Type']
# Preserve filename if possible
if 'Content-Disposition' in r.headers:
response.headers['Content-Disposition'] = r.headers['Content-Disposition'].replace("attachment;", "inline;")
# Work around incorrect application/octet-stream
if 'zenodo.org' in url:
response.headers['Content-Type'] = 'application/pdf'
return response
示例6: login
# 需要导入模块: import flask [as 别名]
# 或者: from flask import url_for [as 别名]
def login():
if current_user.is_authenticated:
return redirect(url_for("main.home"))
form = LoginForm()
if form.validate_on_submit():
user = User.query.filter_by(email=form.email.data).first()
if user and check_password_hash(user.password, form.password.data):
login_user(user, remember=form.remember.data)
# The get method below is actually very helpful
# it returns None if empty. Better than using [] for a dictionary.
next_page = request.args.get("next") # get the original page
if next_page:
return redirect(next_page)
else:
return redirect(url_for("main.home"))
else:
flash("Login failed. Please check e-mail and password", "danger")
return render_template("login.html", title="Login", form=form)
示例7: reset_request
# 需要导入模块: import flask [as 别名]
# 或者: from flask import url_for [as 别名]
def reset_request():
if current_user.is_authenticated:
return redirect(url_for("main.home"))
form = RequestResetForm()
if form.validate_on_submit():
user = User.query.filter_by(email=form.email.data).first()
send_reset_email(user)
flash(
"An email has been sent with instructions to reset your" +
" password.",
"info",
)
return redirect(url_for("users.login"))
return render_template("reset_request.html",
title="Reset Password",
form=form)
示例8: reset_token
# 需要导入模块: import flask [as 别名]
# 或者: from flask import url_for [as 别名]
def reset_token(token):
if current_user.is_authenticated:
return redirect(url_for("main.home"))
user = User.verify_reset_token(token)
if user is None:
flash("That is an invalid or expired token", "warning")
return redirect(url_for("users.reset_request"))
form = ResetPasswordForm()
if form.validate_on_submit():
hash = generate_password_hash(form.password.data)
user.password = hash
db.session.commit()
flash("Your password has been updated! You are now able to log in",
"success")
return redirect(url_for("users.login"))
return render_template("reset_token.html",
title="Reset Password",
form=form)
示例9: delete_baccount
# 需要导入模块: import flask [as 别名]
# 或者: from flask import url_for [as 别名]
def delete_baccount(id):
# type = account or address
account = None
type = request.args.get("type")
if type == "account":
account = AccountInfo.query.filter_by(
user_id=current_user.username).filter_by(account_id=id)
if type == "address":
account = BitcoinAddresses.query.filter_by(
user_id=current_user.username).filter_by(address_id=id)
if (account is None) or (account.count() == 0):
flash(f"{type.capitalize()} id: {id} not found. Nothing done.",
"warning")
return redirect(url_for("node.bitcoin_monitor"))
if account.first().user_id != current_user.username:
abort(403)
account.delete()
db.session.commit()
flash(f"{type.capitalize()} deleted", "danger")
return redirect(url_for("node.bitcoin_monitor"))
示例10: get_user_posts
# 需要导入模块: import flask [as 别名]
# 或者: from flask import url_for [as 别名]
def get_user_posts(id):
user = User.query.get_or_404(id)
page = request.args.get('page', 1, type=int)
pagination = user.posts.order_by(Post.timestamp.desc()).paginate(
page, per_page=current_app.config['CIRCULATE_POSTS_PER_PAGE'],
error_out=False)
posts = pagination.items
prev = None
if pagination.has_prev:
prev = url_for('api.get_user_posts', page=page-1, _external=True)
next = None
if pagination.has_next:
next = url_for('api.get_user_posts', page=page+1, _external=True)
return jsonify({
'posts': [post.to_json() for post in posts],
'prev': prev,
'next': next,
'count': pagination.total
})
示例11: get_user_followed_posts
# 需要导入模块: import flask [as 别名]
# 或者: from flask import url_for [as 别名]
def get_user_followed_posts(id):
user = User.query.get_or_404(id)
page = request.args.get('page', 1, type=int)
pagination = user.followed_posts.order_by(Post.timestamp.desc()).paginate(
page, per_page=current_app.config['CIRCULATE_POSTS_PER_PAGE'],
error_out=False)
posts = pagination.items
prev = None
if pagination.has_prev:
prev = url_for('api.get_user_followed_posts', page=page-1,
_external=True)
next = None
if pagination.has_next:
next = url_for('api.get_user_followed_posts', page=page+1,
_external=True)
return jsonify({
'posts': [post.to_json() for post in posts],
'prev': prev,
'next': next,
'count': pagination.total
})
示例12: get_comments
# 需要导入模块: import flask [as 别名]
# 或者: from flask import url_for [as 别名]
def get_comments():
page = request.args.get('page', 1, type=int)
pagination = Comment.query.order_by(Comment.timestamp.desc()).paginate(
page, per_page=current_app.config['CIRCULATE_COMMENTS_PER_PAGE'],
error_out=False)
comments = pagination.items
prev = None
if pagination.has_prev:
prev = url_for('api.get_comments', page=page-1, _external=True)
next = None
if pagination.has_next:
next = url_for('api.get_comments', page=page+1, _external=True)
return jsonify({
'comments': [comment.to_json() for comment in comments],
'prev': prev,
'next': next,
'count': pagination.total
})
示例13: get_post_comments
# 需要导入模块: import flask [as 别名]
# 或者: from flask import url_for [as 别名]
def get_post_comments(id):
post = Post.query.get_or_404(id)
page = request.args.get('page', 1, type=int)
pagination = post.comments.order_by(Comment.timestamp.asc()).paginate(
page, per_page=current_app.config['CIRCULATE_COMMENTS_PER_PAGE'],
error_out=False)
comments = pagination.items
prev = None
if pagination.has_prev:
prev = url_for('api.get_post_comments', page=page-1, _external=True)
next = None
if pagination.has_next:
next = url_for('api.get_post_comments', page=page+1, _external=True)
return jsonify({
'comments': [comment.to_json() for comment in comments],
'prev': prev,
'next': next,
'count': pagination.total
})
示例14: password_reset_request
# 需要导入模块: import flask [as 别名]
# 或者: from flask import url_for [as 别名]
def password_reset_request():
if not current_user.is_anonymous:
return redirect(url_for('main.index'))
form = PasswordResetRequestForm()
if form.validate_on_submit():
user = User.query.filter_by(email=form.email.data).first()
if user:
token = user.generate_reset_token()
send_email(user.email, 'Reset Your Password',
'auth/email/reset_password',
user=user, token=token,
next=request.args.get('next'))
flash('An email with instructions to reset your password has been '
'sent to you.')
return redirect(url_for('auth.login'))
return render_template('auth/reset_password.html', form=form)
示例15: test_users
# 需要导入模块: import flask [as 别名]
# 或者: from flask import url_for [as 别名]
def test_users(self):
# add two users
r = Role.query.filter_by(name='User').first()
self.assertIsNotNone(r)
u1 = User(email='john@example.com', username='john',
password='cat', confirmed=True, role=r)
u2 = User(email='susan@example.com', username='susan',
password='dog', confirmed=True, role=r)
db.session.add_all([u1, u2])
db.session.commit()
# get users
response = self.client.get(
url_for('api.get_user', id=u1.id),
headers=self.get_api_headers('susan@example.com', 'dog'))
self.assertTrue(response.status_code == 200)
json_response = json.loads(response.data.decode('utf-8'))
self.assertTrue(json_response['username'] == 'john')
response = self.client.get(
url_for('api.get_user', id=u2.id),
headers=self.get_api_headers('susan@example.com', 'dog'))
self.assertTrue(response.status_code == 200)
json_response = json.loads(response.data.decode('utf-8'))
self.assertTrue(json_response['username'] == 'susan')