LoginSignup
3
4

More than 1 year has passed since last update.

Starletteで作る Simple Web Server

Last updated at Posted at 2021-10-27

Starlette は軽量なASGI framework/toolkit です。それによって高速なasyncio servicesを構築することが可能になります。

Starlette 公式サイト

【過去記事】
Python Asyncio入門
Aiohttpで作るSimple Web Server - Qiita
Starletteで作る Simple Web Server - QIita

pip install starlette

Web Applicationはstarlette が分担しますが、ここでASGI serverもインストールします。uvicorn, daphne, や hypercornなどがありますが、uvicornがポピュラーなようです。

pip install uvicorn

公式サイトからのコピペです。

example.py
from starlette.applications import Starlette
from starlette.responses import JSONResponse
from starlette.routing import Route


async def homepage(request):
    return JSONResponse({'hello': 'world'})


app = Starlette(debug=True, routes=[
    Route('/', homepage),
])

以下のように起動します。

$ uvicorn example:app

starletteは以下のような特徴を持つフレームワークです。

  • Seriously impressive performance.
  • WebSocket support.
  • In-process background tasks.
  • Startup and shutdown events.
  • Test client built on requests.
  • CORS, GZip, Static Files, Streaming responses.
  • Session and Cookie support.
  • 100% test coverage.
  • 100% type annotated codebase.
  • Few hard dependencies.

このままstarletteの特徴を負うのも良いのですが、最近はstarlette上に構築された FastAPI を使うのが流行りのようです。次回はFastAPIを見ていきたいと思います。

3
4
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
3
4