The most commonly used web frameworks for building REST APIs with python is Flask and Django. Though we could build APIs with django, the real purpose of Django is building an end to end web application. On the other hand, flask is pretty light weight and can help us quickly build REST APIs. Before jumping into fastapi
let’s quickly revisit a basic flask application.
使用python构建REST API的最常用Web框架是Flask和Django。 尽管我们可以使用django构建API,但是Django的真正目的是构建端到端的Web应用程序。 另一方面,flask重量很轻,可以帮助我们快速构建REST API。 在进入fastapi
之前,让我们快速回顾一下基本的flask应用程序。
from flask import Flask, jsonify
app = Flask(__name__)
@app.route("/", methods = ["GET"])
def index():
return jsonify({"appname" :"firstapp"}),200
if __name__ == "__main__":
app.run(debug=True)
Running the above code should give the following logs and output
运行上面的代码应提供以下日志和输出
* Serving Flask app "myflaskapi" (lazy loading)
* Environment: production
WARNING: This is a development server. Do not use it in a production deployment.
Use a production WSGI server instead.
* Debug mode: on
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
* Restarting with stat
* Debugger is active!
* Debugger PIN: 207-495-435
127.0.0.1 - - [25/Sep/2020 12:35:03] "GET / HTTP/1.1" 200 -Output:
{
"appname": "firstapp"
}
The fundamental problem of flask is it is based on WSGI server which is synchronous. This means that these cannot perform any non blocking asynchronous operations. For instance , consider the example below.
flask的根本问题是它基于同步的WSGI服务器。 这意味着它们不能执行任何非阻塞异步操作。 例如,请考虑以下示例。
@app.route("/", methods=["GET"])
def index():
response = requests.get(url="https://google.com")
print(response.content)
return jsonify({"content" : str(response.content)}), 200
In the above code, the response is returned only after the execution of requests.get
method. Until then, the API
is blocked and unavailable to handle further requests.
在上面的代码中,仅在执行requests.get
方法之后返回响应。 在此之前,该API
被阻止并且无法处理其他请求。
This use case is still valid with a WSGI server like gunicorn handling the requests with worker threads. Ofcourse one would argue that this could still be made asynchronous using Klein
or other libraries. But that still adds further overhead.
这种用例对于像gunicorn这样的WSGI服务器仍然有效,该服务器使用工作线程处理请求。 当然有人会说,仍然可以使用Klein
或其他库将其异步化。 但这仍然增加了额外的开销。
We also cannot use the asyncio
library with flask
apis as asyncio expects a coroutine
and flask is incompatible with a coroutine.
我们也不能将asyncio
库与flask
api一起使用,因为asyncio期望coroutine
并且flask与协程不兼容。
To get around this, we have fastapi
which is based on asyncio.
为了解决这个问题,我