1. 程式人生 > >Python 你必須要知道的 Flask

Python 你必須要知道的 Flask

Flask介紹

Flask 是一個輕量級的 web 開發框架, 使用 Python 開發, 上手簡單。

安裝 Flask

pip install Flask

第一個 Flask 程式

1、編寫 app.py 檔案內容如下:

#encoding: utf-8

# 匯入Flask類
from flask import Flask

# 建立Flask例項
app = Flask(__name__)

# 定義路由, 由index函式處理url為/的GET請求
@app.route('/')
def index():
   # 返回響應內容
   return 'Hello, Silence' 

# 指令碼執行執行程式碼
if __name__ == '__main__':
   # 啟動Flask例項, 設定監聽0.0.0.0:9001, 開啟除錯模式
   app.run(host='0.0.0.0', port=9001, debug=True)

2、啟動程式

 python app.py

3、瀏覽器訪問 http://localhost:9001/ 檢視顯示內容

4、程式說明

  • Line 4: 匯入 Flask 類

  • Line 7: 建立 Flask 例項, 第一個引數為模組或者包的名稱, 模組名稱會根據是否單獨應用而變化因此可以選擇使用 name 變數動態指定, 該引數與 Flask 查詢static 和 template 檔案位置有關

  • Line 10: 定義路由 endpoint=/, 表示有 index 函式處理請求 url 為/的 GET 請求

  • Line 18: 啟動 app, 執行監聽的 host:port, 在測試環境開啟除錯模

  • 注意: debug 模式是不安全的, 在生產環境應該關閉

路由

1、路由用於將 python 函式繫結到 url 上, 一個函式可以繫結多個路由規則, 也可以構建動態的 url

@app.route('/users/')
@app.route('/users/<uid>/')
def users(uid=None):
   return 'ID: %s' % uid

2、訪問瀏覽器 http://localhost:9001/users/

 

3、訪問瀏覽器 http://localhost:9001/users/12/

 

4、在動態 url 中通過新增變數<varname>將引數傳遞到函式中, 在新增變數可以使用 <converter:varname> 指定 varname 的型別

@app.route('/users/<int:uid>/')
def user_uid(uid):
   return 'UID: %s' % uid

converter 支援 int, float, path 三種類型

5、路由中的 endpoint 有兩種模式, 以/結尾和不以/結尾

對於以/結尾的 route, 在瀏覽器中訪問 url 時若不以/結尾, 會被 flask 重定向到與以/結尾的 endpoint 上

對於不以/結尾的 route, 在瀏覽器中訪問 url 時若以/結尾, 則會返回 404 錯誤

個人建議: 在定義 route 和使用 url 訪問時結尾都加上/

6、路由中可以通過 methods 指定函式處理的 HTTP 方法, 預設只處理 GET 方法

@app.route('/users/', methods=["GET", "POST"])
@app.route('/users/<uid>/', methods=["GET", "PUT", "DELETE"])
def users(uid=None):
   print type(uid)
   return 'ID: %s' % uid

HTTP 方法:

  • GET: 獲取內容

  • POST: 提交新資料

  • HEAD: 檢查資料是否存在

  • PUT: 覆蓋資料

  • DELETE: 刪除資料

  • OPTIONS: 檢查伺服器支援哪些方法

模板

1、專案目錄結構:

.
├─ app.py
├─ static
└─ templates
    └─ users.html

2、模板存放目錄為 /templates/

3、渲染模板

# 匯入render_template
from flask import render_template

@app.route('/users/')
def users():
   user_list = [{'name' : 'silence', 'sex' : 1, 'email' : '[email protected]'}]
   # 渲染模板
   return render_template('users.html', title=u"使用者管理", users=user_list)

說明:

  • Line 2: 匯入 render_template 函式

  • Line 8: 使用 render_template 函式渲染模板 users.html, 並將變數 title 和users 傳遞給模板

4、模板定義

<!DOCTYPE html>
<html>
   <head>
       <meta charset="utf-8"/>
       <title>{{title}}</title>
   </head>
   <body>
       <table style="border: 1px solid black;">
           <thead>
               <tr>
                   <th>使用者名稱</th>
                   <th>性別</th>
                   <th>郵件</th>
               </tr>
           </thead>
           <tbody>
           {% for user in users %}
               <tr>
                   <td>{{user.name}}</td>
                   <td>
                   {% if user.sex == 1 %}
                   男
                   {% else %}
                   女
                   {% endif %}
                   </td>
                   <td>{{user['email']}}</td>
               </tr>
           {% else %}
               <tr><td colspan="3">暫無資料</td></tr>
           {% endfor %}
           </tbody>
       </table>
   </body>
</html>

說明:

  • Line 5: 將 title 變數渲染到模板中, 需要使用兩個大括號包含變數

  • Line 17: 遍歷 users, for 語句需要被包含在大括號百分號之中,結束需要用 endfor

  • Line 21: 條件判斷, if 語句需要被包含在大括號百分號之中,結束需要用 endfif

5、訪問瀏覽器 http://localhost:9001/users/

 

靜態檔案

可以在模板中引入本地的 js, css, 圖片等資原始檔

說明:

  1. 靜態資原始檔需要放置在 static 目錄

  2. 在模板中使用 /static/filename.suffix 的格式引入檔案

  3. 可以使用 url_for('static', filename=filename.suffix) 函式自動生成 url 引入檔案

請求引數

from flask import request

@app.route('/users/', methods=["GET", "POST"])
def users():
   if request.method == 'GET':
       return 'GET ID:%s' % request.args.get('id')
   else:
       return 'GET ID:%s' % request.form.get('id')

說明:

  • Line 1: 匯入 reqeust 物件

  • Line 5: 通過 reqeust.method 獲取請求方法

  • Line 6: 通過 reqeust.args 獲取 GET 請求提交的引數

訪問瀏覽器 http://localhost:9001/users/?id=123

 

  • Line 8: 通過 reqeust.form 獲取 POST 請求提交的引數

通過 curl 訪問 http://localhost:9001/users/

 

  • 若需要上傳檔案則需要使用 request.files 獲取提交的引數並通過 save 函式儲存到伺服器上

from werkzeug import secure_filename

@app.route('/users/', methods=["POST"])
def image():
   img = request.files.get('img')
   if img is not None:
       img.save('e:/tmp/%s' % secure_filename(img.filename))

需要注意在儲存使用者上傳的檔案時注意對檔名進行安全處理, 或者使用自己的命名規則,切忌不要直接使用檔名儲存到伺服器中

cookie

from flask import make_response
@app.route('/users/')
def users():
   response = make_response('Hello, Silence')
   response.set_cookie('locale', 'zh_CN')
   print request.cookies.get('locale')
   return response

 

說明:

  1. Line 1: 匯入 make_response 函式

  2. Line 4: 通過 make_response 建立 response 物件

  3. Line 5: 設定 cookie 資訊 locale=zh_CN

  4. Line 6: 獲取 cookie 中資訊

 

會話

 

from flask import session
from flask import redirect

app.secret_key = 'ABCDEFGHIGKLMNOPQRST'

@app.route('/login/', methods=["POST"])
def login():
   if validate_login(request.form.get('username'), request.form.get('password')):
       session['user'] = {'username' : request.form.get('username')}
       return redirect('/users/')
   else:
       return render_template('login.html')

@app.route('/users/')
def users():
   return session.get('user', {}).get('username')

@app.route('/logout/')
def logout():
   session.pop('user')
   session.clear()
   return render_template('login.html')

說明:

  1. Line 1: 匯入 session 物件

  2. Line 9: 在 session 中儲存資訊

  3. Line 2: 匯入重定向函式 redirect

  4. Line 10: 重定向到 /users/

  5. Line 16: 獲取 session 中儲存的資訊

  6. Line 20: 刪除 session 中的資訊

  7. Line 21: 銷燬 session 中的所有資訊

  8. Line 4: 設定 session 簽名所使用的金鑰, 可以使用 os.urandom(32) 來生成強壯的金鑰

Python 零基礎學習