当前位置:网站首页>Flask 上下文详解
Flask 上下文详解
2022-07-04 21:58:00 【Wu_Candy】
Step1:什么是上下文
上下文相当于一个容器,保存了 Flask 程序运行过程中的一些信息。Flask 中有两种上下文,请求上下文(request 和 session )和应用上下文(current_app和g)。
Step2:上下文的使用说明
- request:请求对象,封装了客户端发出的http请求中的内容
- session:用户会话,用于存储请求之间需要‘记住‘的值的词典
- current_app:当前激活程序的程序实例
- g:处理请求时用作临时存储的对象。每次请求会重设这个变量
Step3:上下文代码示例
from flask import request,Flask,current_app,session,g
from datetime import timedelta
import os
app = Flask(__name__)
app.config['SECRET_KEY'] = os.urandom(24)
app.config['PERMANENT_SESSION_LIFETIME'] = timedelta(days=7) # 配置7天有效
#测试请求上下文request
@app.route('/request_context')
def request_context():
user_agent = request.headers.get("User-Agent")
# return "<p>Your browser is %s</p>" % user_agent
return f"<h1>Hello World!</h1>\nHello World!{user_agent}"
#测试应用上下文current_app
@app.route("/currentapp_context")
def currentapp_context():
return "hello %s" % current_app.name
# 设置session
@app.route('/set_session')
def set_session():
session['username'] = 'steven' # 设置“字典”键值对
session['password'] = '123456'
session.permanent = True # 设置session的有效时间,长期有效,一个月的时间有效,
return 'login success'
# 获取session
@app.route('/get_session')
def get_session():
# 第一种session获取如果不存在会报错
# session['username']
# 推荐使用session.get('username')
# session.get('username')
return session.get('password')
# 删除session
@app.route('/delete_session/')
def delete_session():
print(session.get('username'), session.pop('username', None))
# 或者 session['username'] = False
print(session.get('username'))
return "delete session is success"
#清除session中所有数据
@app.route('/clear_session')
def clear_session():
print(session.get('username'))
# 清除session中所有数据
session.clear
print(session.get('username'))
return 'clear session is success'
#定义了一个方法,用g来获取一个name的值
def test_g():
return g.get('name',"no name")
#测试应用上下文g
@app.route('/testG')
def test():
g.name = '张三'
test_g()
return test_g()
#定义了一个提交的form
@app.route('/testRequest')
def test1():
return '<form action="/getUser" method="get"> ' \
'<input type="text" name="username" value=""> ' \
'<input type="submit" value="提交"> ' \
'</form>'
#测试请求上下文request
@app.route('/getUser',methods=['GET'])
def getUser():
username=request.values.get('username')
return "my name is "+username
if __name__ == '__main__':
app.run(debug=True)
end
边栏推荐
- 使用 BlocConsumer 同时构建响应式组件和监听状态
- leetcode 72. Edit Distance 编辑距离(中等)
- Xiangjiang Kunpeng joined the shengteng Wanli partnership program and continued to write a new chapter of cooperation with Huawei
- TCP protocol three times handshake process
- WebGIS框架---kalrry
- Telephone encryption, middle 4 is replaced by * * * *
- 面试题 01.08. 零矩阵
- 抖音实战~评论数量同步更新
- 网上开户哪家证券公司佣金最低,我要开户,网上开户安全吗
- 【米哈游2023届秋招】开启【校招唯一专属内推码EYTUC】
猜你喜欢

TCP协议三次握手过程

Bookmark

Scala download and configuration

Radio and television Wuzhou signed a cooperation agreement with Huawei to jointly promote the sustainable development of shengteng AI industry

From repvgg to mobileone, including mobileone code

可视化任务编排&拖拉拽 | Scaleph 基于 Apache SeaTunnel的数据集成

QT - plot other problems

傳智教育|如何轉行互聯網高薪崗比特之一的軟件測試?(附軟件測試學習路線圖)

【C语言进阶篇】数组&&指针&&数组笔试题

The use of complex numbers in number theory and geometry - Cao Zexian
随机推荐
【米哈游2023届秋招】开启【校招唯一专属内推码EYTUC】
close系统调用分析-性能优化
Interview question 01.01 Determine whether the character is unique
文件读取写入
能源势动:电力行业的碳中和该如何实现?
短视频系统源码,点击屏幕空白处键盘不自动收起
Solve the problem of data disorder caused by slow asynchronous interface
传智教育|如何转行互联网高薪岗位之一的软件测试?(附软件测试学习路线图)
机器学习笔记 - 互信息Mutual Information
Nat. Commun.| 机器学习对可突变的治疗性抗体的亲和力和特异性进行共同优化
GTEST from ignorance to proficient use (2) what is test fixture
Open3d surface normal vector calculation
Scala download and configuration
vim 从嫌弃到依赖(23)——最后的闲扯
Which securities company has the lowest Commission for opening an account online? I want to open an account. Is it safe to open an account online
将QA引入软件开发生命周期是工程师要遵循的最佳实践
常用的开源无代码测试工具
What is the stock account opening process? Is it safe to use flush mobile stock trading software?
KDD2022 | 什么特征进行交互才是有效的?
Convolutional neural network model -- lenet network structure and code implementation