当前位置:网站首页>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
边栏推荐
- 达梦数据凭什么被称为国产数据库“第一股”?
- 如何实现轻松管理1500万员工?
- 并发优化总结
- Open3d surface normal vector calculation
- 保证接口数据安全的10种方案
- Is it safe to open an account in the stock of Caicai college? Can you only open an account by digging money?
- 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
- Zhiyang innovation signed a cooperation agreement with Huawei to jointly promote the sustainable development of shengteng AI industry
- B站大量虚拟主播被集体强制退款:收入蒸发,还倒欠B站;乔布斯被追授美国总统自由勋章;Grafana 9 发布|极客头条
- # 2156. 查找给定哈希值的子串-后序遍历
猜你喜欢
随机推荐
MongoDB中的索引操作总结
B站大量虚拟主播被集体强制退款:收入蒸发,还倒欠B站;乔布斯被追授美国总统自由勋章;Grafana 9 发布|极客头条
MongoDB聚合操作总结
Use blocconsumer to build responsive components and monitor status at the same time
Redis has three methods for checking big keys, which are necessary for optimization
Locust性能测试 —— 环境搭建及使用
bizchart+slider实现分组柱状图
复数在数论、几何中的用途 - 曹则贤
从RepVgg到MobileOne,含mobileone的代码
What is the stock account opening process? Is it safe to use flush mobile stock trading software?
能源势动:电力行业的碳中和该如何实现?
Which securities company is better to open an account? Is online account opening safe
File read write
Acwing 2022 daily question
Interview question 01.01 Determine whether the character is unique
# 2156. Find the substring of the given hash value - post order traversal
可视化任务编排&拖拉拽 | Scaleph 基于 Apache SeaTunnel的数据集成
【Acwing】第58场周赛 题解
Force buckle_ Palindrome number
BigFilter全局交易防重组件的介绍与应用