当前位置:网站首页>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
边栏推荐
- 面试题 01.08. 零矩阵
- 使用 BlocConsumer 同时构建响应式组件和监听状态
- 文件读取写入
- Bookmark
- Éducation à la transmission du savoir | Comment passer à un test logiciel pour l'un des postes les mieux rémunérés sur Internet? (joindre la Feuille de route pour l'apprentissage des tests logiciels)
- HDU - 2859 Phalanx(DP)
- # 2156. Find the substring of the given hash value - post order traversal
- Force buckle 3_ 383. Ransom letter
- Huawei Nova 10 series released Huawei application market to build a solid application security firewall
- [optimtool.unconstrained] unconstrained optimization toolbox
猜你喜欢
Sorting and sharing of selected papers, systems and applications related to the most comprehensive mixed expert (MOE) model in history
能源势动:电力行业的碳中和该如何实现?
A large number of virtual anchors in station B were collectively forced to refund: revenue evaporated, but they still owe station B; Jobs was posthumously awarded the U.S. presidential medal of freedo
湘江鲲鹏加入昇腾万里伙伴计划,与华为续写合作新篇章
Bizchart+slider to realize grouping histogram
Bookmark
抖音实战~评论数量同步更新
国产数据库乱象
传智教育|如何转行互联网高薪岗位之一的软件测试?(附软件测试学习路线图)
QT - double buffer plot
随机推荐
Xiangjiang Kunpeng joined the shengteng Wanli partnership program and continued to write a new chapter of cooperation with Huawei
可视化任务编排&拖拉拽 | Scaleph 基于 Apache SeaTunnel的数据集成
大厂的广告系统升级,怎能少了大模型的身影
凭借了这份 pdf,最终拿到了阿里,字节,百度等八家大厂 offer
什么是商业智能(BI),就看这篇文章足够了
迷失在Mysql的锁世界
能源势动:电力行业的碳中和该如何实现?
HDU - 1078 fatmouse and cheese (memory search DP)
What is business intelligence (BI), just look at this article is enough
el-tree结合el-table,树形添加修改操作
From repvgg to mobileone, including mobileone code
PMO:比较25种分子优化方法的样本效率
# 2156. 查找给定哈希值的子串-后序遍历
Sqlserver encrypts and decrypts data
close系统调用分析-性能优化
力扣_回文数
Nat. Commun.| Machine learning jointly optimizes the affinity and specificity of mutagenic therapeutic antibodies
i.MX6ULL驱动开发 | 24 - 基于platform平台驱动模型点亮LED
AscendEX 上线 Walken (WLKN) - 一款卓越领先的“Walk-to-Earn”游戏
GTEST from ignorance to skillful use (1) GTEST installation