Merge pull request #75 from tomchristie/asgi-middleware

Support ASGI middleware
This commit is contained in:
2018-10-17 12:03:15 -07:00
committed by GitHub
2 changed files with 9 additions and 27 deletions
+9
View File
@@ -11,6 +11,7 @@ from graphql_server import encode_execution_results, json_encode, default_format
from starlette.routing import Router
from starlette.staticfiles import StaticFiles
from starlette.testclient import TestClient
from starlette.middleware.gzip import GZipMiddleware
from apispec import APISpec
from apispec.ext.marshmallow import MarshmallowPlugin
from apispec import yaml_utils
@@ -76,6 +77,8 @@ class API:
self.add_route(openapi_route, self.schema_response)
self.default_endpoint = None
self.app = self.dispatch
self.add_middleware(GZipMiddleware)
@property
def _apispec(self):
@@ -102,6 +105,9 @@ class API:
def openapi(self):
return self._apispec.to_yaml()
def add_middleware(self, middleware_cls, **middleware_config):
self.app = middleware_cls(self.app, **middleware_config)
def __call__(self, scope):
path = scope["path"]
root_path = scope.get("root_path", "")
@@ -117,6 +123,9 @@ class API:
app = WsgiToAsgi(app)
return app(scope)
return self.app(scope)
def dispatch(self, scope):
# Call the main dispatcher.
async def asgi(receive, send):
nonlocal scope, self
-27
View File
@@ -250,35 +250,8 @@ class Response:
{"Content-Type": "application/json"},
)
@property
async def gzipped_body(self):
body, headers = await self.body
if isinstance(body, str):
body = body.encode(self.encoding)
if "gzip" in self.req.headers["Accept-Encoding"].lower():
gzip_buffer = io.BytesIO()
gzip_file = gzip.GzipFile(mode="wb", fileobj=gzip_buffer)
gzip_file.write(body)
gzip_file.close()
new_headers = {
"Content-Encoding": "gzip",
"Vary": "Accept-Encoding",
"Content-Length": str(len(body)),
}
headers.update(new_headers)
return (gzip_buffer.getvalue(), headers)
else:
return (body, headers)
async def __call__(self, receive, send):
body, headers = await self.body
if len(await self.body) > 500:
body, headers = await self.gzipped_body
if self.headers:
headers.update(self.headers)