flask框架(四)路由相关(如何添加路由,各参数介绍,源码解析)

谢阳曜
2023-12-01


 

添加路由的两种方式:
@app.route('/index')
def index():
    return "index"


def order():
    return "order"

app.add_url_rule('/order', view_func=order)

 

反向生成url

endpoint()默认是函数名

from flask import url_for
@app.route('/hdfiriowjeroijorowro', endpoint='index')

x = url_for("index")
# x = '/hdfiriowjeroijorowro'
# 用于反向生成url,当url特别长时,重定向比较方便
# 如果不起别名,就是函数名

from flask import url_for
@app.route('/hdfiriowjeroijorowro')
def test():
    return 

x = url_for("test")
# x = '/hdfiriowjeroijorowro'

 

路由转换器
@app.route('/index<int: nid>')
def index(nid):
    print(nid, nid.type())
    
    # 这儿反向生成url时需要加参数
    x = url_for('index', nid=666)
	# x = '/index666'
    
    return nid

传入的值是字符串,例如’/index11’,结果输出是11和<class ‘int’>。说明在flask内部进行了类型转换处理。常见的路由系统及其转换关系:

@app.route('/user/<username>')
@app.route('/post/<int:post_id>')
@app.route('/post/<float:post_id>')
@app.route('/post/<path:path>')
@app.route('/login', methods=['GET', 'POST'])

DEFAULT_CONVERTERS = {
    'default':          UnicodeConverter,
    'string':           UnicodeConverter,
    'any':              AnyConverter,
    'path':             PathConverter,
    'int':              IntegerConverter,
    'float':            FloatConverter,
    'uuid':             UUIDConverter,
}

 

自定义正则路由转换器
from flask import Flask, views, url_for
from werkzeug.routing import BaseConverter

app = Flask(import_name=__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

# 添加到flask中
app.url_map.converters['regex'] = RegexConverter


@app.route('/index/<regex("\d+"):nid>')
def index(nid):
    print(url_for('index', nid='888'))
    return 'Index'


if __name__ == '__main__':
    app.run()

 

其他参数
@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),
# 访问 http://www.xx.com/index/ 或 http://www.xx.com/index均可
                                           @app.route('/index',strict_slashes=True)
# 仅访问 http://www.xx.com/index 
            
redirect_to=None,           # 重定向到指定地址,如:
@app.route('/index/<int:nid>', redirect_to='/home/<nid>')
# 或
def func(adapter, nid):
	return "/home/888"
@app.route('/index/<int:nid>', redirect_to=func)
            
subdomain=None,             # 子域名访问                                              

 
子域名访问

from flask import Flask, views, url_for

app = Flask(import_name=__name__)

app.config['SERVER_NAME'] = 'wlq.com:5000'


@app.route("/", subdomain="admin")
def static_index():
    """
    Flask supports static subdomains 
    This is available at static.your-domain.tld
    """
    return "static.your-domain.tld"


@app.route("/dynamic", subdomain="<username>")
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()
 类似资料: