PythonライブラリノックDay106 外部ライブラリ #プログラミング #python #library

テクノロジー



Pythonのライブラリの紹介です。それぞれの説明と使用例は以下になります。

L 316. websockets(WebSocket)
websockets は、WebSocketプロトコル(双方向通信)を扱うための、非同期対応のライブラリです。asyncioと組み合わせて、リアルタイムなチャットアプリや通知システムのような非同期通信を簡単に構築できます。

▼主な機能
WebSocketサーバー/クライアント両方に対応
asyncioベースの非同期通信
RFC 6455準拠(WebSocketの仕様)

▼使い方(例)
# WebSocketサーバー
import asyncio
import websockets

async def echo(websocket, path):
async for message in websocket:
await websocket.send(f”Echo: {message}”)

start_server = websockets.serve(echo, “localhost”, 8765)

asyncio.run(start_server)

# WebSocketクライアント
import asyncio
import websockets

async def hello():
uri = “ws://localhost:8765”
async with websockets.connect(uri) as websocket:
await websocket.send(“Hello!”)
response = await websocket.recv()
print(f”Received: {response}”)

asyncio.run(hello())

L 317. starlette(Webフレームワーク)
starlette は、ASGI(非同期Webサーバーの仕様)に準拠した、軽量かつ高速なWebフレームワークです。FastAPIはこのstarletteの上に構築されています。

▼主な機能
高速な非同期ルーティング
WebSocketサポート
Middleware(ミドルウェア)機構
Background tasks(バックグラウンド処理)
テスト機能付き

▼使い方(例)
from starlette.applications import Starlette
from starlette.responses import JSONResponse
from starlette.routing import Route

async def homepage(request):
return JSONResponse({“message”: “Hello, Starlette!”})

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

#ASGIサーバ(uvicornなど)で起動します:
uvicorn main:app –reload

L 318. asgiref(ASGIリファレンス実装)
asgiref は、ASGIアプリケーションの基盤となるリファレンス実装です。ASGI(Asynchronous Server Gateway Interface)は、WSGIの非同期版であり、FastAPI や Starlette などの ASGI フレームワークの基礎となります。

▼主な機能
同期関数と非同期関数のブリッジ(sync_to_async / async_to_sync)
タイムゾーン・ローカル化機能(Djangoで使用)
ASGIアプリのリファレンスツール群

▼使い方(例)
from asgiref.sync import sync_to_async

def blocking_function():
return “Hello from sync!”

async_func = sync_to_async(blocking_function)

import asyncio
asyncio.run(async_func()) # 非同期コードから同期関数を呼び出し

Comments

Copied title and URL