一、Flask的默認轉換器
轉換器 | 含義 |
---|---|
default | 接受字符串,默認轉換器 |
stirng | 接受字符串,跟默認一樣 |
int | 接受整數 |
float | 同 int ,但是接受浮點數 |
uuid | 唯一識別碼 |
path | 和默認的相似,但也接受斜線 |
二、自己定義一個轉換器
在Flask中,默認支持6種轉換器,但這些轉換器並不能完全按照我們的意願去接受,比如我們想接受一個手機號
這些默認的轉換器就不能幫我們實現,我們就可以自己定義一個轉換器
步驟如下:
-
導入轉換器基類
BaseConverter
rom werkzeug.routing import BaseConverter
-
自定義類繼承於轉換器基類
class PhoneConverter(BaseConverter):#我這裏定義電話轉換器 def __init__(self,map): BaseConverter.__init__(self, map) self.regex=r'1[34578]\d{9}'
-
添加轉換器到默認的轉換器字典
app.url_map.converters
中app.url_map.converters['phone']=PhoneConverter
-
使用自定義轉換器實現自定義匹配規則
@app.route("/<phone:number>")
三、萬能一點!
class ReConverter(BaseConverter):#我這裏定義萬能轉化器
def __init__(self,map,regex):
BaseConverter.__init__(self, map)
self.regex=regex
app.url_map.converters['re']=ReConverter#添加
@app.route("/<re(r'1[34578]\d{9}'):number>")#使用時通過正則表達式實現