python视图函数是什么意思_Flask初学者:视图函数
視圖函數(shù)返回html模板:使用“from flask import render_template”,在函數(shù)中傳入相對于文件夾“templates”html模板路徑名稱字符串即可,flask會自動到項目根目錄的“templates”文件夾(創(chuàng)建flask項目時,pycharm會自動創(chuàng)建兩個空文件夾,其中一個就是“templates”)下尋找對應(yīng)的html文件;如果需要給html模板傳參,則在“render_template”中使用變量名或字典進行傳參即可(在python2中,如果涉及中文,需要使用unicode字符串)。如圖:
視圖函數(shù)返回response對象:視圖函數(shù)返回響應(yīng)response給瀏覽器,一般來說只能是字符串和固定格式的元組,當然也可以自定義,但無論是返回哪種數(shù)據(jù)格式,最終都是被包裝成一個response對象返回給瀏覽器的。返回的是字符串時,其實也是被包裝成response對象返回給瀏覽器的。也可以是一個固定格式的元組:(response, status, headers),即響應(yīng)體、狀態(tài)碼和頭信息的元組,可以只返回一個response,或者兩個(response, status),或者全部返回(response, status, headers)。當可以自定義返回的響應(yīng)體時需要注意以下幾點:
response子類:自定義的response子類必須繼承自from flask import response(其實就是from werkzeug.wrappers import response)。
response_class:使用app.response_class=myresponse使之生效。
force_type(response, environ=none):當返回的數(shù)據(jù)類型,既不是字符串,也不是元組時,flask就會調(diào)用response的force_type方法來處理,如果不能處理就會返回錯誤,所以response子類一般是需要重寫這個方法來返回一個合法的數(shù)據(jù),參數(shù)response即為傳入的不合法的數(shù)據(jù),可以經(jīng)過處理后返回一個合法的response對象。
1 from flask import flask, response
2
3 app = flask(__name__)
4
5
6 class myresponse(response):
7 """自定義response類"""
8 @classmethod
9 def force_type(cls, response, environ=none):
10 """重寫force_type方法,當參數(shù)既不是字符串,
11 也不是(response, status, headers)元組時會調(diào)用此方法"""
12 if isinstance(response, list):
13 response = response('+'.join(response))
14
15 # 這里需要包裝成response對象才能傳入父類的force_type中,
16 # 只傳字符串會報錯
17 return super().force_type(response, environ)
18
19
20 # 指定自定義的response類,使之生效
21 app.response_class = myresponse
22
23
24 @app.route('/listresponse/')
25 def list_response():
26 # 返回一個不合法的數(shù)據(jù)
27 # 如果沒有自定義的response類來處理的話,就會報錯
28 return ['python', '36']
29
30
31 if __name__ == '__main__':
32 app.run(debug=true)
希望與廣大網(wǎng)友互動??
點此進行留言吧!
總結(jié)
以上是生活随笔為你收集整理的python视图函数是什么意思_Flask初学者:视图函数的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: linux下toe网卡驱动,toe命令是
- 下一篇: ssh登陆慢/xhell访问主机慢