Python --- Flask - 05 - g objects and hook function

use

from flask import g

g Object

  1. g the object is designed to store user data.
  2. G object where a request for all code, can all be used.

Steps for usage:

1. Create a file utils.py, g using the test object other than the main file

from flask import g  # 引入g对象

def login_log():
    print '当前登录用户是:%s' % g.username


def login_ip():
    print '当前登录用户的IP是:%s' % g.ip

2. utils.py in function calls in the main file

from flask import Flask,g,request,render_template
from utils import login_log,login_ip

app = Flask(__name__)

@app.route('/')
def hello_world():
    return 'Hello World!'


@app.route('/login/',methods=['GET', 'POST'])
def login():
    if request.method == 'GET':
        return render_template('login.html')
    else:
        username = request.form.get('username')
        password = request.form.get('password')

     # 使用g对象
        g.username = username
        g.ip = password
        login_log()
        login_ip()
        return '恭喜登录成功!'

if __name__ == '__main__':
    app.run()

Hook function

Hook understanding:

When the program is running, the program in accordance with the function A -> B functions sequentially operating sequence; hooking function may be inserted into the function A to the function so that the intermediate B runs, runs into a sequence A -> hook function -> B function.

Flask item has two contexts, a context is the application (App), it is a further context request (request). Request context, and application context current_app request is a global variable. All requests are shared. Flask special mechanism to ensure that each is isolated requested data, i.e., data request A to B will not affect the generated request. Can be introduced directly request object, will not be affected some dirty data, and does not require the use of an incoming request when the request object in each function. Both context specific implementation methods and principles may not need to learn more about. If we can understand the context of these four properties will be able to:

(1) request: Context Request object. This object is generally used to store some variables request. For example, method, args, form and so on.

(2) session: the requested object on the context. The objects are generally used to save some of session information.

(3) current_app: Returns the current app.

(4) g: object on the application context. As a temporary storage of objects while processing the request.

Common hook function

  • before_first_request: processing performed prior to the first request.
@app.before_first_request
def first_request():
    print 'first time request'
  • before_request: before each execution request. You can usually increase the number of variables to the view function with the decorator.
@app.before_request
def before_request():
    if not hasattr(g,'user'):
        setattr(g,'user','xxxx')
  • teardown_appcontext: Regardless of whether there is an exception, registration function will be executed after each request.
@app.teardown_appcontext
def teardown(exc=None):
    if exc is None:
        db.session.commit()
    else:
        db.session.rollback()
        db.session.remove()

Guess you like

Origin www.cnblogs.com/sunshenggang/p/11071806.html