1. routing basicconcepts
routing is URL to 视graphfunction maprelationships. in Flaskin, 我们using装饰器来定义routing. 当user访问某个URL时, Flask会根据routing规则调用 for 应 视graphfunction, 并将function return valueserving asresponse返回给客户端.
1.1 basicrouting定义
using@app.route()装饰器可以定义一个routing:
from flask import Flask
app = Flask(__name__)
@app.route('/')
def index():
return 'Hello, Flask!'
@app.route('/about')
def about():
return 'About Page'
if __name__ == '__main__':
app.run(debug=True)
in on 面 例子in, 我们定义了两个routing:
/map toindex()function/aboutmap toabout()function
2. URL规则
Flasksupport many 种URL规则, including静态routing, 动态routing and URL转换器etc..
2.1 静态routing
静态routing is 指URLpath固定不变 routing:
@app.route('/contact')
def contact():
return 'Contact Page'
2.2 动态routing
动态routing is 指URLpathinpackage含variable routing. using尖括号<>可以定义动态routing:
@app.route('/user/')
def user_profile(username):
return f'User Profile: {username}'
当user访问/user/john时, Flask会调用user_profile('john')function, 并返回"User Profile: john".
2.3 URL转换器
Flaskproviding了 many 种URL转换器, 用于指定variable class型:
| 转换器 | describes | example |
|---|---|---|
string |
stringclass型 (默认) , 不package含斜杠 | /user/<string:username> |
int |
整数class型 | /post/<int:post_id> |
float |
浮点数class型 | /product/<float:price> |
path |
stringclass型, package含斜杠 | /file/<path:file_path> |
uuid |
UUIDclass型 | /item/<uuid:item_id> |
2.3.1 usingURL转换器 example
@app.route('/post/')
def show_post(post_id):
return f'Post ID: {post_id}'
@app.route('/product/')
def product_by_price(price):
return f'Product Price: ${price}'
@app.route('/file/')
def get_file(file_path):
return f'File Path: {file_path}'
3. 视graphfunction
视graphfunction is processingrequest并返回response function. in Flaskin, 视graphfunction可以返回 many 种class型 response:
3.1 返回string
视graphfunction可以直接返回string, Flask会将其serving asresponse体返回:
@app.route('/')
def index():
return 'Hello, Flask!'
3.2 返回HTML
视graphfunction可以返回HTMLstring, Flask会将其serving asHTMLresponse返回:
@app.route('/html')
def html_response():
return '<h1>Hello, HTML!</h1><p>This is an HTML response.</p>'
3.3 返回JSON
usingjsonify()function可以返回JSONresponse:
from flask import jsonify
@app.route('/json')
def json_response():
data = {
'name': 'John',
'age': 30,
'city': 'New York'
}
return jsonify(data)
3.4 返回重定向
usingredirect()function可以返回重定向response:
from flask import redirect
@app.route('/old-url')
def old_url():
return redirect('/new-url', code=302)
@app.route('/new-url')
def new_url():
return 'This is the new URL'
3.5 返回errorresponse
usingabort()function可以返回errorresponse:
from flask import abort
@app.route('/error')
def error():
abort(404) # 返回404error
@app.route('/forbidden')
def forbidden():
abort(403) # 返回403error
3.6 自定义error页面
using@app.errorhandler()装饰器可以自定义error页面:
@app.errorhandler(404)
def page_not_found(error):
return '<h1>404 - Page Not Found</h1><p>The requested page does not exist.</p>', 404
@app.errorhandler(500)
def internal_server_error(error):
return '<h1>500 - Internal Server Error</h1><p>Something went wrong on the server.</p>', 500
4. requestmethod
默认circumstances under , Flaskrouting只processingGETrequest. usingmethodsparameter可以指定routingprocessing requestmethod:
4.1 processing many 种requestmethod
@app.route('/login', methods=['GET', 'POST'])
def login():
if request.method == 'POST':
# processingPOSTrequest, 例such asprocessing表单submitting
username = request.form['username']
password = request.form['password']
# verificationuser名 and password
return f'Login successful for {username}'
else:
# processingGETrequest, 例such as显示login表单
return '<h1>Login Page</h1><form method="post">Username: <input type="text" name="username"><br>Password: <input type="password" name="password"><br><input type="submit" value="Login"></form>'
4.2 专门 装饰器
Flask 0.6及以 on versionproviding了专门 装饰器来processing不同 requestmethod:
from flask import request
@app.get('/login')
def login_get():
# processingGETrequest
return '<h1>Login Page</h1><form method="post">Username: <input type="text" name="username"><br>Password: <input type="password" name="password"><br><input type="submit" value="Login"></form>'
@app.post('/login')
def login_post():
# processingPOSTrequest
username = request.form['username']
password = request.form['password']
return f'Login successful for {username}'
5. URL构建
usingurl_for()function可以根据视graphfunction名构建URL:
5.1 basic用法
from flask import url_for
@app.route('/')
def index():
# 构建URL for 'about' view function
about_url = url_for('about')
return f'<a href="{about_url}">About</a>'
@app.route('/about')
def about():
return 'About Page'
5.2 带 has parameter URL构建
for 于带 has parameter routing, 可以through关键字parameter传递parameter值:
@app.route('/user/')
def user_profile(username):
return f'User Profile: {username}'
@app.route('/url-build')
def url_build():
# 构建URL with parameter
user_url = url_for('user_profile', username='john')
return f'<a href="{user_url}">John\'s Profile</a>'
5.3 静态fileURL
usingurl_for('static', filename='filename')可以构建静态file URL:
@app.route('/static-url')
def static_url():
css_url = url_for('static', filename='style.css')
js_url = url_for('static', filename='script.js')
return f'CSS: <link rel="stylesheet" href="{css_url}"><br>JS: <script src="{js_url}"></script>'
6. 蓝graph (Blueprints)
蓝graph is Flaskin用于组织routing 一种方式, 适合 big 型application. using蓝graph可以将application分 for many 个module, 每个module has 自己 routing, 视graphfunction and 模板.
6.1 creation蓝graph
首先, creation一个蓝graphobject:
from flask import Blueprint
# creation蓝graph, 第一个parameter is 蓝graph 名称, 第二个parameter is 蓝graphwhere module
blog_bp = Blueprint('blog', __name__)
6.2 in 蓝graphin定义routing
using蓝graphobject route()method定义routing:
@blog_bp.route('/')
def blog_index():
return 'Blog Index'
@blog_bp.route('/post/')
def blog_post(post_id):
return f'Blog Post: {post_id}'
6.3 register蓝graph
in Flaskapplicationinregister蓝graph:
from flask import Flask
from blog import blog_bp # import蓝graph
app = Flask(__name__)
# register蓝graph, url_prefixparameter指定蓝graph URL before 缀
app.register_blueprint(blog_bp, url_prefix='/blog')
register after , 蓝graphin定义 routing会被添加 to applicationin, URL会自动添加/blog before 缀:
/blog/map toblog_index()function/blog/post/1map toblog_post(1)function
6.4 蓝graph 模板 and 静态file
蓝graph可以 has 自己 模板 and 静态fileTable of Contents:
# creation蓝graph时指定模板 and 静态fileTable of Contents
blog_bp = Blueprint('blog', __name__,
template_folder='templates',
static_folder='static')
in 蓝graph 视graphfunctioninusing模板:
from flask import render_template
@blog_bp.route('/')
def blog_index():
return render_template('blog/index.html')
7. routing advanced features
7.1 子域名routing
Flasksupport子域名routing, 可以throughsubdomainparameter指定子域名:
app.config['SERVER_NAME'] = 'example.com'
@app.route('/', subdomain='admin')
def admin_index():
return 'Admin Index'
当访问admin.example.com时, 会调用admin_index()function.
7.2 重定向routing
可以usingredirect_toparametercreation重定向routing:
@app.route('/old', redirect_to='/new')
def old_route():
# 这个function不会被调用, 因 for request会被重定向 to /new
pass
@app.route('/new')
def new_route():
return 'This is the new route'
7.3 routing别名
可以usingendpointparameter for routing指定别名:
@app.route('/home', endpoint='index')
def home():
return 'Home Page'
usingurl_for('index')会生成/home URL.
8. request on under 文
Flaskproviding了request on under 文, 用于访问request相关 information. 常用 request on under 文variableincluding:
8.1 request
requestobjectpackage含了request 所 has information:
from flask import request
@app.route('/request-info')
def request_info():
return f'''Request Method: {request.method}<br>
Request URL: {request.url}<br>
Request Headers: {request.headers}<br>
Request Args: {request.args}<br>
Request Form: {request.form}<br>
Request Files: {request.files}'''
8.2 session
sessionobject用于storeusersessiondata:
from flask import session
app.secret_key = 'your-secret-key'
@app.route('/set-session')
def set_session():
session['username'] = 'john'
return 'Session set'
@app.route('/get-session')
def get_session():
username = session.get('username', 'Guest')
return f'Username: {username}'
练习 1: creation动态routing
- creation一个Flaskapplication
- 定义一个动态routing
/greet/<name>, 返回"Hello, [name]!" - 定义一个动态routing
/add/<a>/<b>, 返回a + b 结果 - usingURL转换器确保a and b is 整数
- test这两个routing
练习 2: creation蓝graph
- creation一个名 for
auth蓝graph - in 蓝graphin定义以 under routing:
/login- GET and POSTmethod/register- GET and POSTmethod/logout- GETmethod
- in applicationinregister蓝graph, using
/authbefore 缀 - test这些routing
练习 3: 自定义error页面
- creation一个Flaskapplication
- 自定义404error页面, 返回友 good errorinformation
- 自定义500error页面, 返回友 good errorinformation
- test这些error页面