- Python Microservices Development
- Tarek Ziadé
- 330字
- 2021-07-02 18:54:21
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.
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.
- Python數(shù)據(jù)分析入門與實(shí)戰(zhàn)
- Spring技術(shù)內(nèi)幕:深入解析Spring架構(gòu)與設(shè)計
- Rust編程:入門、實(shí)戰(zhàn)與進(jìn)階
- JS全書:JavaScript Web前端開發(fā)指南
- Python算法從菜鳥到達(dá)人
- Java:High-Performance Apps with Java 9
- Citrix XenServer企業(yè)運(yùn)維實(shí)戰(zhàn)
- 實(shí)戰(zhàn)Java高并發(fā)程序設(shè)計(第2版)
- Mapping with ArcGIS Pro
- Android初級應(yīng)用開發(fā)
- Pandas入門與實(shí)戰(zhàn)應(yīng)用:基于Python的數(shù)據(jù)分析與處理
- OpenStack Sahara Essentials
- HTML5+jQuery Mobile移動應(yīng)用開發(fā)
- Swift從入門到精通 (移動開發(fā)叢書)
- Learning Redis