flask進階

內容:html

1.flask閃現及cookie和session前端

2.flask請求拓展python

3.json API和RESTful  APIdjango

4.flask中間件json

5.藍圖與紅圖flask

6.flask上下文管理後端

 

flask框架基礎:http://www.javashuo.com/article/p-mkpnpxcn-dx.htmlcookie

flask框架詳細:http://www.cnblogs.com/wupeiqi/articles/7552008.htmlsession

 

 

 

1.flask閃現及cookie和session多線程

(1)flask閃現

 1 # encoding: utf-8
 2 # __author__ = "wyb"
 3 # date: 2018/9/9
 4 from flask import Flask, flash, get_flashed_messages
 5 
 6 app = Flask(__name__)
 7 app.secret_key = 'wyb test flash'
 8 
 9 
10 @app.route('/get')
11 def get():
12     # 從某個地方獲取設置過的值並清除
13     data = get_flashed_messages()
14     print(data)
15     return 'Hello World!, msg: {}'.format(data)
16 
17 
18 @app.route('/set')
19 def set():
20     # 向某個地方設置一個值
21     flash("xxx")
22 
23     return 'Hello World!'
24 
25 
26 if __name__ == '__main__':
27     app.run(debug=True)

 

應用:對臨時數據操做,如:顯示錯誤信息,以下所示:

 1 # encoding: utf-8
 2 # __author__ = "wyb"
 3 # date: 2018/9/9
 4 from flask import Flask, flash, get_flashed_messages, request, redirect, url_for
 5 
 6 app = Flask(__name__)
 7 app.secret_key = 'wyb test flash'
 8 
 9 @app.route('/index')
10 def index():
11     val = request.args.get('v')
12     if val == 'wyb':
13         return 'Hello wyb!'
14     else:
15         # 向某個地方設置一個值
16         flash("超時錯誤")
17     # 重定向到錯誤頁面
18     return redirect(url_for("error"))
19 
20 @app.route('/error')
21 def error():
22     # 從某個地方獲取設置過的值並顯示在頁面上
23     data = get_flashed_messages()
24     print(data)
25     return 'Error: {}'.format(data)
26 
27 
28 if __name__ == '__main__':
29     app.run(debug=True)

另外flash還能夠設置分類來限制get_flashed_messages獲取的數據:

1 # 向某個地方設置一個值
2 flash("超時錯誤", category="c1")
3 
4 # 從某個地方獲取設置過的值並顯示在頁面上
5 data = get_flashed_messages(category_filter=["c1"])  # 只能拿c1類的數據

 

(2)cookie和session

詳細內容: http://www.javashuo.com/article/p-ceqcahvy-ba.html

 

 

2.flask請求拓展

(1)什麼是請求拓展

相似django中的中間件,能夠對請求進行相應的處理,django中相似的是process_request和process_response

 

(2)實例

 1 # encoding: utf-8
 2 # __author__ = "wyb"
 3 # date: 2018/9/9
 4 from flask import Flask, Request, render_template
 5 
 6 app = Flask(__name__, template_folder='templates')
 7 app.debug = True
 8 
 9 @app.before_first_request       # -> 在第一次請求以前執行
10 def before_first_request():
11     print('第一次請求 - before_first_request')
12 
13 @app.before_request             # -> 請求以前執行
14 def process_request():
15     # 在這裏能夠寫登錄驗證
16     """
17         if request.path == '/login':
18             return None
19         user = session.get('user_info')
20         if user:
21             return None
22         return redirect('/login')
23     """
24     print('進來了 - before_request')
25 
26 @app.after_request              # -> 請求以後執行
27 def process_response(response):
28     print('出去了 - after_request: ', response)
29     return response
30 
31 
32 # 定製錯誤信息:
33 @app.errorhandler(404)          # -> 404處理
34 def page_not_found(error):
35     return 'This page does not exist', 404
36 
37 @app.route('/')
38 def hello_world():
39     return "Hello world!"
40 
41 
42 if __name__ == '__main__':
43     app.run(debug=True)

運行以後訪問首頁以及不存在的頁面輸出以下:

注意:多個before_request的執行順序是從上到下(先執行先定義的before_request),多個after_request的順序是從下到上(先執行後定義的after_request)

 

 

3.json API和RESTful  API

(1)什麼是json API

簡而言之就是後端對前端的接口是json格式,後端返回json格式的數據,前端用Ajax技術獲取這些數據,而後用js將這些數據渲染到頁面上

json API的好處:

  • 先後端分離
  • 渲染只發生在前端,後端無需關注渲染,只用提供數據接口便可
  • 後端可使用多種語言(python、PHP、Java等)編寫,只要這種語言支持json便可

flask的json API簡單實例:

 1 # encoding: utf-8
 2 # __author__ = "wyb"
 3 # date: 2018/9/6
 4 from flask import Flask, redirect, url_for, jsonify, request
 5 
 6 app = Flask(__name__)
 7 users = []
 8 
 9 @app.route("/", methods=["GET"])
10 def index():
11     return'''<form method=post action='/add'>
12     <input type=text name=author>
13     <button>提交</button>
14     </form>
15     '''
16 
17 @app.route("/add", methods=["POST"])
18 def add():
19     form = request.form
20     users.append(dict(author=form.get("author", "")))
21     return redirect(url_for(".index"))
22 
23 # json API:
24 @app.route("/json")
25 def json():
26     # 下面返回的是json格式的數據
27     return jsonify(users)
28 
29 app.run(debug=True)

 

(2)RESTful  API

RESTful API:由Dr. Fielding提出,指出url能夠是一種用資源來組織的名詞,能夠用URL來定位資源,用HTTP動詞(GET,POST,PUT,DELETE)來描述操做

  • Resource:資源,即數據
  • Representational:某種表現形式,好比用JSON,XML,JPEG等
  • State Transfer:狀態變化。經過HTTP動詞實現

RESTful API就是REST風格的API

RESTful API的使用場景:

在當今的互聯網應用的前端展現媒介很豐富。有手機、有平板電腦還有PC以及其餘的展現媒介。那麼這些前端接收到的用戶請求統一由一個後臺來處理並返回給不一樣的前端確定是最科學和最經濟的方式,

RESTful API就是一套協議來規範多種形式的前端和同一個後臺的交互方式

RESTful API實例:

1 /GET /players 拿到全部玩家
2 /GET /player/id 訪問id的玩家的數據
3 /PUT /players 全量更新
4 /PATCH /players 部分更新
5 /DELETE /player/id 刪除一個玩家
6 /GET /player/id/level 訪問id的玩家的數據中的level

 

 

4.flask中間件

flask請求入口要執行wsgi_app,因此咱們能夠經過在一個類中保存wsgi_app而後重寫call方法,再將這個類實例化返回給app.wsgi_app便可對請求進行相應處理

 1 # encoding: utf-8
 2 # __author__ = "wyb"
 3 # date: 2018/9/9
 4 
 5 from flask import Flask
 6 
 7 app = Flask(__name__)
 8 app.secret_key = 'some_secret'
 9 
10 @app.route('/')
11 def index():
12     return "index"
13 
14 # 中間件
15 class MiddleWare:
16     def __init__(self, old_wsgi_app):
17         self.old_wsgi_app = old_wsgi_app
18 
19     def __call__(self, *args, **kwargs):
20         print("開始以前")
21         return self.old_wsgi_app(*args, **kwargs)
22 
23 if __name__ == "__main__":
24     app.wsgi_app = MiddleWare(app.wsgi_app)
25     app.run()

 

解釋以下:

 

 

5.flask藍圖與紅圖

藍圖:用於實現單個應用的視圖、模板、靜態文件的集合。

藍圖就是模塊化處理的類

紅圖:通常用藍圖實現模塊的劃分,用紅圖來實現模塊中視圖函數(具體功能)的劃分

簡單來講,藍圖就是一個存儲操做路由映射方法的容器,主要用來實現客戶端請求和URL相互關聯的功能。 在Flask中,使用藍圖能夠幫助咱們實現模塊化應用的功能

藍圖與紅圖詳細內容:http://www.javashuo.com/article/p-emgarktr-dn.html

 

 

6.flask上下文管理

關於flask的上下文:http://www.cnblogs.com/wupeiqi/articles/8202353.html

(1)threading.local對象

threading.local對象用於爲每一個線程開闢一塊空間來保存它獨有的值

 1 import threading
 2 
 3 local_values = threading.local()        # 至關於對數據加鎖
 4 
 5 def func(num):
 6     local_values.name = num
 7     import time
 8     time.sleep(1)
 9     print(local_values.name, threading.current_thread().name)
10 
11 for i in range(20):
12     th = threading.Thread(target=func, args=(i,), name='線程%s' % i)
13     th.start()

 

(2)源碼(request)

  • 狀況一:單進程單線程,基於全局變量作
  • 狀況二:單進程多線程,threading.local對象
  • 狀況二:單進程單線程(多個協程),threading.local對象作不到


決定:
- 之後不支持協程:threading.local對象。
- 支持:自定義相似threading.local對象(支持協程)
- 自定義相似threading.local對象
注意:

1 a:
2 object.__setattr__(self, 'storage', {})
3 self.storage = {}
4 
5 b:
6 對象.xx
7 def __setattr__(self, key, value):
8 print(key,value)
相關文章
相關標籤/搜索