Sixty-nine: Use g objects flask context of thread isolated

 

G object holds the global object
g is the object that can be used in applications that run throughout the flask, and the same request and also, is the thread isolated, this object is designed to store some data the developer's own definition, convenience throughout flask procedure can be used, is generally used to bind some of the frequently used data to the above, after he took directly from the g above it, without having to pass by way of reference, so more convenient

 

def log_a(username):
print(f'log_a{username}')


def log_b(username):
print(f'log_b{username}')


def log_c(username):
print(f'log_c{username}')

from flask import Flask, request
from utils import log_a, log_b, log_c

app = Flask(__name__)


@app.route('/')
def index():
username = request.args.get('username')
log_a(username)
log_b(username)
log_c(username)
return 'hello word'


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

 

Use variable g

from flask import g


def log_a():
print(f'log_a{g.username}')


def log_b():
print(f'log_b{g.username}')


def log_c():
print(f'log_c{g.username}')

from flask import Flask, request, g  # g: global  在flask的程序中全局都可以使用
from utils import log_a, log_b, log_c

app = Flask(__name__)


@app.route('/')
def index():
username = request.args.get('username')
g.username = username
log_a()
log_b()
log_c()
return 'hello word'


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

 

Guess you like

Origin www.cnblogs.com/zhongyehai/p/11874070.html