当前位置:网站首页>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
边栏推荐
- Kdd2022 | what features are effective for interaction?
- 从RepVgg到MobileOne,含mobileone的代码
- Force buckle 3_ 383. Ransom letter
- new IntersectionObserver 使用笔记
- 283. Moving zero-c and language assisted array method
- Energy momentum: how to achieve carbon neutralization in the power industry?
- With this PDF, we finally got offers from eight major manufacturers, including Alibaba, bytek and Baidu
- Convolutional neural network model -- lenet network structure and code implementation
- Tiktok actual combat ~ the number of comments is updated synchronously
- 力扣98:验证二叉搜索树
猜你喜欢

Cloudcompare & open3d DBSCAN clustering (non plug-in)

智洋创新与华为签署合作协议,共同推进昇腾AI产业持续发展

With this PDF, we finally got offers from eight major manufacturers, including Alibaba, bytek and Baidu

QT—双缓冲绘图

What is business intelligence (BI), just look at this article is enough

Ascendex launched Walken (WLKN) - an excellent and leading "walk to earn" game

i. Mx6ull driver development | 24 - platform based driver model lights LED

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

Machine learning notes mutual information

Sorting and sharing of selected papers, systems and applications related to the most comprehensive mixed expert (MOE) model in history
随机推荐
Scala下载和配置
关系型数据库
How can the advertising system of large factories be upgraded without the presence of large models
# 2156. Find the substring of the given hash value - post order traversal
PostgreSQLSQL高级技巧透视表
【Acwing】第58场周赛 题解
Zhiyang innovation signed a cooperation agreement with Huawei to jointly promote the sustainable development of shengteng AI industry
电话加密,中间4为****代替
Enabling digital economy Fuxin software attends the BRICs high level Forum on Sustainable Development
What is the stock account opening process? Is it safe to use flush mobile stock trading software?
VIM from dislike to dependence (23) -- the last gossip
Deveco device tool 3.0 release brings five capability upgrades to make intelligent device development more efficient
É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)
智洋创新与华为签署合作协议,共同推进昇腾AI产业持续发展
el-tree结合el-table,树形添加修改操作
Redis has three methods for checking big keys, which are necessary for optimization
TCP协议三次握手过程
Interview question 01.08 Zero matrix
Sqlserver encrypts and decrypts data
面试题 01.01. 判定字符是否唯一