路由系统,请求,响应
路由系统
1.1路由经典写法
@app.route('/index',methods=['GET'],endpoint='index')
def index():
return 'hello'
'''
methods:能接受的请求方式
endpoint:路由的别名
'''
1.2默认转换器
'default': UnicodeConverter,
'string': UnicodeConverter,
'any': AnyConverter,
'path': PathConverter,
'int': IntegerConverter,
'float': FloatConverter,
'uuid': UUIDConverter,
1.3本质
# 源码分析
'''
#1 装饰器 @route python特殊语法糖,会把下面的函数当参数传入 order=route(order) 以后调用order本质就是在执行route(order)()
#2 route的内层函数---->本质是self.add_url_rule(rule, endpoint, f, **options)
def decorator(f):
endpoint = options.pop("endpoint", None)
self.add_url_rule(rule, endpoint, f, **options)
return f
#3 self是app对象,add_url_rule 其实就Flask类的add_url_rule方法
#4 所以我们可以不使用装饰器来注册路由,而自己写
app.add_url_rule('/order/<string:pk>',view_func=order)
app.add_url_rule('/index',view_func=index)
'''
1.4cbv源码
'''
#1 cbv写法,继承MethodView,跟django一样
#2 as_view中的name是别名,在fbv中,endpoint是别名,在cbv中name最终会变成endpoint
app.add_url_rule方法中:
if endpoint is None:
endpoint = _endpoint_from_view_func(view_func) # type: ignore
options["endpoint"] = endpoint
view_func就是我们传入的视图函数
#3 app.add_url_rule('/index', view_func=index),路由有个别名,如果不写endpoint,会以函数名作为endpoint
# 如果是cbv,as_view(name='home') name就是路径的别名,endpoint name是必填参数,不传入会报错
#4 cbv加装饰器 在类中写一个类属性decorators: t.List[t.Callable] = []; decorators是一个列表类型。
第一个位置的会放在最下层,多个装饰器执行顺序是从【上往下执行】
#5 cbv只允许某个请求方式或者几个请求方式 methods=['POST','GET','DELETE']
'''
1.5add_url_rule方法参数
### 参数
-rule:请求的路径,可以使用转换器
-endpoint:别名-->反向解析
-view_func:视图类.as_view(name='xx')(视图函数内存地址)
-methods:允许的请求方式
# ---------以下不重要-----
-defaults:字典,给视图函数传默认值
-strict_slashes:对URL最后的 / 符号是否严格要求
-redirect_to # 308重定向
请求
from flask import request
request.method 请求方式
request.args get请求参数
request.form post请求参数
request.values get,post提交的数据总和
request.cookie cookie
request.headers 请求头
request.path 路径
request.full_path全路径
request.url 带服务器地址的全路径
request.base_url 不带地址的全路径
request.url_root 域名+端口
request.host_url 域名+端口
request.host 不带http的域名+端口
响应
1.向浏览器中写入cookie,都可以使用make_response包裹一下变成响应对象
from flask import make_response
res = make_response(render_tamplate('home.html'))
res.set_cookie('name','春游去动物园')
return res
2.向浏览器中写响应头
from flask import make_response
res = make_response(render_tamplate('home.html'))
res.headers['USER_AGENT'] = 'values'
return res
本文作者:春游去动物园
本文链接:https://www.cnblogs.com/chunyouqudongwuyuan/p/16563528.html
版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步