官术网_书友最值得收藏!

Globals

As discussed earlier in this chapter, Flask provides a mechanism to store global variables that are unique to a particular thread and request context. That's used for request and session, but is also available to store any custom object.

The flask.g variable contains all globals, and you can set whatever attributes you want on it.

In Flask, the @app.before_request decorator can be used to point a function that the app will call every time a request is made just before it dispatches the request to a view.

It's a typical pattern in Flask to use before_request to set values in the globals. That way, all the functions that are called within the request context can interact with g and get the data.

In the following example, we copy the username provided when the client performs an HTTP basic authentication in the user attribute:

    from flask import Flask, jsonify, g, request 

app = Flask(__name__)

@app.before_request
def authenticate():
if request.authorization:
g.user = request.authorization['username']
else:
g.user = 'Anonymous'

@app.route('/api')
def my_microservice():
return jsonify({'Hello': g.user})

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

When a client requests the /api view, the authenticate function will set g.user depending on the provided headers:

$ curl http://127.0.0.1:5000/api 
{
"Hello": "Anonymous"
}
$ curl http://127.0.0.1:5000/api --user tarek:pass
{
"Hello": "tarek"
}

Any data you may think of that's specific to a request context, and could be shared throughout your code, can be shared via flask.g.

主站蜘蛛池模板: 新宾| 东乌珠穆沁旗| 丰城市| 尼勒克县| 治多县| 麻栗坡县| 鹿邑县| 潢川县| 临沂市| 丰镇市| 荃湾区| 虞城县| 观塘区| 成安县| 思南县| 宝应县| 屏东县| 耒阳市| 青河县| 朝阳县| 佛山市| 临夏市| 抚州市| 溆浦县| 九龙县| 鄂尔多斯市| 乳源| 台州市| 准格尔旗| 牡丹江市| 潜江市| 贡觉县| 扎鲁特旗| 喀喇沁旗| 景谷| 林甸县| 修水县| 双峰县| 铜陵市| 齐河县| 蒙城县|