Flask 路由相关操作
URL Route
- URL 后接
/
作为目录级访问 - URL 后不接
/
作为文件级访问
from flask import Flask app = Flask(__name__) @app.route('/') def index(): return 'Index Page' @app.route('/about') def about(): return 'The about page'
说明 | |
---|---|
string | (default) accepts any text without a slash |
int | accepts positive integers |
float | accepts positive floating point values |
path | like string but also accepts slashes |
uuid | accepts UUID strings |
from flask import Flask app = Flask(__name__) @app.route('/user/<username>') def show_user_profile(username): # show the user profile for that user return 'User %s' % username @app.route('/post/<int:post_id>') def show_post(post_id): # show the post with the given id, the id is an integer return 'Post %d' % post_id @app.route('/path/<path:subpath>') def show_subpath(subpath): # show the subpath after /path/ return 'Subpath %s' % subpath
- 可以使用
methods
来指定该路由使用的HTTP方法。
from flask import request @app.route('/login', methods=['GET', 'POST']) def login(): if request.method == 'POST': return do_the_login() else: return show_the_login_form()
参考
- route
URL Binding
使用url_for()
方法可以调用参数中的route
方法,以便满足某种调用目的,如单元测试。
from flask import Flask from flask import Flask, url_for app = Flask(__name__) with app.test_request_context(): print(url_for('index')) print(url_for('login')) print(url_for('login', next='/')) print(url_for('profile', username='John Doe'))
静态文件伺候
静态文件指应用使用的Javascript
、CSS
代码及图片资源文件。
- 在项目根目录下创建
static
目录
url_for('static', filename='style.css')
模板文件伺候
Flask会自动寻找templates
目录,所以原则上请不要自定义这个目录的名字,且应该将其放在项目(或模块)的根路径下。
from flask import Flask from flask import render_template app = Flask(__name__) @app.route('/hello/') @app.route('/hello/<name>') def hello(name=None): return render_template('hello.html', name=name)
<body> Hello, World! from templates </body>
参考
- render_templates
- Request
- Session
- g
请求处理
Request
@app.route('/test', methods=['POST', 'GET']) def test(): error = None if request.method == 'POST': t1 = request.form['1'] t2 = request.form['2'] elif request.method == 'GET': # for URL `?key=value` t3 = request.args.get('key', '') else: error = 'Method is not POST or GET!' return render_template('test.html', error=error)
参考
- Request
- form
- KeyError
文件上传
- 保存时重新指定文件名
from flask import request @app.route('/upload', methods=['GET', 'POST']) def upload_file(): if request.method == 'POST': f = request.files['the_file'] f.save('/var/www/uploads/uploaded_file.txt') ...
- 保存时,使用上传的文件名
from flask import request from werkzeug.utils import secure_filename @app.route('/upload', methods=['GET', 'POST']) def upload_file(): if request.method == 'POST': f = request.files['the_file'] f.save('/var/www/uploads/' + secure_filename(f.filename)) ...
参考
- Uploading Files
Cookies
- 读取
cookie
from flask import request @app.route('/') def index(): username = request.cookies.get('username') # use cookies.get(key) instead of cookies[key] to not get a # KeyError if the cookie is missing.
- 写入
cookie
from flask import make_response @app.route('/') def index(): resp = make_response(render_template(...)) resp.set_cookie('username', 'the username') return resp
- cookies
- set_cookie
- session
重定向
- 使用
url_for
来找到URL地址 - 使用
redirect
来重定向
from flask import abort, redirect, url_for @app.route('/') def index(): return redirect(url_for('login'))
- 使用
abort
来返回错误码
@app.route('/login') def login(): abort() this_is_never_executed()
- 使用
@app.errorhandler()
来处理错误码对应的请求
from flask import render_template @app.errorhandler() def page_not_found(error): return render_template('page_not_found.html'),
参考
- redirect
- abort
相关推荐
bestallen 2020-08-17
JessePinkmen 2020-07-26
washing 2020-07-18
hzyuhz 2020-07-04
hzyuhz 2020-06-28
hzyuhz 2020-06-25
苦咖啡flask 2020-06-25
苦咖啡flask 2020-06-25
苦咖啡flask 2020-06-18
washing 2020-06-16
liuweiq 2020-06-14
wushaojun 2020-06-14
JessePinkmen 2020-06-14
kgshuo 2020-06-14
JessePinkmen 2020-06-14
bestallen 2020-06-13