flask框架 視圖函數當中 各種實用情況簡單配置
1 建立連接
2 路由參數
3 返回網絡狀態碼
4 自定義錯誤頁面
5 重定向
6 正則url限制 和 url 優化
7 設置和獲取cookie
1 #coding:utf8
2 # 導入flask
3 from flask import Flask,abort,redirect,make_response,request 4 from werkzeug.routing import BaseConverter 5
6
7 # Flask 接受一個參數__name__ 作用是指明應用的位置
8 app = Flask(__name__) 9
10
11
12 '''
13 1 建立一個前后台鏈接 14 裝飾器的作用是陸游映射到視圖函數index 15 訪問根目錄就會進入index視圖函數 16 '''
17 @app.route('/') 18 def index(): 19 # 返回后會調用make_response
20 return "你好 世界!"
21
22
23 '''
24 2 給路由傳參數 25 傳遞的參數在<name>當中 這個變量名稱也要傳遞給視圖函數 26 可以在<int:name> 或者<string:name> 指定傳遞參數的類型 27 不指定類型默認使用string類型 28 '''
29 @app.route('/attr/<string:attr>') 30 def attr(attr): 31 return "hello,%s"%attr 32
33
34 '''
35 3 返回網絡狀態碼的兩種方式 36 01 return 字符串,狀態碼 37 02 abort(狀態碼) 38 200 成功 39 300 重定向 40 404 未找到 41 500 服務器內部錯誤 42 '''
43 #01 return 字符串,狀態碼 這種方式 可以返回不存在的狀態碼 前端依然能得到頁面
44 @app.route('/status') 45 def status(): 46 # 用這種方式可以返回假的狀態碼 前端依然能夠渲染
47 return 'hello status',999
48
49 #02 利用abort(狀態碼) 進行返回狀態碼,只能寫入真的狀態碼
50 # 這個函數的作用是 自定義我們項目的 出錯頁面
51 @app.route('/abort') 52 def geive500(): 53 abort(500) 54
55 '''
56 4 捕獲訪問我們flask后台發生各種錯誤的情況 57 利用@app.errorhandler(500) 進行裝飾 能截獲500的response 58 '''
59 # 捕獲500異常 函數當中接受到錯誤信息
60 @app.errorhandler(500) 61 def error500(e): 62 return "您請求的頁面后台發生錯誤!錯誤信息:%s"%e 63 @app.errorhandler(404) 64 def error404(e): 65 return "您訪問的頁面飛去了火星!信息:%s"%e 66
67 '''
68 5 重定向 69 有兩種方式: 70 01 redirect(url) 71 02 url_for(視圖函數) 72 '''
73 @app.route('/redirect') 74 def redir(): 75 return redirect('http://www.baidu.com') 76
77
78 '''
79 6 url正則 80 兩個用途: 限制訪問 和 優化訪問路徑 81 使用: 82 01首先要 定義一個繼承自BaseConverter的子類 83 在子類里面調用父類的初始化方法 84 重寫父類的變量 85 02然后 給applurl_map.converters 字典添加re健 和 我們自己寫的類做val 86
87 03最后 視圖函數的app.route('路徑<re(正則),變量名>') 88 變量名要傳給視圖函數做參數 89 '''
90 # 01 寫一個繼承自 BaseConverter的子類 相應的方法和屬性要重寫
91 class Regex_url(BaseConverter): 92 def __init__(self,url_map,*args): 93 super(Regex_url,self).__init__(url_map) 94 self.regex = args[0] 95 # 02 添加re映射
96 app.url_map.converters['re'] = Regex_url 97 # 03 正則匹配參數
98 # 利用正則對傳入參數進行限制
99 # 只有1到3位小寫英文才能成功 否則都是404
100 @app.route('/attr2/<re("[a-z]{1,3}"):attr>') 101 def attr2(attr): 102 return "hello %s"%attr 103
104
105 '''
106 7 設置cookie 和 獲取 cookie 107 設置cookie: 108 利用 make_response() 拿到response對象 109 response.set_cookie(key,val) 110 獲取cookie: 111 利用request.cookies.get(key) 獲取cookie 112 '''
113 # 設置cookie
114 @app.route('/set_cookie') 115 def setCookie(): 116 response = make_response('設置cookie') 117 response.set_cookie('log','設置的cookie') 118 return response 119
120 # 獲取cookie
121 @app.route('/get_cookie') 122 def getCookie(): 123 log = request.cookies.get('log') 124 return log 125
126
127 if __name__ == '__main__': 128 # 執行后台服務器
129 app.run(debug=True)
