当前位置:网站首页>Detailed explanation of flask context
Detailed explanation of flask context
2022-07-04 22:22:00 【Wu_ Candy】
Step1: What is context
The context is equivalent to a container , Save the Flask Some information in the process of program running .Flask There are two contexts , Request context (request and session ) And application context (current_app and g).
Step2: Context instructions
- request: Request object , Encapsulates the http What's in the request
- session: The user's session , It is used to store the information needed between requests ‘ remember ‘ Dictionary of values for
- current_app: The program instance of the currently active program
- g: Objects used as temporary storage when processing requests . Each request resets this variable
Step3: Context code example
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) # To configure 7 Days in effect
# Test request context 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}"
# Test application context current_app
@app.route("/currentapp_context")
def currentapp_context():
return "hello %s" % current_app.name
# Set up session
@app.route('/set_session')
def set_session():
session['username'] = 'steven' # Set up “ Dictionaries ” Key value pair
session['password'] = '123456'
session.permanent = True # Set up session Effective time of , Long term effectiveness , One month is valid ,
return 'login success'
# obtain session
@app.route('/get_session')
def get_session():
# The first one is session If it does not exist, an error will be reported
# session['username']
# Recommended session.get('username')
# session.get('username')
return session.get('password')
# Delete session
@app.route('/delete_session/')
def delete_session():
print(session.get('username'), session.pop('username', None))
# perhaps session['username'] = False
print(session.get('username'))
return "delete session is success"
# eliminate session All data in
@app.route('/clear_session')
def clear_session():
print(session.get('username'))
# eliminate session All data in
session.clear
print(session.get('username'))
return 'clear session is success'
# Defines a method , use g To get one name Value
def test_g():
return g.get('name',"no name")
# Test application context g
@app.route('/testG')
def test():
g.name = ' Zhang San '
test_g()
return test_g()
# Defines a submitted form
@app.route('/testRequest')
def test1():
return '<form action="/getUser" method="get"> ' \
'<input type="text" name="username" value=""> ' \
'<input type="submit" value=" Submit "> ' \
'</form>'
# Test request context 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
边栏推荐
- 复数在数论、几何中的用途 - 曹则贤
- MySQL存储数据加密
- 高中物理:直线运动
- leetcode 72. Edit Distance 编辑距离(中等)
- Xiangjiang Kunpeng joined the shengteng Wanli partnership program and continued to write a new chapter of cooperation with Huawei
- i. Mx6ull driver development | 24 - platform based driver model lights LED
- ACM Multimedia 2022 | 视觉语言预训练模型中社会偏见的反事实衡量和消除
- 不同环境相同配置项的内容如何diff差异?
- Domestic database chaos
- 《命令行上的数据科学第二版》校对活动重新启动
猜你喜欢
QT - plot other problems
智洋创新与华为签署合作协议,共同推进昇腾AI产业持续发展
卷积神经网络模型之——LeNet网络结构与代码实现
常用的开源无代码测试工具
傳智教育|如何轉行互聯網高薪崗比特之一的軟件測試?(附軟件測試學習路線圖)
Nat. Commun.| 机器学习对可突变的治疗性抗体的亲和力和特异性进行共同优化
嵌入式开发:技巧和窍门——提高嵌入式软件代码质量的7个技巧
Concurrent network modular reading notes transfer
Xiangjiang Kunpeng joined the shengteng Wanli partnership program and continued to write a new chapter of cooperation with Huawei
复数在数论、几何中的用途 - 曹则贤
随机推荐
Jvm-Sandbox-Repeater的部署
Nat. Commun.| 机器学习对可突变的治疗性抗体的亲和力和特异性进行共同优化
The proofreading activity of data science on the command line second edition was restarted
[Yugong series] go teaching course 003-ide installation and basic use in July 2022
Scala download and configuration
制作条形码的手机App推荐
力扣3_383. 赎金信
BigFilter全局交易防重组件的介绍与应用
B站大量虚拟主播被集体强制退款:收入蒸发,还倒欠B站;乔布斯被追授美国总统自由勋章;Grafana 9 发布|极客头条
Common open source codeless testing tools
阿里推出新品牌“瓴羊”,致力成为“数字化领头羊”
What is business intelligence (BI), just look at this article is enough
可视化任务编排&拖拉拽 | Scaleph 基于 Apache SeaTunnel的数据集成
Force buckle 3_ 383. Ransom letter
TCP协议三次握手过程
WebGIS框架---kalrry
HDU - 1078 fatmouse and cheese (memory search DP)
Introduction and application of bigfilter global transaction anti duplication component
Deveco device tool 3.0 release brings five capability upgrades to make intelligent device development more efficient
面试题 01.08. 零矩阵