flask第二十一篇——練習題
阿新 • • 發佈:2018-04-04
視圖 函數 content edi values == 一個 debug tin
自定義url轉化器
實現一個自定義的URL轉換器,這個轉換器需要滿足的是獲取從多少到多少的url,例如,你輸入的地址是http://127.0.0.1:8000/1-5/
,那麽頁面返回[1,2,3,4,5]
。
答案:
1 # coding: utf-8 2 3 from flask import Flask 4 from werkzeug.routing import BaseConverter 5 6 app = Flask(__name__) # type: Flask 7 app.debug = True 8 9 @app.route(‘/‘) 10 def hello_world():11 return ‘Hello World!‘ 12 13 class NumConverter(BaseConverter): 14 15 regex = r‘\d+-\d+‘ 16 17 # 把url中的參數傳到視圖函數中,用to_python方法 18 def to_python(self, value): 19 tmp = value.split(‘-‘) 20 if int(tmp[0]) < int(tmp[-1]): 21 nums = range(int(tmp[0]), int(tmp[-1])+1)22 return str(nums) 23 else: 24 return u‘請檢查傳入的參數‘ 25 26 # 把類似[1,2,3]這樣的列表轉換成/1-3/這種url 27 def to_url(self, value): 28 min = value[0] 29 max = value[-1] 30 temp = ‘%s-%s‘ % (min, max) 31 return temp 32 33 app.url_map.converters[‘num‘] = NumConverter 34 35 @app.route(‘/login/<num: values>/‘) 36 def numList(values): 37 return values 38 39 if __name__ == ‘__main__‘: 40 app.run()
flask第二十一篇——練習題