Skip to content

Commit

Permalink
allow using multipart/form-data to upload files with graphql
Browse files Browse the repository at this point in the history
  • Loading branch information
jareks committed Aug 25, 2019
1 parent cba5eb8 commit f2fda86
Showing 1 changed file with 17 additions and 1 deletion.
18 changes: 17 additions & 1 deletion starlette/graphql.py
Expand Up @@ -7,6 +7,7 @@
from starlette.requests import Request
from starlette.responses import HTMLResponse, JSONResponse, PlainTextResponse, Response
from starlette.types import Receive, Scope, Send
from starlette.datastructures import UploadFile, MultiDict

try:
import graphene
Expand Down Expand Up @@ -54,6 +55,7 @@ async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
await response(scope, receive, send)

async def handle_graphql(self, request: Request) -> Response:
files = MultiDict()
if request.method in ("GET", "HEAD"):
if "text/html" in request.headers.get("Accept", ""):
if not self.graphiql:
Expand All @@ -75,6 +77,20 @@ async def handle_graphql(self, request: Request) -> Response:
data = {"query": text}
elif "query" in request.query_params:
data = request.query_params
elif "multipart/form-data" in content_type:
form = await request.form()
data = {
"query": form.get('query'),
"variables": json.loads(form.get('variables')),
}

for (key, value) in form.items():
if type(value) is UploadFile:
files.append(key, {
"filename": value.filename,
"content_type": value.content_type,
"content": await form[key].read()
})
else:
return PlainTextResponse(
"Unsupported Media Type",
Expand All @@ -97,7 +113,7 @@ async def handle_graphql(self, request: Request) -> Response:
)

background = BackgroundTasks()
context = {"request": request, "background": background}
context = {"request": request, "background": background, "files": files }

result = await self.execute(
query, variables=variables, context=context, operation_name=operation_name
Expand Down

0 comments on commit f2fda86

Please sign in to comment.