一,前端访问路由配置
from flask import Flask, redirect, url_for
app = Flask( __name__)
@app. route ( "/index" )
def index ( ) :
"""定义的视图函数"""
return "hello flask"
@app. route ( "/post_only" , methods= [ "GET" , "POST" ] )
def post_only ( ) :
return "post only page"
@app. route ( "/hello" , methods= [ "POST" ] )
def hello ( ) :
return "hello 1"
@app. route ( "/hello" , methods= [ "GET" ] )
def hello2 ( ) :
return "hello 2"
@app. route ( "/hi1" )
@app. route ( "/hi2" )
def hi ( ) :
return "hi page"
@app. route ( "/login" )
def login ( ) :
url = url_for( "index" )
return redirect( url)
@app. route ( "/register" )
def register ( ) :
url = url_for( "index" )
return redirect( url)
if __name__ == '__main__' :
print ( app. url_map)
app. run( debug= True )
"""
<Rule '/register' (GET, HEAD, OPTIONS) -> register>,
<Rule '/index' (GET, HEAD, OPTIONS) -> index>,
<Rule '/hello' (POST, OPTIONS) -> hello>,
<Rule '/hello' (GET, HEAD, OPTIONS) -> hello2>,
<Rule '/login' (GET, HEAD, OPTIONS) -> login>,
<Rule '/hi2' (GET, HEAD, OPTIONS) -> hi>,
<Rule '/hi1' (GET, HEAD, OPTIONS) -> hi>,
<Rule '/static/<filename>' (GET, HEAD, OPTIONS) -> static>])
"""
二,路由转换器(路由提取器)
from flask import Flask, redirect, url_for
from werkzeug. routing import BaseConverter
app = Flask( __name__)
@app. route ( "/goods/<goods_id>" )
def goods_detail ( goods_id) :
"""定义的视图函数"""
return "goods detail page %s" % goods_id
class MobileConverter ( BaseConverter) :
def __init__ ( self, url_map) :
super ( MobileConverter, self) . __init__( url_map)
self. regex = r'1[34578]\d{9}'
class RegexConverter ( BaseConverter) :
""""""
def __init__ ( self, url_map, regex) :
super ( RegexConverter, self) . __init__( url_map)
self. regex = regex
def to_python ( self, value) :
""""""
print ( "to_python方法被调用" )
return value
def to_url ( self, value) :
"""使用url_for的方法的时候被调用"""
print ( "to_url方法被调用" )
return value
app. url_map. converters[ "re" ] = RegexConverter
app. url_map. converters[ "mobile" ] = MobileConverter
@app. route ( "/send/<re(r'1[34578]\d{9}'):mobile_num>" )
def send_sms ( mobile_num) :
return "send sms to %s" % mobile_num
@app. route ( "/index" )
def index ( ) :
url = url_for( "send_sms" , mobile_num= "18922222222" )
return redirect( url)
if __name__ == '__main__' :
print ( app. url_map)
app. run( debug= True )
三,前后端定时重定向
1.前端定时重定向
当跳转到自定义的404错误页面后,实现两秒后跳转到首页
{ % extends '母版.html' % } {
{ % block content % }
< div class = "col-10" style= "margin: auto" >
< img src= "/img/404.png" class = "img-fluid" / >
< / div>
< script>
setTimeout( function ( ) {
location. href = '/' ;
} , 2000 ) ;
< / script>
{ % endblock % }
2.后端定时重定向
当访问到某一路由时,自动重定向到首页,可以用于异常网址访问,实质还是前端重定向
@app. route ( '/error' )
def redjs ( ) :
html = '感谢访问,2秒以后将跳转到首页.'
html += "<script>"
html += "setTimeout(function() {location.href='/';}, 2000);"
html += "</script>"
return html