flask入門(二)

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ù)。

圖片發(fā)自簡書App

環(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>
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 136,539評論 19 139
  • 2017-01-11 雨哥官微(公眾號) 九大理賠保險(xiǎn)從意義和功用上劃分,分為保障和理財(cái)兩塊那所謂的保障就是保人的...
    簡單做事閱讀 639評論 0 2
  • 母親節(jié),我懷著孩子的心,敲開了母親的門,母親在家里守著一屋子的寂寞,等待著我——遠(yuǎn)嫁的閨女??吹侥赣H的瞬間,我心里...
    梅園遺珠閱讀 485評論 0 1
  • 小時(shí)候電腦還未普及的時(shí),流行過一段問候卡,大抵是過年時(shí)較多,生日偶爾也會(huì)收到,當(dāng)然零零后可能就不知道了。 一般來說...
    雪方明閱讀 199評論 0 0

友情鏈接更多精彩內(nèi)容