π Flask (WSGI-based Framework)
π¦ Components:
-
Web Server: Gunicorn
-
Interface Protocol: WSGI (Web Server Gateway Interface)
-
API Code: Synchronous (Blocking I/O)
π Flow:
-
Client request hits the Gunicorn web server.
- Gunicorn forwards the request via WSGI (uses Werkzeug internally).
- The request reaches the Flask API code, where the endpoint is defined using
@app.route(...)
.
- The function executes synchronously, blocking the thread until the task completes.
- Response is returned via jsonify(result).
π Code Example:
@app.route("/predict", methods=["POST"])
def predict():
json_data = request.get_json()
data = InputData(**json_data)
result = predict_sync(data)
return jsonify(result)
β οΈ Limitations:
- Not suitable for async tasks (e.g., I/O-bound operations).
- Can be less performant under high concurrency.
β‘ FastAPI (ASGI-based Framework)
π¦ Components:
-
Web Server: Any ASGI server (e.g., Uvicorn)
-
Interface Protocol: ASGI (Asynchronous Server Gateway Interface)
-
API Code: Asynchronous (Non-blocking I/O)
π Flow:
-
Client request hits the ASGI-compatible web server.
- The request is passed through the ASGI interface.
- The FastAPI app handles it with
@app.post(...)
.
- The function runs asynchronously, allowing concurrent processing.
- The response is returned directly.
π Code Example:
@app.post("/predict")
async def predict(data: InputData):
result = await predict_async(data)
return result
β
Advantages:
- Built-in support for async/await.
- Higher performance for I/O-bound tasks.
- Better suited for modern web applications and microservices.
π Summary Table:
Feature |
Flask |
FastAPI |
Protocol |
WSGI |
ASGI |
Web Server |
Gunicorn |
Uvicorn/Hypercorn/etc. |
Concurrency Model |
Synchronous (Blocking) |
Asynchronous (Non-blocking) |
Async Support |
β Not native |
β
Fully supported |
Performance |
Medium |
High |
Use Case |
Simple APIs, Synchronous |
High-concurrency, Async |
Top comments (0)