Flask framework context & hook function

context

There are two contexts in the flash project, one is the application context (web), the other is the request context (request), the request context request and the application context current_app is A global variable, and all requests are shared. Flask has A special mechanism to ensure that the data of each request is isolated, that is, the data generated by A request will not affect B request, so the request object can be imported directly without being affected by some dirty data, And it is not necessary to pass in the request object when using request in each function. There is no need to understand the specific implementation methods and principles of these two contexts in detail

Request: the object on the request context, which is generally used to store some requested variables, such as method, args, form, etc

Session: the object on the request context, which is generally used to save some session information

current_app: returns the current web

g: An object on the application context that is used as temporary storage when processing requests

Context instance

After running the file, open the web address and do not immediately pass in the encrypted cookie. Therefore, when calling the view function index for the first time, the console will not output the data of username. When we change the url to / login /, the cookie named username will be loaded. Therefore, when calling the view function index for the second time, The console will output the data of username

from flask import Flask, session, current_app
# It is used to create a Flask object, request url and request session(cookie)

import os  # be used for
from datetime import timedelta  # Used to set the time

web = Flask(__name__)  # Create a flash instance

web.config['SECRET_KEY'] = os.urandom(25)  # Set the key to a randomly generated string
web.config['PERMANENT_SESSION_LIFETIME'] = timedelta(hours=24)  # session lifetime configuration


@web.route('/')
def index():
    username = session.get('username')
    print(username)  # Get the content named username in the session
    print(current_app.name)  # Output 'context'
    return 'home page'


@web.route('/login/')
def login():
    # Stored in the form of a dictionary
    session['username'] = 'cheney'
    # session persistence
    session.permanent = True  # The default time is 30 days
    return 'Login page'


if __name__ == '__main__':
    web.run(debug=True)

g object

External Python file

from flask import g


def log_a():
    print('log a %s' % g.username)

Python master file

from flask import Flask, session, current_app, g
# Used to create a Flask object, request url, request session(cookie),
from utils import log_a

import os  # be used for
from datetime import timedelta  # Used to set the time

web = Flask(__name__)  # Create a flash instance

web.config['SECRET_KEY'] = os.urandom(25)  # Set the key to a randomly generated string
web.config['PERMANENT_SESSION_LIFETIME'] = timedelta(hours=24)  # session lifetime configuration


@web.route('/')
def index():
    username = session.get('username')
    print(username)
    g.username = username
    log_a()  # Call log of external python file_ A function
    hello()  # Call the internal hello function
    return 'home page'


def hello():
    print('hello %s' % g.username)


@web.route('/login/')
def login():
    # Stored in the form of a dictionary
    session['username'] = 'cheney'
    # session persistence
    session.permanent = True  # The default time is 30 days
    return 'Login page'


if __name__ == '__main__':
    web.run(debug=True)

Hook function

When the url is /, access the index function, actively throw 404 exception, and call the hook function errorhandler to render the text (the page does not exist)

from flask import Flask, render_template, abort  # It is used to instantiate the flash instance, connect html files, and actively throw exceptions

web = Flask(__name__)  # Instantiate a Flask object


@web.route('/')
def index():
    # a = 1/0  # Return 500 exception
    abort(404)  # For actively throwing an exception 404
    print('home page')
    return render_template('index.html')  # Connect html files


# Execute before first request
@web.before_first_request
def before_first_request():
    print('The first function I access before I access the route')


# Context processor, the keys in the returned dictionary can be used in the template context
@web.context_processor
def context():
	# Return key(username):value(xiao su)
    return {'username': 'xiao su'}  

# errorhandler receives the status code. You can customize the processing method of the response that returns this status code
@web.errorhandler(404)
def errorhandler(error):  # The error parameter is required
    return 'Page does not exist'


@web.errorhandler(500)
def server_error(error):
    return 'Server internal error'


if __name__ == '__main__':
    app.run(debug=True)
    # app.run()

When the url is /, the index function is accessed because an exception is thrown except for 0 error and the debug mode needs to be turned off. At the same time, the hook function server is called_ Error, rendering text (server internal error)

from flask import Flask, render_template, abort  # It is used to instantiate the flash instance, connect html files, and actively throw exceptions

web = Flask(__name__)  # Instantiate a Flask object


@web.route('/')
def index():
    a = 1/0  # Return 500 exception
    # abort(404)  # For actively throwing an exception 404
    print('home page')
    return render_template('index.html')  # Connect html files


# Execute before first request
@web.before_first_request
def before_first_request():
    print('The first function I access before I access the route')


# Context processor, the keys in the returned dictionary can be used in the template context
@web.context_processor
def context():
    return {'username': 'xiao su'}  # Return key(username):value(xiao su)


# errorhandler receives the status code. You can customize the processing method of the response that returns this status code
@web.errorhandler(404)
def errorhandler(error):  # The error parameter is required
    return 'Page does not exist'


@web.errorhandler(500)
def server_error(error):
    return 'Server internal error'


if __name__ == '__main__':
    # app.run(debug=True)
    web.run()

Keywords: Python Java Django

Added by Swede78 on Tue, 01 Feb 2022 12:32:16 +0200