Flask 的路由系统 FBV 与 CBV

Flask的路由系统

本质:
           带参数的装饰器
           传递函数后 执行 add_url_rule 方法
           将 函数 和 url 封装到一个 Rule对象
           将Rule对象 添加到 app.url_map(Map对象)

注意:装饰器要放在路由的上方 -- 注意装饰器的执行顺序


1 路由格式以及参数

@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'])

本质: app.add_url_rule(rule 路由, endpoint 别名, f 视图函数, **options 参数)

常用路由系统有以上五种,所有的路由系统都是基于一下对应关系来处理:

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

app.route和app.add_url_rule参数详细:

rule,                     URL规则

view_func,                视图函数名称   #CBV 使用  view_func=IndexView.as_view(name='...')

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, 子域名访问

    公网上线时
		租域名                       aaa.com/net
		租用服务器 + 公网IP           213.213.21

		  访问 域名 -->> (域名解析)ip

	测试时 修改hosts
	  	hosts文件

	  	127.0.0.1:8000 www.aaa.com
	  	127.0.0.1:8000 www.admin.aaa.com
	  	127.0.0.1:8000 www.username.aaa.com


	使用子域名

        from flask import Flask, views, url_for
        app = Flask(import_name=__name__)

        app.config['SERVER_NAME'] = 'www.aaa.com:5000'  # 配置主域名


        @app.route("/", subdomain="admin")              # 子域名   admin.aaa.com
        def static_index():
            return "static.your-domain.tld"


        @app.route("/dynamic", subdomain="<username>")  # 传参--字符串  username.aaa.com/dynamic
        def username_index(username):
            return username + ".your-domain.tld"

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

>## 2 url_for 与 endpoint

url反向生成

无参数

	app.route('/login',method=['GET','POST'],endpoint='login')

	视图
		return redirect(url_for('login'))
	模板
		<form action='{{url_for("login")}}'></form>


有参数

	app.route('/index/<int:nid>',method=['GET','POST'],endpoint='index')

	视图
		return redirect(url_for('index',nid=111))
	模板
		<form action='{{url_for("index",nid=111)}}'></form>

>## 3 让路由支持正则
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


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


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

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

>##4 Flask 的FBV与CBV

不常使用

from flask import Flask,views,redirect,url_for  # 导入views 基础类

app = Flask(__name__)

# 定义装饰器
def auth_decorator(func):
	def inner(*args,**kwargs):
		print('装饰器')
		return func(*args,**kwargs)
	return inner


CBV 添加 装饰器 和 指定 请求方法
class IndexView(views.MethodView):
	methods = ['POST','GET']      # 指定允许的 请求方法
	decorators = [auth_decorator] # 所有方法都加上 装饰器
	def get(self):
		return redirect(url_for('home'))
	def post(self):
		return 'POST'


class HomeView(views.MethodView):
	def get(self):
		return 'Home'

app.add_url_rule('/index',view_func=IndexView.as_view(name='index'))   	
app.add_url_rule('/home',view_func=HomeView.as_view(name='home'))
	# CBV 只能通过这种方式 
	# view_func = IndexView.as_view(name='index') # 指定 反向解析的name


if __name__ == '__main__':
	app.run()
原文地址:https://www.cnblogs.com/big-handsome-guy/p/8539096.html