- 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.
- Django+Vue.js商城項目實戰
- Java 9 Concurrency Cookbook(Second Edition)
- 深入理解Java7:核心技術與最佳實踐
- Learning R for Geospatial Analysis
- Mastering Linux Security and Hardening
- 基于SpringBoot實現:Java分布式中間件開發入門與實戰
- JavaScript腳本特效編程給力起飛
- 軟件體系結構
- 零基礎學C語言(升級版)
- CodeIgniter Web Application Blueprints
- 玩轉.NET Micro Framework移植:基于STM32F10x處理器
- Practical Maya Programming with Python
- Java程序設計教程
- 微信小程序開發邊做邊學(微課視頻版)
- 小學生C++趣味編程從入門到精通