当前位置:网站首页>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

原网站

版权声明
本文为[Wu_ Candy]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/185/202207042157284998.html