LoginSignup
6
4

More than 1 year has passed since last update.

Aiohttpで作るSimple Web Server

Last updated at Posted at 2021-10-26

前回、Python Asyncio 入門という記事を書きました。それはAsyncioの互換ライブラリ Aiohttpのhttpクライアント機能を使ったサンプルでの説明でした。

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

AiohttpにはFlaskに似たサーバ機能もあります。Flaskは同期的プログラミングですが、Aiohttpは非同期的プログラミングで速度の点で優れています。

Asyncio公式サイト

aiohttp公式サイト

以下のサンプルはaiohttp公式サイトのものを少し修正しして、2つのroutes、2つのHandlersにしてみました。プログラムの流れは説明不要でしょう。厳密な理解をしたいときは公式サイトをご確認ください。

simple.py
from aiohttp import web

async def hello(request):
    return web.Response(text="Hello, world")

async def handle_greeting(request):
    name = request.match_info.get('name', "Anonymous")
    txt = "Hello, {}".format(name)
    return web.Response(text=txt)

app = web.Application()
app.add_routes([web.get('/', hello),
                web.get('/greet/{name}', handle_greeting)])

web.run_app(app)

以下のようにコマンドラインで起動できます。

python simple.py
======== Running on http://0.0.0.0:8080 ========
(Press CTRL+C to quit)

ブラウザから http-://localhost:8080/ でアクセスすると「Hello, world」と表示されます。
http-://localhost:8080/greet/taro でアクセスすると「Hello, taro」と表示されます。

また、Flaskのように Route decorators を使って以下のように書くこともできます。こちらの方がスッキリしているような気がします。

simple2.py
from aiohttp import web

routes = web.RouteTableDef()

@routes.get('/')
async def hello(request):
    return web.Response(text="Hello, world")

@routes.get('/greet/{name}')
async def handle_greeting(request):
    name = request.match_info.get('name', "Anonymous")
    txt = "Hello, {}".format(name)
    return web.Response(text=txt)

app = web.Application()
app.add_routes(routes)
web.run_app(app)

aiohttpのサーバ機能は今回のさわり程度で終えたいと思います。次回以降、非同期のサーバ機能についてはASGI(Starlette)を見ていきたいと思います。

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