ミドルウェア#

ミドルウェアは Quart アプリインスタンスをラップして ASGI プロセスを変更するために使用できます。非常にシンプルな例としては、ヘッダーの存在に基づいてリクエストを拒否するものがあります。

class RejectMiddleware:

    def __init__(self, app):
        self.app = app

    async def __call__(self, scope, receive, send):
        if "headers" not in scope:
            return await self.app(scope, receive, send)

        for header, value in scope['headers']:
            if header.lower() == b'x-secret' and value == b'very-secret':
                return await self.app(scope, receive, send)

        return await self.error_response(receive, send)

    async def error_response(self, receive, send):
        await send({
            'type': 'http.response.start',
            'status': 401,
            'headers': [(b'content-length', b'0')],
        })
        await send({
            'type': 'http.response.body',
            'body': b'',
            'more_body': False,
        })

ミドルウェアは常にアプリインスタンスのラッパーとして使用できますが、asgi_app 属性に割り当ててラップするのが最善です。

quart_app.asgi_app = RejectMiddleware(quart_app.asgi_app)

これにより、ミドルウェアがテストコードで適用されるようになります。

複数のミドルウェアラッパーを組み合わせて、

quart_app.asgi_app = RejectMiddleware(quart_app.asgi_app)
quart_app.asgi_app = AdditionalMiddleware(quart_app.asgi_app)

任意の ASGI ミドルウェアを使用できます。

警告

ミドルウェアは Quart コードの前に実行されるため、ミドルウェアがレスポンスを返した場合、Quart ファンクションも Quart 拡張機能も実行されません。