0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

#0080(2024/03/26)PythonのUvicorn

Last updated at Posted at 2025-03-26

PythonのUvicorn(ユビコーン)とは?

uvicornはPythonで書かれた高速で軽量なASGI(Asynchronous Server Gateway Interface)サーバーです。主に非同期Webアプリケーションを実行するために使用され、特にFastAPIやStarletteなどの非同期フレームワークと組み合わせて利用されます。


🔹 Uvicornの特徴

Uvicornの主な特徴は次の通りです。

  • 非同期処理:Pythonのasyncioを活用し、高速な処理が可能
  • 軽量かつ高速:オーバーヘッドが少なく、高パフォーマンス
  • 対応プロトコルの幅広さ:HTTP/1.1、HTTP/2、WebSocketに対応
  • 使いやすさ:シンプルでわかりやすいインターフェース

🔹 Uvicornのインストール方法

pipを使用して簡単にインストールできます。

pip install uvicorn

🔹 Uvicornの使い方(FastAPIとの例)

FastAPIアプリの例

# main.py
from fastapi import FastAPI

app = FastAPI()

@app.get("/")
async def read_root():
    return {"message": "Hello, World!"}

サーバー起動方法

次のコマンドを実行し、サーバーを起動します。

uvicorn main:app --reload
  • mainは作成したPythonファイル名(main.py)
  • appはFastAPIインスタンス
  • --reloadオプションは、コード変更時の自動リロードを有効化します(開発時に便利)

サーバー起動後、ブラウザでhttp://127.0.0.1:8000にアクセスすると動作確認できます。


🔹 他のWSGIサーバー(Gunicorn)との比較

項目 Uvicorn Gunicorn
プロトコル ASGI(非同期) WSGI(同期)
パフォーマンス 高速(非同期処理に適している) 安定的だが非同期処理に不向き
主な用途 FastAPI、Starletteなど非同期フレームワーク Django、Flaskなど同期フレームワーク

UvicornとGunicornの併用例

Gunicornを使用してUvicornを動作させる場合は以下のようにします。

gunicorn main:app -w 4 -k uvicorn.workers.UvicornWorker
  • -w 4:4つのワーカープロセスを作成
  • -k uvicorn.workers.UvicornWorker:GunicornのワーカーにUvicornを指定

この組み合わせで、負荷分散と高速処理を同時に実現できます。


🔹 まとめ

UvicornはPythonの非同期処理能力を活用し、高性能なWebアプリケーションを実行するためのASGIサーバーです。FastAPIやStarletteなどのフレームワークと相性が良く、リアルタイム通信(WebSocket)や高速API開発に適しています。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?