1.可傳入參數:
@app.route('/user/
') #常用的 不加參數的時候默認是字符串形式的
@app.route('/post/
') #常用的 #指定int,說明是整型的
@app.route('/post/
')
@app.route('/post/
')
@app.route('/login', methods=['GET', 'POST'])
DEFAULT_CONVERTERS = {
'default': UnicodeConverter,
'string': UnicodeConverter,
'any': AnyConverter,
'path': PathConverter,
'int': IntegerConverter,
'float': FloatConverter,
'uuid': UUIDConverter,
}
2.反向生成URL: url_for
endpoint("name") #別名,相當于django中的name
from flask import Flask, url_for
'''
遇到不懂的問題?Python學習交流群:821460695滿足你的需求,資料都已經上傳群文件,可以自行下載!
'''
@app.route('/index',endpoint="xxx") #endpoint是別名
def index():
v = url_for("xxx")
print(v)
return "index"
@app.route('/zzz/
',endpoint="aaa") #endpoint是別名
def zzz(nid):
v = url_for("aaa",nid=nid)
print(v)
return "index2"
3. @app.route和app.add_url_rule參數
@app.route和app.add_url_rule參數:
rule, URL規則
view_func, 視圖函數名稱
defaults=None, 默認值,當URL中無參數,函數需要參數時,使用defaults={'k':'v'}為函數提供參數
endpoint=None, 名稱,用于反向生成URL,即: url_for('名稱')
methods=None, 允許的請求方式,如:["GET","POST"]
strict_slashes=None, 對URL最后的 / 符號是否嚴格要求,
如:
@app.route('/index',strict_slashes=False), #當為False時,url上加不加斜杠都行
訪問 http://www.xx.com/index/ 或 http://www.xx.com/index均可
@app.route('/index',strict_slashes=True) #當為True時,url后面必須不加斜杠
僅訪問 http://www.xx.com/index
redirect_to=None, 由原地址直接重定向到指定地址,原url有參數時,跳轉到的新url也得傳參,注意:新url中不用指定參數類型,直接用舊的參數的類型
如:
@app.route('/index/
', redirect_to='/home/
') # 訪問index時,會直接自動跳轉到home,執行home的函數,
不執行index的
或
def func(adapter, nid):
return "/home/888"
@app.route('/index/
', redirect_to=func)
subdomain=None, 子域名訪問
from flask import Flask, views, url_for
app = Flask(import_name=__name__)
app.config['SERVER_NAME'] = 'haiyan.com:5000'
@app.route("/", subdomain="admin")
def static_index():
"""Flask supports static subdomains
This is available at static.your-domain.tld"""
return "admin.xxx.com"
#動態生成
@app.route("/dynamic", subdomain="
")
def username_index(username):
"""Dynamic subdomains are also supported
Try going to user1.your-domain.tld/dynamic"""
return username + ".your-domain.tld"
if __name__ == '__main__':
app.run()
所有的域名都得與IP做一個域名解析:
如果你想通過域名去訪問,有兩種解決方式:
方式一:
1、租一個域名 haiyan.lalala
2、租一個公網IP 49.8.5.62
3、域名解析:
haiyan.com 49.8.5.62
4、吧代碼放在49.8.5.62這個服務器上,程序運行起來
用戶可以通過IP進行訪問
方式二:如果是自己測試用的就可以用這種方式。先在自己本地的文件中找
C:\Windows\System32\drivers\etc 找到HOST,修改配置
然后吧域名修改成自己的本地服務器127.0.0.1
加上配置:app.config["SERVER_NAME"] = "haiyan.com:5000"
# =============== 子域名訪問============
@app.route("/static_index", subdomain="admin")
def static_index():
return "admin.bjg.com"
# ===========動態生成子域名===========
@app.route("/index",subdomain='
')
def index(xxxxx):
return "%s.bjg.com" %(xxxxx,)
4.自定制正則路由匹配
擴展Flask的路由系統,讓他支持正則,這個類必須這樣寫,必須去繼承BaseConverter
from flask import Flask,url_for
from werkzeug.routing import BaseConverter
'''
遇到不懂的問題?Python學習交流群:821460695滿足你的需求,資料都已經上傳群文件,可以自行下載!
'''
app = Flask(__name__)
# 定義轉換的類 class RegexConverter(BaseConverter):
"""
自定義URL匹配正則表達式
"""
def __init__(self, map, regex):
super(RegexConverter, self).__init__(map)
self.regex = regex
def to_python(self, value):
"""
路由匹配時,匹配成功后傳遞給視圖函數中參數的值
:param value:
:return:
"""
return int(value)
def to_url(self, value):
"""
使用url_for反向生成URL時,傳遞的參數經過該方法處理,返回的值用于生成URL中的參數
:param value:
:return:
"""
val = super(RegexConverter, self).to_url(value)
return val
# 添加到converts中
app.url_map.converters['regex'] = RegexConverter
# 進行使用
@app.route('/index/
',endpoint='xx')
def index(nid):
url_for('xx',nid=123)
return "Index"
if __name__ == '__main__':
app.run()
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
