[Linux] WSGIとASGIの違いを理解する:FlaskとFastAPIを実運用する前に

はじめに

PythonでWebアプリを作るとき、python app.py でローカル実行はできても、実運用ではそれだけでは足りません。
FlaskやFastAPIを本番で動かすには、WebサーバーとPythonアプリをつなぐ仕組みが必要になります。

そこで登場するのが WSGIASGI です。 この記事では、2つの違いや役割を入門的に解説し、サンプルコードと共に理解していきます。

WSGIとは?

WSGI (Web Server Gateway Interface) は、Python 2.x時代から存在する標準仕様で、WebサーバーとPythonアプリをつなぐためのインターフェースです。 FlaskやDjangoなど、多くの古くからあるフレームワークがWSGIに対応しています。

実運用の典型的な構成:


ブラウザ → nginx → Gunicorn → Flask/Django

最小のWSGIアプリ

def simple_app(environ, start_response):
    status = "200 OK"
    headers = [("Content-type", "text/plain; charset=utf-8")]
    start_response(status, headers)
    return [b"Hello WSGI World!"]

# gunicornから呼び出せるように
app = simple_app

実行例:

pip install gunicorn
gunicorn simple_app:app

ASGIとは?

ASGI (Asynchronous Server Gateway Interface) は、非同期処理 (async/await) に対応するために作られた新しい標準仕様です。
FastAPIやStarletteがASGIベースで動作し、WebSocketやリアルタイム通信にも対応できます。

実運用の典型的な構成:

ブラウザ → nginx → Uvicorn/Daphne → FastAPI/Starlette

最小のASGIアプリ

async def app(scope, receive, send):
    assert scope["type"] == "http"
    await send({
        "type": "http.response.start",
        "status": 200,
        "headers": [(b"content-type", b"text/plain")],
    })
    await send({
        "type": "http.response.body",
        "body": b"Hello ASGI World!",
    })

実行例:

pip install uvicorn
uvicorn app:app --reload

FlaskとFastAPIの実運用の違い

フレームワーク 対応 実行サーバー 特徴
Flask / Django WSGI Gunicorn 同期処理ベース、歴史が長く安定
FastAPI / Starlette ASGI Uvicorn / Hypercorn 非同期処理対応、リアルタイム通信可

図解イメージ:

WSGIルート:  ブラウザ → nginx → Gunicorn → Flask
ASGIルート:  ブラウザ → nginx → Uvicorn → FastAPI

運用シナリオの違い

  • Flask/Django は「従来型の同期アプリ」に強み。シンプルなAPIやWebサイトで安定運用できる。
  • FastAPI/Starlette は「非同期I/O」が得意。WebSocketやチャット、リアルタイム通知などのアプリに向く。

起動コマンドの違い

# Flask (WSGI)
gunicorn -w 4 -b 0.0.0.0:8000 app:app

# FastAPI (ASGI)
uvicorn app:app --host 0.0.0.0 --port 8000 --workers 4

実際の選び方は、**アプリの性質(同期で十分か/非同期が必要か)**と、**既存資産(Djangoを使うか、新規でFastAPIか)**で決まる。

実際に動かしてみる

Flask + Gunicorn

pip install flask gunicorn

app.py

from flask import Flask
app = Flask(__name__)

@app.route("/")
def hello():
    return "Hello Flask (WSGI)!"

実行:

gunicorn app:app

FastAPI + Uvicorn

pip install fastapi uvicorn

app.py

from fastapi import FastAPI
app = FastAPI()

@app.get("/")
async def hello():
    return {"message": "Hello FastAPI (ASGI)!"}

実行:

uvicorn app:app --reload

まとめ

  • WSGI = 同期処理が前提、FlaskやDjangoなどが利用
  • ASGI = 非同期処理対応、FastAPIやStarletteが利用
  • 実運用では nginxリバースプロキシ + (Gunicorn/Uvicorn) が基本構成
  • FlaskとFastAPIの違いは、単にフレームワークの違いだけでなく、裏で動くインターフェース仕様(WSGI/ASGI)の違いでもある