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

Request

When a request comes in, Flask calls the view inside a thread-safe block, and uses Werzeug's local helper (http://werkzeug.pocoo.org/docs/latest/local/). This helper does a job similar to Python's threading.local (https://docs.python.org/3/library/threading.html#thread-local-data), and makes sure that each thread has an isolated environment, specific to that request.

In other words, when you access the global request object in your view, you are guaranteed that it's unique to your thread, and will not leak data to another thread in a multi-threaded environment.

As we've seen earlier, Flask uses the incoming WSGI environment data to create the request object. That object is a Request class instance, which merges several mixin classes in charge of parsing specific headers from the incoming environment.

Check out the WSGI PEP ( Python Environment Proposal) to get more details on what's in a WSGI environment at https://www.python.org/dev/peps/pep-0333/#environ-variables.

The bottom line is that a view can introspect the incoming request through the request object attributes without having to deal with some parsing. The work done by Flask is quite high level. For instance, the Authorization header is looked at and decomposed automatically when possible.

In the following example, an HTTP Basic Auth that is sent by the client is always converted to a base64 form when sent to the server. Flask will detect the Basic prefix, and will parse it into username and password fields in the request.authorization attribute:

    from flask import Flask, request 

app = Flask(__name__)

@app.route("/")
def auth():
print("The raw Authorization header")
print(request.environ["HTTP_AUTHORIZATION"])
print("Flask's Authorization header")
print(request.authorization)
return ""

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

$ curl http://localhost:5000/ -u tarek:password

$ bin/python flask_auth.py
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
The raw Authorization header
Basic dGFyZWs6cGFzc3dvcmQ=
Flask's Authorization header
{'username': 'tarek', 'password': 'password'}
127.0.0.1 - - [26/Dec/2016 11:33:04] "GET / HTTP/1.1" 200 -

This behavior makes it easy to implement a pluggable authentication system on top of the request object.

Other common request elements like cookies, files, and so on are all accessible via other attributes, as we will discover throughout the book.

主站蜘蛛池模板: 正定县| 平南县| 陵川县| 许昌县| 禹州市| 岑溪市| 杂多县| 灌阳县| 革吉县| 黄陵县| 安塞县| 奉新县| 洞头县| 永安市| 鹤庆县| 高雄市| 平利县| 兰溪市| 陆丰市| 彰武县| 会泽县| 南汇区| 乌兰县| 苗栗县| 荣成市| 金昌市| 万安县| 大方县| 滨海县| 泸西县| 鹿泉市| 商都县| 治县。| 巩留县| 土默特左旗| 嘉黎县| 仙游县| 泰和县| 明水县| 乌拉特后旗| 大冶市|