Sanic
はじめに
[編集]Sanicは、Pythonの非同期プログラミングを活用した高速なウェブフレームワークです。このハンドブックでは、Sanicの基本的な使い方から高度な機能までを網羅し、実際のプロジェクトで活用するための知識を提供します。
Sanicの概要
[編集]Sanicとは
[編集]Sanicは、Python 3.7以降で利用可能な非同期ウェブフレームワークです。その特徴は以下の通りです:
- 非同期処理による高速なレスポンス
- シンプルで直感的なAPI
- 組み込みのHTTPサーバー
- 拡張性の高い設計
インストール
[編集]Sanicはpip
を使って簡単にインストールできます。
pip install sanic
基本的な使い方
[編集]最小限のアプリケーション
[編集]以下は、Sanicで作成した最小限のウェブアプリケーションの例です。
from sanic import Sanic from sanic.response import text app = Sanic("MyApp") @app.route("/") async def hello(request): return text("Hello, World!") if __name__ == "__main__": app.run(host="0.0.0.0", port=8000)
このコードを実行し、ブラウザでhttp://localhost:8000
にアクセスすると、「Hello, World!」というメッセージが表示されます。
ルーティング
[編集]Sanicでは、@app.route
デコレータを使ってルーティングを定義します。
@app.route("/about") async def about(request): return text("About Us")
リクエストとレスポンス
[編集]Sanicでは、リクエストオブジェクトを通じてクエリパラメータやJSONデータにアクセスできます。
@app.route("/greet") async def greet(request): name = request.args.get("name", "Guest") return text(f"Hello, {name}!")
非同期処理
[編集]非同期関数
[編集]Sanicは非同期関数をサポートしており、async
とawait
を使って非同期処理を記述できます。
import asyncio @app.route("/delay") async def delay(request): await asyncio.sleep(1) return text("Delayed response")
バックグラウンドタスク
[編集]Sanicでは、バックグラウンドで実行されるタスクを定義できます。
async def notify_server_started_after_five_seconds(): await asyncio.sleep(5) print("Server has been running for 5 seconds!") @app.listener('after_server_start') async def notify_server_started(app, loop): app.add_task(notify_server_started_after_five_seconds())
ミドルウェア
[編集]ミドルウェアとは
[編集]ミドルウェアは、リクエストとレスポンスの処理の前後に特定の処理を追加するための仕組みです。
ミドルウェアの使用例
[編集]以下は、リクエストの処理時間を計測するミドルウェアの例です。
@app.middleware('request') async def start_timer(request): request['start_time'] = time.time() @app.middleware('response') async def end_timer(request, response): total_time = time.time() - request['start_time'] print(f"Request took {total_time} seconds")
拡張機能
[編集]Blueprint
[編集]Blueprintを使うと、アプリケーションをモジュール化して管理できます。
from sanic import Blueprint from sanic.response import text bp = Blueprint("my_blueprint") @bp.route("/") async def bp_root(request): return text("Blueprint Root") app.blueprint(bp)
カスタムエラーハンドリング
[編集]Sanicでは、カスタムエラーハンドラを定義できます。
@app.exception(Exception) async def handle_exception(request, exception): return text(f"An error occurred: {str(exception)}", status=500)
データベース連携
[編集]データベース接続
[編集]Sanicでは、非同期データベースライブラリ(例: asyncpg
、aiomysql
)を使ってデータベースに接続できます。
import asyncpg async def create_db_pool(): return await asyncpg.create_pool(user='user', password='password', database='mydb', host='localhost') @app.listener('before_server_start') async def setup_db(app, loop): app.db_pool = await create_db_pool() @app.listener('after_server_stop') async def close_db(app, loop): await app.db_pool.close()
データベースクエリの実行
[編集]以下は、データベースからデータを取得する例です。
@app.route("/users") async def get_users(request): async with request.app.db_pool.acquire() as connection: users = await connection.fetch("SELECT * FROM users") return json([dict(user) for user in users])
テストとデプロイ
[編集]テスト
[編集]Sanicアプリケーションのテストは、pytest
とSanicTestClient
を使って行えます。
from sanic_testing import TestManager def test_hello(): app = Sanic("TestApp") TestManager(app) @app.route("/") async def hello(request): return text("Hello, World!") request, response = app.test_client.get("/") assert response.text == "Hello, World!"
デプロイ
[編集]Sanicアプリケーションは、GunicornやDockerを使ってデプロイできます。
gunicorn myapp:app --worker-class sanic.worker.GunicornWorker
高度なトピック
[編集]WebSocket
[編集]SanicはWebSocketをサポートしており、リアルタイム通信を実現できます。
@app.websocket('/feed') async def feed(request, ws): while True: data = await ws.recv() await ws.send(f"Received: {data}")
シグナル
[編集]Sanicのシグナル機能を使うと、アプリケーションのライフサイクルにフックを追加できます。
@app.signal('http.lifecycle.complete') async def on_complete(request, response): print("Request completed")
まとめ
[編集]このハンドブックでは、Sanicの基本的な使い方から高度な機能までを解説しました。Sanicはその高速性と柔軟性から、モダンなウェブアプリケーション開発に適したフレームワークです。是非、このハンドブックを参考にして、Sanicを使ったプロジェクトを始めてみてください。