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

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.

主站蜘蛛池模板: 龙泉市| 衡阳市| 汉寿县| 佛山市| 屯门区| 凉城县| 开平市| 祁门县| 吉首市| 白银市| 安多县| 琼海市| 会东县| 太谷县| 连南| 临朐县| 伊宁市| 永春县| 潮安县| 琼中| 仙居县| 色达县| 教育| 罗源县| 新晃| 广州市| 大兴区| 老河口市| 盐津县| 牙克石市| 铁力市| 都江堰市| 柘荣县| 北海市| 当雄县| 茶陵县| 秦皇岛市| 迭部县| 天镇县| 双柏县| SHOW|