ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

Flask路由系统、模板、请求响应

2022-08-14 14:31:05  阅读:185  来源: 互联网

标签:endpoint Flask app request rule url 路由 模板 view


1 路由系统

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 本质

# 源码分析
'''
#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.4 cbv源码

'''
#0 cbv写法,继承MethodView,跟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'


'''
# 装饰器   @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)
'''


# @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'
'''
#0 cbv写法,继承MethodView,跟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']
'''


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()

2 模板

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

3 请求响应

from flask import Flask, request,make_response,render_template

app = Flask(__name__)
app.debug=True

def test():
    print(request.xxx)


@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


@app.route('/register.html', methods=['GET', "POST"])
def register():
    test()
    return "内容"

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

标签:endpoint,Flask,app,request,rule,url,路由,模板,view
来源: https://www.cnblogs.com/zhengkaijian/p/16585360.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有