Flask的FBV路由写法与解析

路由典型写法

#flask 路由写法:基于装饰器,跟djagno有区别,本质其实是一样的,sanic,fastapi就是这种路由方式

@app.route('/index', methods=['GET'], endpoint='index')
def index():
    return 'hello'

flask路由和djagno路由的区别?

django 是放在 urls.py 文件中,flask 是基于装饰器写在被装饰函数上

 

默认转换器

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

 

路由装饰器源码分析

**如果没有写endpoint参数,就会以函数名作为别名 **

@app.route('/index/<int:pk>', methods=['get'], endpoint="index")
def index(pk):
	return pk

route(… …)=> 先执行了route函数,此时在该route函数的名称空间之中已经确定了self, rule, options

最终返回了内层函数decorator,所以装饰器变成了@decorator

route源码

def route(self, rule, **options):
    def decorator(f):
      endpoint = options.pop('endpoint', None)
      self.add_url_rule(rule, endpoint, f, **options)
      return f
  return decorator

那么原视图函数 index => index = decorator(index)

有内层函数decorator 可以知道,最主要的逻辑在于add_url_rule(rule, endpoint, f, **options)

由于decorator的返回值是传入的f,所以匹配成功之后执行的仍然是原来的视图函数,并没有修改;

总结:

# 加上装饰器最终的目的在于add_url_rule函数
所以,路由除了加装饰器的方式;还可以单独写add_url_rule;
def add_url_rule(self, rule, endpoint=None, view_func=None,provide_automatic_options=None,**options):
		... ... 
    
app.add_url_rule('index/<int:pk>', view_func=index, endpoint="index")
# 跟 Django 中的路由写法几乎一样

 

add_url_rule参数

rule ---- 请求的路径,可以使用转换器
endpoint ---- 别名==>反向解析
view_func ---- 视图函数(视图类.as_view(name="xxx"))
defaluts ---- 字典,给视图函数传递参数
methods ---- 允许的请求方式
# ---------了解
strict_slashes
redirect_to ---- 直接跳转

defaluts 等同于 django中的kwargs,media 暴露文件配置用到了

可以将其中的kv键值对传给视图函数

# defaluts={key:value}

@app.route('/index', defaluts={"name":"xxx"})
def index(name):
	return name
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值