flask鑷畾涔夎浆鎹㈠櫒
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了flask鑷畾涔夎浆鎹㈠櫒相关的知识,希望对你有一定的参考价值。
鏍囩锛?a href='http://www.mamicode.com/so/1/converter' title='converter'>converter
__init__ div ini __name__ integer 鍏冲績 浣跨敤 缁ф壙flask浣滀负杞诲瀷WEB妗嗘灦锛屽湪web寮€鍙戜腑锛屽彲鑳戒細鍑虹幇闄愬埗鐢ㄦ埛璁块棶鐨勮鍒欑殑鍦烘櫙锛岄偅涔堣繖涓椂鍊欙紝灏遍渶瑕佽繃婊ゆ寚瀹氱敤鎴凤紝鎵€浠ュ彲浠ヤ娇鐢ㄨ浆鎹㈠櫒瀹炵幇銆?br>杞崲鍣ㄧ殑鏈川鏄細閫氳繃姝e垯琛ㄨ揪寮忓尮閰嶈矾鐢卞湴鍧€
flask 绯荤粺鑷甫鐨勮浆鎹㈠櫒鏈?br>
褰撴垜浠嚜瀹氫箟杞崲鍣ㄧ殑鏃跺€欑殑鏈変互涓嬫楠わ細
瀵煎叆杞崲鍣ㄥ熀绫伙紙BaseConverter锛?Flask涓墍鏈夌殑璺敱鐨勫尮閰嶈鍒欙紝閮芥槸浣跨敤杞崲鍣ㄥ疄鐜?br>鑷畾涔夎浆鎹㈠櫒缁ф壙浜庤浆鎹㈠櫒鍩虹被
娣诲姞杞崲鍣ㄥ埌榛樿鐨勮浆鎹㈠櫒瀛楀吀涓?br>浣跨敤鑷畾涔夎浆鎹㈠櫒瀹炵幇鑷畾涔夊尮閰嶈鍒?/div>
鏃㈢劧鑷畾涔夎浆鎹㈠櫒闇€瑕佺户鎵胯浆鎹㈠櫒鍩虹被锛圔aseConverter锛夐偅涔堟垜浠湅涓€涓嬭浆鎹㈠櫒鍩虹被鐨勬簮鐮併€?
flask 绯荤粺鑷甫鐨勮浆鎹㈠櫒鏈?br>
DEFAULT_CONVERTERS = { 鈥榙efault鈥? UnicodeConverter, 鈥榮tring鈥? UnicodeConverter, 鈥榓ny鈥? AnyConverter, 鈥榩ath鈥? PathConverter, 鈥榠nt鈥? IntegerConverter, 鈥榝loat鈥? FloatConverter, 鈥榰uid鈥? UUIDConverter, }
褰撴垜浠嚜瀹氫箟杞崲鍣ㄧ殑鏃跺€欑殑鏈変互涓嬫楠わ細
瀵煎叆杞崲鍣ㄥ熀绫伙紙BaseConverter锛?Flask涓墍鏈夌殑璺敱鐨勫尮閰嶈鍒欙紝閮芥槸浣跨敤杞崲鍣ㄥ疄鐜?br>鑷畾涔夎浆鎹㈠櫒缁ф壙浜庤浆鎹㈠櫒鍩虹被
娣诲姞杞崲鍣ㄥ埌榛樿鐨勮浆鎹㈠櫒瀛楀吀涓?br>浣跨敤鑷畾涔夎浆鎹㈠櫒瀹炵幇鑷畾涔夊尮閰嶈鍒?/div>
鏃㈢劧鑷畾涔夎浆鎹㈠櫒闇€瑕佺户鎵胯浆鎹㈠櫒鍩虹被锛圔aseConverter锛夐偅涔堟垜浠湅涓€涓嬭浆鎹㈠櫒鍩虹被鐨勬簮鐮併€?
class BaseConverter(object): """Base class for all converters.""" regex = 鈥榌^/]+鈥? weight = 100 def __init__(self, map): self.map = map def to_python(self, value): return value def to_url(self, value): return url_quote(value, charset=self.map.charset)
銆€銆€
鑷畾涔夎浆鎹㈠櫒浠g爜
from flask import Flask #瀵煎叆鍩虹被杞崲鍣?from werkzeug.routing import BaseConverter app = Flask(__name__) # 1.鑷畾涔夌被,缁ф壙鑷狟aseConverter class MyRegexConverter(BaseConverter): # 2.缂栧啓鍒濆鍖栨柟娉? init鏂规硶, 鎺ユ敹涓や釜鍙傛暟, url_map, regex, 骞跺垵濮嬪寲鐖剁被绌洪棿鍜屽瓙绫荤┖闂? def __init__(self,url_map,regex): super(MyRegexConverter, self).__init__(url_map) self.regex = regex # 3.灏嗚嚜瀹氫箟杞崲鍣ㄧ被,娣诲姞鍒伴粯璁ょ殑杞崲鍒楄〃涓?app.url_map.converters[鈥榬e鈥榏 = MyRegexConverter #浣跨敤鑷畾涔夎浆鎹㈠櫒 #鎺ユ敹3浣嶆暣鏁?@app.route(鈥?<re("d{3}"):num>鈥? def hello_world(num): print("num = %s"%num) return "the num is %s"%num #鎺ユ敹涓€涓墜鏈哄彿 @app.route(鈥?<re("1[345678]d{9}"):mobile>鈥? def get_phone_number(mobile): return "the mobile is %s"%mobile if __name__ == 鈥榑_main__鈥? app.run()
銆€銆€
鑷畾涔夎浆鎹㈠櫒鍖归厤閿欒鑷姩璺宠浆缃戠珯棣栭〉
from flask import Flask from flask import redirect from flask import url_for from werkzeug.routing import BaseConverter app = Flask(__name__) class MyConverter(BaseConverter): def __init__(self,url_map,regex): super(MyConverter, self).__init__(url_map) self.regex = regex def to_python(self, value): # 鍖归厤鎴愬姛鍚庤璋冪敤锛屽彲浠ュ鍖归厤鍒扮殑鍙傛暟杩涜澶勭悊锛屾瘮濡傝浆鎹㈠尮閰嶅埌鐨勬暟鎹殑绫诲瀷锛屽湪姝e垯鍖归厤瀹屾垚涔嬪悗锛岃皟鐢ㄨ鍥惧嚱鏁颁箣鍓嶏紝鍙互瀵规暟鎹繘琛屾渶鍚庣殑澶勭悊 return value def to_url(self, value): # 鍦ㄦ鍒欏尮閰嶄箣鍓嶈皟鐢ㄦ墽琛岋紝骞朵紶鍏ュ弬鏁帮紝璋冪敤瀹屾垚涔嬪悗鎵嶅紑濮嬬湡姝g殑璺敱鍖归厤锛屼笉鍏冲績鏄惁鍖归厤鎴愬姛锛屽彲浠ラ€氳繃姝ゅ嚱鏁颁慨姝h浼犲叆璺敱涓殑鍙傛暟锛屾柟渚挎洿濂界殑姝e垯鍖归厤 return value app.url_map.converters[鈥榬e鈥榏 = MyConverter @app.route(鈥?<re("d{3}"):num>鈥? def index(num): return num @app.errorhandler(404) def my_error(e): return redirect(url_for(鈥榡ia鈥?) @app.route(鈥?jia鈥? def jia(): return 鈥榡ai鈥? if __name__ == 鈥榑_main__鈥? app.run(debug=True)
銆€銆€
以上是关于flask鑷畾涔夎浆鎹㈠櫒的主要内容,如果未能解决你的问题,请参考以下文章
python pyMysql 鑷畾涔夊紓甯? 鍑芥暟閲嶈浇