首页 > 其他分享 >flask框架02 cbv分析 模板 请求与响应 session 闪现 请求拓展

flask框架02 cbv分析 模板 请求与响应 session 闪现 请求拓展

时间:2023-04-04 20:33:23浏览次数:33  
标签:02 __ 请求 flask app request session print name

今日内容详细

目录

1 cbv分析

# 基于类的视图,写法

from flask import Flask,request
from flask.views import View, MethodView

app = Flask(__name__)

app.debug = True


# 视图类,继承MethodView,类中写跟请求方式同名的方法即可,之前学的所有都一致
class IndexView(MethodView):
    def get(self):
        print(request.method)
        return 'get 请求'

    def post(self):
        print(request.method)
        return 'post 请求'


app.add_url_rule('/index', endpoint='index', view_func=IndexView.as_view('index'))
if __name__ == '__main__':
    app.run()

1.1 源码分析

# 1 IndexView.as_view('index') 执行完的结果,是个函数(view的)内存地址
    def as_view(cls, name, *class_args, **class_kwargs):
        def view(**kwargs: t.Any) -> ft.ResponseReturnValue:
            # 本质是在执行self.dispatch_request,只是用了异步
           return current_app.ensure_sync(self.dispatch_request)(**kwargs)
        return view
    
    
# 2 请求来了,执行view()--->本质在执行self.dispatch_request---》MethodView中的
    def dispatch_request(self, **kwargs):
        # self是视图类的对象
        meth = getattr(self, request.method.lower(), None)
        # 用异步执行meth()
        return current_app.ensure_sync(meth)(**kwargs)
    
    
# 3 总结:执行原理跟django一样


# 4 路径如果不传别名,别名就是函数名---》分析一下源码
	[email protected]('/index')--》没有传endpoint
    -endpoint 就是None---》调用了app.add_url_rule,传入了None
    if endpoint is None:
       endpoint = _endpoint_from_view_func(view_func)  # type: ignore
	-_endpoint_from_view_func 就是返回函数的名字
# 5 as_view('index') 必须传参数,传进来的参数是,是【别名】
	# view是as_view内的内层函数,闭包函数
	view.__name__ = name  # 修改了函数的名字变成了你传入的
    
    # app.add_url_rule('/index',view_func=IndexView.as_view('index'))
    简写成:app.add_url_rule('/index',view_func=view)
    #如果不传参数, 所有人的别名(endpoint),都是内层函数view,所以就报错了
    
    
   

#6 补充:flask的路由注册使用装饰器,如果写了一个登录认证装饰器,那么应该放在路由装饰器上还是下?
	-放在路由下面
    -路由必须传endpoint,如果不传,又报错

    
    
#7  视图类必须继承MethodView,如果继承View,它的dispatch_request没有具体实现,你的视图类必须重写dispatch_request,我们不想重写,继承MethodView
    def dispatch_request(self) -> ft.ResponseReturnValue:
        raise NotImplementedError()
    
    
# 8 视图类加装饰器,直接配置在类属性上【decorators】即可
	decorators = [auth,]
    # 源码,cls是视图类,中有decorators
    if cls.decorators:
      for decorator in cls.decorators:
          view = decorator(view)  # view=auth(view)

# 源码学到的
	-1 as_view 执行流程跟djagno一样
	-2 路径如果不传别名,别名就是函数名(endpoint)
	-3 视图函数加多个装饰器(上下顺序和必须传endpoint)
	-4 视图类必须继承MethodView,否则需要重写dispatch_request
	-5 视图类加装饰器:类属性decorators = [auth,]

2 模板

2.1 py文件

from flask import Flask, render_template,Markup

app = Flask(__name__, template_folder='templates', static_folder='static')  # 模板的路径必须是templates,因为实例化app对象时,传入的
app.debug=True


def add(a,b):
    return a+b
@app.route('/')
def index():
    a='<a href="http://www.baidu.com">点我看美女</a>'  # 不存在xss攻击,处理了xss
    a=Markup(a)
    return render_template('index.html',name='lqz',a=a,add=add)


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

2.2 html页面

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1>模板语法,static</h1>
<img src="/static/1.jpg" alt="">

<h1>模板语法,if</h1>
{% if name %}
<h1>Hello {{ name }}!</h1>
{% else %}
<h1>Hello World!</h1>
{% endif %}

<h1>模板语法,标签渲染</h1>
{{a|safe}}
{{a}}

<h1>模板语法,执行函数</h1>
{{add(4,5)}}

</body>
</html>

3 请求与响应

# 请求:全局的request对象

# 响应:四件套
	render_template		# 返回模板
	redirect       		# 重定向
	jsonify        		# 返回json格式数据
	''            		# 返回字符串类型
from flask import Flask, request, make_response,render_template

app = Flask(__name__)
app.debug = True


@app.route('/', methods=['GET', 'POST'])
def index():
    #### 请求
    # request.method  提交的方法
    # request.args  get请求提及的数据
    # request.form   post请求提交的数据
    # request.values  post和get提交的数据总和
    # request.cookies  客户端所带的cookie
    # request.headers  请求头
    # request.path     不带域名,请求路径
    # request.full_path  不带域名,带参数的请求路径
    # request.script_root
    # request.url           带域名带参数的请求路径
    # request.base_url    带域名请求路径
    # request.url_root      域名
    # request.host_url    域名
    # request.host       127.0.0.1:500
    print(request.method)
    print(request.args)
    print(request.form)
    print(request.values)
    print(request.cookies)
    print(request.headers)
    print(request.path)
    print(request.full_path)
    print(request.url)
    print(request.base_url)
    print(request.host_url)
    print(request.host)

    obj = request.files['file']
    obj.save(obj.filename)

    ### 响应  四件套
    # 1 响应中写入cookie
    # response = 'hello'
    # res = make_response(response)  # flask.wrappers.Response
    # print(type(res))
    # res.set_cookie('xx','xx')
    # return res
    # 2 响应头中写数据(新手四件套,都用make_response包一下)
    response = render_template('index.html')
    res = make_response(response)  # flask.wrappers.Response
    print(type(res))
    res.headers['yy']='yy'
    return res

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

4 session及源码分析

4.1 session的使用

from flask import Flask, request, session, render_template, redirect

app = Flask(__name__)
app.debug = True
app.secret_key = 'asdfas33asdfasf'


@app.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'GET':
        return render_template('login.html')
    else:
        name = request.form.get('name')
        password = request.form.get('password')
        print(password)
        session['name'] = name
        return redirect('/index')


@app.route('/index', methods=['GET', 'POST'])
def index():
    return 'hello %s' % session.get('name', '匿名用户')

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

4.2 源码分析

# cookie :存在于客户端浏览器的键值对
# session:存在于服务端的键值对    # djagno 放在了django_session表中

# flask中,叫session,问题来了,存哪里了?
	-加密后,放到了cookie中,如果session发生了变化,我们的cookie也会跟着变
    

    
# 源码部分:
	# 1 app.session_interface  配置了一个类的对象,这个就是session的执行流程
    # 2 类中有两个非常重要的方法,请求来了,会执行open_session,请求走了会执行save_session
      def open_session(self, app, request) :
		#1 根据名字,取出前端传入的cookie的value值
        val = request.cookies.get(self.get_cookie_name(app))
        #2 如果没有val,构造了一个空session对象
        if not val:
            return self.session_class()
        max_age = int(app.permanent_session_lifetime.total_seconds())
        try:
            # 如果没有过期,解码,做成session对象,后续直接用session即可
            data = s.loads(val, max_age=max_age)
            return self.session_class(data)
        except BadSignature:
            # 如果过期了,也是空session
            return self.session_class()
        
        


    def save_session(self, app, session, response) :
        name = self.get_cookie_name(app)
		# 取出过期事件,和把session加密转成字符串,放到cookie中
        expires = self.get_expiration_time(app, session)
        val = self.get_signing_serializer(app).dumps(dict(session))
        response.set_cookie(
            name,
            val, 
            expires=expires,
        )

  # 扩展,想把session放到redis中,mysql中,已经有人帮咱们写了,第三方的
	只需要写个类,重写open_session,save_session自己写

5 闪现

# flash 翻译过来的
	- 当次请求先把一些数据,放在某个位置
    - 下一次请求,把这些数据取出来,取完,就没了
    
# 作用:
	1 可以跨请求,来保存数据
    2 当次请求,访问出错,被重定向到其他地址,重定向到这个地址后,拿到当时的错误
    
    
# djagno中有这个东西吗?
	-message框架
# 用法:
	-设置 闪现  
    	-flash('%s,我错了'%name) ,可以设置多次,放到列表中
        -flash('超时错误',category="debug") 分类存 
    -获取 闪现
    	-get_flashed_messages() ,取完就删除
        -get_flashed_messages(category_filter=['debug'])分类取
        
        
        
 # 本质,放到session中

6 请求拓展

# 请求扩展中:在请求来了,或请求走了,可以绑定一些函数,到这里就会执行这个函数,类似于django的中间件
# 在flask中就用请求扩展,来代替djagno的中间件

# 好几个请求扩展
	-before_request:请求来了会走,如果他返回了四件套,就结束了
    -after_request :请求走了会走,一定要返回response对象
    -before_first_request:第一次来了会走
    -teardown_request:无论是否出异常,会走
    -errorhandler:监听状态码,404  500
    -template_global:标签
    -template_filter:过滤器
from flask import Flask, request,render_template

app = Flask(__name__)


####1 before_request 和 after_request
# 请求来了,执行一个函数,来的时候从上往下执行
# @app.before_request
# def before():
#     print('我来了111')
#     # if 'index' in request.path:
#     return '不让看了'  # 如果不是retrun了None,说明被拦截了,直接返回
#
#
# @app.before_request
# def before1():
#     print('我来了222')
#
#
# # 请求走了,执行一个函数,走的时候,从下往上执行
# @app.after_request
# def after(response):
#     print('我走了111')
#     return response
#
#
# @app.after_request
# def after2(response):
#     print('我走了222')
#     return response


# 2 项目启动后的第一个请求
# @app.before_first_request
# def first():
#     print('我的第一次')


# 3 teardown_request,无论视图函数是否出错,都会执行它,做错误日志
# @app.teardown_request
# def teardown(e):
#     print(e)
#     print('执行我了')



# 4 errorhandler  监听响应状态码,如果符合监听的状态码,就会走它
# @app.errorhandler(404)
# def error_404(arg):
#     return "404错误了"

# @app.errorhandler(500)
# def error_500(arg):
#     return "500错误了"


##5 template_global  在模板中直接使用该过滤器
@app.template_global()
def add(a1, a2):
    return a1 + a2

# 6 template_filter
@app.template_filter()
def db(a1, a2, a3):
    return a1 + a2 + a3


@app.route('/')
def index():
    # a = [1, 2, 3]
    # print(a[9])
    return render_template('index1.html')


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

标签:02,__,请求,flask,app,request,session,print,name
From: https://www.cnblogs.com/qian-yf/p/17287823.html

相关文章

  • 美团面试题目以及解答20200424
    一面:集合有哪些:List(ArrayList Linklist)set(SetTreesetHashset)map(HashmapcurrentHashmaphashtable)arraylist和linkedlist区别一个是基于数组的实现一个是基于的链表的实现hashmap怎么扩容(多线程扩容为什么会死循环),put过程出现的是链表的闭环。concurrentHashMap1.7和1.......
  • 基础_002_常量
    一、数值常量1、常见数值常量   65535、37         //十进制整型,默认   012、-023         //八进制整型,0开头,每一位只能0~7   0x3a、0X22F       //十六进制整型,0x或0X开头,每一位只能0~9或A~F   123u、46U         //无符号整......
  • cbv分析、模板、请求与响应、session及源码分析、闪现、请求扩展
    cbv分析#基于类的视图,写法fromflaskimportFlask,requestfromflask.viewsimportView,MethodViewapp=Flask(__name__)app.debug=True#视图类,继承MethodView,类中写跟请求方式同名的方法即可,之前学的所有都一致classIndexView(MethodView):defget(s......
  • flask,蓝图使用,g对象,数据库连接池
    内容回顾cbv使用写一个类继承MethodView写get,post…类属性decorators=[auth]可以加装饰器CBV执行流程跟django的执行流程一样endpoint作用路径别名add_url_rule(view_func=IndexView.as_view(‘index’))为什么endpoint不传,是被路由装饰器装饰的函数名:函数名._name_装饰......
  • flask3
    今日内容1蓝图的使用#blueprint翻译过来的,称之为蓝图#作用是:之前全在一个py中写flask项目,后期肯定要划分目录#不用蓝图,划分目录 no_blueprint_flask#项目名src#核心源码位置__init__.py#包里面实例化得到了app对象,......
  • 2023GPLT选拔题解
    看到没有题解我就给大家浅浅的写一篇吧,如果有错误,希望大家可以帮我指出来哦,创作不易,如果大家给个关注,点个赞就更好了  1:著名开源操作系统Linux的核心创始人Linus有一句经典名言:”Talkischeap.Showmethecode.“ 说出这句话时是2000年8月25日,那天有人在Linus的Linu......
  • flask-蓝图、g对象
    1.蓝图的使用蓝图是由blueprint翻译过来的,作用是之前在一个py文件中写的flask项目,后期划分目录,不用蓝图同样可以划分项目1.1不用蓝图划分项目不使用蓝图划分也可以完成项目需求,但是随着项目深入导入情况越来越多可能会出现导入错误1.项目目录结构:根目录:srcinit.pymodels.......
  • Flask框架使用蓝图划分目录、g对象、使用数据库连接池链接数据库
    目录一、使用蓝图划分项目目录1.蓝图的介绍2.蓝图的使用二、介绍flask框架的g对象1.g对象是什么?2.使用代码再次解释g对象三、使用数据库连接池链接数据库1.引入数据库连接池的概念2.在flask框架中使用数据库连接池的步骤一、使用蓝图划分项目目录1.蓝图的介绍flask框架的目......
  • 【游记】SDOI2023 游记
    3.25-3.26来到南京啦,跟着号爸度过这最后的一个星期,刚来的第一天,天上就下冰雹,震惊。但是这两天莫名其妙跟了两天普及组,甚至让我对号爸的实力产生了怀疑。3.27巨佬\(3h\)切掉APIOT3和USACO铂金组T3,只能膜膜膜。晚上我爸竟然抓到了一位NOIP2022SDrk10-的大佬,和大佬......
  • 2023年4月4日
    打起精神,斗志昂扬计划做PPT理清项目背景,需求,功能,整理到ppt上不研究新东西,管理员端,重点看项目结构,看懂某一个功能如何实现,例如新增接口执行09点35分  读书《Spring+SpringMVC+MyBatis从零开始学》先11点06分  CRM视频记录已解决解决找回密码界面等的邮件发送......