Exemplos

HTTP

from asgikit import Request


async def main(scope, receive, send):
    if scope["type"] != "http":
        return

    request = Request(scope, receive, send)

    # request method
    method = request.method

    # request path
    path = request.path

    # request headers
    headers = request.headers

    # read body as json
    body = await request.body.read_json()

    data = {
        "lang": "Python",
        "async": True,
        "platform": "asgi",
        "method": method,
        "path": path,
        "headers": dict(headers.items()),
        "body": body,
    }

    # send json response
    await request.respond_json(data)

WebSocket

from asgikit import Request, WebSocketDisconnect


async def app(scope, receive, send):
    if scope["type"] != "websocket":
        return

    request = Request(scope, receive, send)
    ws = await request.upgrade()
    print("Client connected")

    while True:
        try:
            message = await ws.read()
            await ws.write(message)
        except WebSocketDisconnect:
            print("Client disconnected")
            break