flask---路由系统,模板和请求响应

路由系统


1.1 路由典型写法

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

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

1.2 默认转换器

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

1.3 本质

# 装饰器
@route  python特殊语法糖,会把下面的函数当参数传入order=route(order)  以后调用order本质就是在执行route(order)()
# 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
# self是app对象
add_url_rule 其实就Flask类的add_url_rule方法
# 不用装饰器写路由
app.add_url_rule('/order/<string:pk>',view_func=order)
app.add_url_rule('/index',view_func=index)

1.4 cbv源码

#0 cbv写法,继承Met
hodView,跟djagno很像

#1  as_view的name是别名,之前写fbv的时候,endpoint是别名,现在写cbv,name它最终就是endpoint,但是必须写,即便写了endpoint
    -Home.as_view是view函数的内存地址,请求来了执行  self.dispatch_request(),MethodView重写了dispatch_request--》根据请求方式执行视图类中跟请求方式同名的方法
    -如果视图类继承了View,需要重写dispatch_request
    
    
#2  app.add_url_rule('/index', view_func=index),路由有个别名,如果不写endpoint,会以函数名作为endpoint
# 如果是cbv,as_view(name='home') name就是路径的别名,endpoint

#3 cbv加装饰器, 在类中写 decorators = (装饰器名字,装饰器名字2,),第一个位置的会放在最下层,多个装饰器执行顺序是从【上往下执行】

#4 cbv只允许某个请求方式   methods=['POST']

1.5 add_url_rule参数

-rule:请求的路径,可以使用转换器
-endpoint:别名--》反向解析
-view_func:视图类.as_view(name='xx')(视图函数内存地址)
-methods:允许的请求方式
# ---------以下不重要-----
-defaults:字典,给视图函数传默认值
-strict_slashes:对URL最后的 / 符号是否严格要求
-redirect_to

案例

from flask import Flask

app = Flask(__name__)
app.debug = True


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




# @app.route('/order/<string:pk>', methods=['GET'], endpoint='order')
def order(pk):
    print(pk)
    return 'order'


# 注册路由的另一种写法,本质跟django的是一样的
app.add_url_rule('/order/<string:pk>', view_func=order)
app.add_url_rule('/index', view_func=index,)

# 如何写基于类的视图 cbv
from flask.views import MethodView


# @装饰器1
# @装饰器2
# def index()

class Home(MethodView):
    methods=['POST']
    # decorators = (装饰器名字,装饰器名字2,)
    def get(self):
        return 'home'

    def post(self):
        return 'home-post'



app.add_url_rule('/home', view_func=Home.as_view(name='home'))



@app.route('/goods',defaults={'name':'lqz'},redirect_to='/home')
def goods(name):
    print(name)
    return 'goods'
if __name__ == '__main__':
    app.run()

模板


模板语法

-django 是自己的模板语法,dtl
-flask使用第三方,兼容dtl,但是它可以加括号,可以使用[],处理了xss攻击
    	-xss,csrf,cors分别是什么?
    	-django,flask处理了xss攻击,不存在这个攻击,原理是什么?
        	-使用了html的特殊字符替换,但是如果使用了 |safe 或者Markup ,就不会渲染到页面上

请求响应


请求

@app.route('/login.html', methods=['GET', "POST"])
def login():
    ####请求对象的属性和方法
    # request:是全局的request,用起来就当是每个请求都有一个request即可
    print(request.method) # 请求方式
    print(request.args) # get 请求参数
    print(request.form) # post提交的数据
    print(request.values)  # get,post提交的数据总和

    print(request.cookies)  # cookies
    print(request.headers)  # 请求头
    print(request.path)  # 路径
    print(request.full_path)  # 全路径
    print('-----',request.script_root)
    # request.url           带域名带参数的请求路径
    print(request.url)      # 带服务器地址的全路径
    # request.base_url		带域名请求路径
    print(request.base_url)  # 不带地址的全路径
    # request.url_root      域名
    print(request.url_root)   # 域名+端口
    # request.host_url		域名
    print(request.host_url)  # 域名+端口
    # request.host
    print(request.host)    # 不带http的域名+端口
    from werkzeug.datastructures import FileStorage
    print(type(request.files.get('files')))

响应

#1  向浏览器中写入cookie,四件套都可以使用make_response包裹一下变成响应对象
res=make_response(render_template('home.html'))
res.set_cookie('name','lqz')
# delete_cookie

## 2 向浏览器中写响应头
# res.headers['X-Something'] = 'A value'


return res
posted @ 2022-08-08 22:09  早安_1207  阅读(70)  评论(0)    收藏  举报
返回顶端