当前位置:网站首页>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
边栏推荐
- DevEco Device Tool 3.0 Release带来5大能力升级,让智能设备开发更高效
- MySQL存储数据加密
- Use blocconsumer to build responsive components and monitor status at the same time
- 赋能数字经济 福昕软件出席金砖国家可持续发展高层论坛
- Bookmark
- Visual task scheduling & drag and drop | scalph data integration based on Apache seatunnel
- 智洋创新与华为签署合作协议,共同推进昇腾AI产业持续发展
- 力扣_回文数
- 保证接口数据安全的10种方案
- HDU - 1078 fatmouse and cheese (memory search DP)
猜你喜欢

VS2019 C# release下断点调试

Bizchart+slider to realize grouping histogram

Xiangjiang Kunpeng joined the shengteng Wanli partnership program and continued to write a new chapter of cooperation with Huawei

【愚公系列】2022年7月 Go教学课程 003-IDE的安装和基本使用

能源势动:电力行业的碳中和该如何实现?

Huawei Nova 10 series released Huawei application market to build a solid application security firewall

close系统调用分析-性能优化

Zhiyang innovation signed a cooperation agreement with Huawei to jointly promote the sustainable development of shengteng AI industry

i.MX6ULL驱动开发 | 24 - 基于platform平台驱动模型点亮LED

PMO:比较25种分子优化方法的样本效率
随机推荐
Radio and television Wuzhou signed a cooperation agreement with Huawei to jointly promote the sustainable development of shengteng AI industry
PostgreSQL JOIN实践及原理
Nat. Commun.| 机器学习对可突变的治疗性抗体的亲和力和特异性进行共同优化
Interview question 01.08 Zero matrix
Huawei Nova 10 series released Huawei application market to build a solid application security firewall
Cadre WebGIS - kalrry
Machine learning notes mutual information
股票开户流程是什么?使用同花顺手机炒股软件安全吗?
高中物理:直线运动
淘宝商品评价api接口(item_review-获得淘宝商品评论API接口),天猫商品评论API接口
Solana链上应用Crema因黑客攻击停运
卷积神经网络模型之——LeNet网络结构与代码实现
传智教育|如何转行互联网高薪岗位之一的软件测试?(附软件测试学习路线图)
Implementation rules for archiving assessment materials of robot related courses 2022 version
php短视频源码,点赞时会有大拇指动画飘起
Force buckle_ Palindrome number
WebGIS框架---kalrry
力扣98:验证二叉搜索树
i. Mx6ull driver development | 24 - platform based driver model lights LED
[acwing] solution of the 58th weekly match