1.路由
使用route()裝飾器把一個(gè)函數(shù)綁定到URL上,可以動(dòng)態(tài)的構(gòu)造URL的特定部分,也可在一個(gè)函數(shù)上附加多個(gè)規(guī)則。
@app.route('/')
def index():
return 'Index Page'
@app.route('/hello')
def hello():
return 'Hello World'
2.變量規(guī)則
用<variable_name>給URL添加變量部分,這部分作為命名參數(shù)傳遞到函數(shù)。規(guī)則可用<converter:variable_name>指定轉(zhuǎn)換器
@app.route('/user/<username>')
def show_user_profile(username):
return 'User %s' %username
@app.route('/post/<int:post_id>')
def show_post(post_id):
return 'Post %d' %post_id
| 轉(zhuǎn)換器 | 接受參數(shù) |
|---|---|
| string | 接受任何沒有斜杠“/”文本(默認(rèn)) |
| int | 整型 |
| float | 同int一樣,但是還包括浮點(diǎn)數(shù) |
| path | 和string相似,但也接受斜杠“/” |
| uuid | 只接受UUID字符串 |
| any | 可以制定多種路徑,但是需要傳遞參數(shù) |
@app.route('/<any(a,b):page_name>/') 訪問/a/和/b/都符合這個(gè)規(guī)則,page_name對應(yīng)的就是a或b。
3.唯一URL和重定向行為
以下兩個(gè)為例:
@app.route('/projects/')
def projects():
return 'The project page'
@app.route('/about')
def about():
return 'The about page'
它們結(jié)尾斜線的使用在 URL 定義 中不同。 第一種情況中,指向 projects 的規(guī)范 URL 尾端有一個(gè)斜線。這種感覺很像在文件系統(tǒng)中的文件夾。訪問一個(gè)結(jié)尾不帶斜線的 URL 會(huì)被 Flask 重定向到帶斜線的規(guī)范 URL 去。
然而,第二種情況的 URL 結(jié)尾不帶斜線,類似 UNIX-like 系統(tǒng)下的文件的路徑名。訪問結(jié)尾帶斜線的 URL 會(huì)產(chǎn)生一個(gè) 404 “Not Found” 錯(cuò)誤。
4.構(gòu)造URL
url_for()可以給指定的函數(shù)構(gòu)造URL。
接受函數(shù)名作為第一個(gè)參數(shù),也接受對應(yīng)URL規(guī)則的變量部分的命名參數(shù)。未知變量會(huì)添加到URL末尾作為查詢參數(shù)。

環(huán)境局部變量
一段依賴請求對象的代碼,因沒有請求對象而無法運(yùn)行。
解決方案:自行創(chuàng)建一個(gè)請求對象,并綁定到環(huán)境中。單元測試中最簡單的使用
test_request_context()環(huán)境管理器
from flask import request
with app.test_request_context('/hello',method='POST'):
assert request.method=='POST'
assert request.path=='/hello'
另外一種可能,傳遞整個(gè)WSGI環(huán)境request_context()方法
from flask import request
with app.request_context(environ):
assert request.method=='POST'
5.重定向和錯(cuò)誤
redirect(location,code=301)函數(shù)把用戶重新定向到其他地方,和url_for()結(jié)合使用。abort()放棄請求并返回錯(cuò)誤碼
from flask import abort,url_for,redirect
@app.route('/')
def index():
retuen redirect(url_for('login'))
@app.route('/login')
def login():
abort(401)
this_is_never_execute()
定制錯(cuò)誤頁面,使用errorhandler()裝飾器
from flask import render_template
@app.errorhandler(404)
def page_not_found(error):
return render_template('page_not_found.html'),404
實(shí)例
from flask import Flask,request,redirect,abort,url_for,render_template
app=Flask(__name__)
app.config.from_object("config")
@app.route('/people/')
def people():
name=request.args.get("name")
if not name:
return redirect(url_for("login"))
user_agent=request.headers.get("User-Agent")
return "Name:{0};UA:{1}".format(name,user_agent)
@app.route('/login/',methods=["GET","POST"])
def login():
if request.method=="POST":
user_id=request.form.get("user_id")
return "User:{} login".format(user_id)
else:
return render_template('login.html')
@app.route('/secret/')
def secret():
abort(401)
print('This is never execute!')
if __name__ == '__main__':
app.run()
login.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="../static/css/bootstrap.min.css" />
<title>登錄</title>
</head>
<body>
<form class="form-inline" method="post">
<div class="form-group">
<lable>用戶名</lable>
<input type="text" name="user_id" class="form-control" />
</div>
<div class="form-group">
<lable>密碼</lable>
<input type="password" name="pw" class="form-control" />
</div>
<div class="form-group">
<input type="submit" class="form-control" value="登錄" />
</div>
</form>
<script src="../static/js/jquery-3.3.1.min.js"></script>
<script src="../static/js/bootstrap.min.js"></script>
</body>
</html>