当前位置:网站首页>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
边栏推荐
- Service online governance
- PMO:比较25种分子优化方法的样本效率
- Enabling digital economy Fuxin software attends the BRICs high level Forum on Sustainable Development
- [Yugong series] go teaching course 003-ide installation and basic use in July 2022
- 机器人相关课程考核材料归档实施细则2022版本
- 玩转gRPC—深入概念与原理
- 复数在数论、几何中的用途 - 曹则贤
- Why do you have to be familiar with industry and enterprise business when doing Bi development?
- MySQL存储数据加密
- 如何实现轻松管理1500万员工?
猜你喜欢

Introduction and application of bigfilter global transaction anti duplication component

Embedded development: skills and tricks -- seven skills to improve the quality of embedded software code

HUAWEI nova 10系列发布 华为应用市场筑牢应用安全防火墙

【C语言进阶篇】数组&&指针&&数组笔试题

KDD2022 | 什么特征进行交互才是有效的?
![[advanced C language] array & pointer & array written test questions](/img/3f/83801afba153cfc0dd73aa8187ef20.png)
[advanced C language] array & pointer & array written test questions

TCP协议三次握手过程

Domestic database chaos

赋能数字经济 福昕软件出席金砖国家可持续发展高层论坛

Nat. Commun.| 机器学习对可突变的治疗性抗体的亲和力和特异性进行共同优化
随机推荐
现在mysql cdc2.1版本在解析值为0000-00-00 00:00:00的datetime类
Common open source codeless testing tools
力扣3_383. 赎金信
Introduction and application of bigfilter global transaction anti duplication component
网上开户哪家证券公司佣金最低,我要开户,网上开户安全吗
Is it safe to open an account in the stock of Caicai college? Can you only open an account by digging money?
1807. Replace the parentheses in the string
El tree combined with El table, tree adding and modifying operations
odps 中 对表进行了一次备份,为什么在元数据库查m_table 时,两张表的逻辑大小不一致,但数
【米哈游2023届秋招】开启【校招唯一专属内推码EYTUC】
Force buckle 3_ 383. Ransom letter
电话加密,中间4为****代替
删库不必跑路!详解 MySQL 数据恢复
Implementation rules for archiving assessment materials of robot related courses 2022 version
【愚公系列】2022年7月 Go教学课程 003-IDE的安装和基本使用
Interview question 01.01 Determine whether the character is unique
ACM Multimedia 2022 | 视觉语言预训练模型中社会偏见的反事实衡量和消除
Concurrent network modular reading notes transfer
时空预测3-graph transformer
WebGIS framework -- kalrry