Skip to content

Merge sanic-graphql #38

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Jun 6, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions graphql_server/sanic/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
from .graphqlview import GraphQLView

__all__ = ["GraphQLView"]
190 changes: 190 additions & 0 deletions graphql_server/sanic/graphqlview.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,190 @@
import copy
from cgi import parse_header
from collections.abc import MutableMapping
from functools import partial

from graphql import GraphQLError
from graphql.type.schema import GraphQLSchema
from sanic.response import HTTPResponse
from sanic.views import HTTPMethodView

from graphql_server import (
HttpQueryError,
encode_execution_results,
format_error_default,
json_encode,
load_json_body,
run_http_query,
)

from .render_graphiql import render_graphiql


class GraphQLView(HTTPMethodView):
schema = None
root_value = None
context = None
pretty = False
graphiql = False
graphiql_version = None
graphiql_template = None
middleware = None
batch = False
jinja_env = None
max_age = 86400
enable_async = False

methods = ["GET", "POST", "PUT", "DELETE"]

def __init__(self, **kwargs):
super(GraphQLView, self).__init__()
for key, value in kwargs.items():
if hasattr(self, key):
setattr(self, key, value)

assert isinstance(
self.schema, GraphQLSchema
), "A Schema is required to be provided to GraphQLView."

def get_root_value(self):
return self.root_value

def get_context(self, request):
context = (
copy.copy(self.context)
if self.context and isinstance(self.context, MutableMapping)
else {}
)
if isinstance(context, MutableMapping) and "request" not in context:
context.update({"request": request})
return context

def get_middleware(self):
return self.middleware

async def render_graphiql(self, params, result):
return await render_graphiql(
jinja_env=self.jinja_env,
params=params,
result=result,
graphiql_version=self.graphiql_version,
graphiql_template=self.graphiql_template,
)

format_error = staticmethod(format_error_default)
encode = staticmethod(json_encode)

async def dispatch_request(self, request, *args, **kwargs):
try:
request_method = request.method.lower()
data = self.parse_body(request)

show_graphiql = request_method == "get" and self.should_display_graphiql(
request
)
catch = show_graphiql

pretty = self.pretty or show_graphiql or request.args.get("pretty")

if request_method != "options":
execution_results, all_params = run_http_query(
self.schema,
request_method,
data,
query_data=request.args,
batch_enabled=self.batch,
catch=catch,
# Execute options
run_sync=not self.enable_async,
root_value=self.get_root_value(),
context_value=self.get_context(request),
middleware=self.get_middleware(),
)
exec_res = (
[await ex for ex in execution_results]
if self.enable_async
else execution_results
)
result, status_code = encode_execution_results(
exec_res,
is_batch=isinstance(data, list),
format_error=self.format_error,
encode=partial(self.encode, pretty=pretty), # noqa: ignore
)

if show_graphiql:
return await self.render_graphiql(
params=all_params[0], result=result
)

return HTTPResponse(
result, status=status_code, content_type="application/json"
)

else:
return self.process_preflight(request)

except HttpQueryError as e:
parsed_error = GraphQLError(e.message)
return HTTPResponse(
self.encode(dict(errors=[self.format_error(parsed_error)])),
status=e.status_code,
headers=e.headers,
content_type="application/json",
)

# noinspection PyBroadException
def parse_body(self, request):
content_type = self.get_mime_type(request)
if content_type == "application/graphql":
return {"query": request.body.decode("utf8")}

elif content_type == "application/json":
return load_json_body(request.body.decode("utf8"))

elif content_type in (
"application/x-www-form-urlencoded",
"multipart/form-data",
):
return request.form

return {}

@staticmethod
def get_mime_type(request):
# We use mime type here since we don't need the other
# information provided by content_type
if "content-type" not in request.headers:
return None

mime_type, _ = parse_header(request.headers["content-type"])
return mime_type

def should_display_graphiql(self, request):
if not self.graphiql or "raw" in request.args:
return False

return self.request_wants_html(request)

@staticmethod
def request_wants_html(request):
accept = request.headers.get("accept", {})
return "text/html" in accept or "*/*" in accept

def process_preflight(self, request):
""" Preflight request support for apollo-client
https://www.w3.org/TR/cors/#resource-preflight-requests """
origin = request.headers.get("Origin", "")
method = request.headers.get("Access-Control-Request-Method", "").upper()

if method and method in self.methods:
return HTTPResponse(
status=200,
headers={
"Access-Control-Allow-Origin": origin,
"Access-Control-Allow-Methods": ", ".join(self.methods),
"Access-Control-Max-Age": str(self.max_age),
},
)
else:
return HTTPResponse(status=400)
185 changes: 185 additions & 0 deletions graphql_server/sanic/render_graphiql.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,185 @@
import json
import re

from sanic.response import html

GRAPHIQL_VERSION = "0.7.1"

TEMPLATE = """<!--
The request to this GraphQL server provided the header "Accept: text/html"
and as a result has been presented GraphiQL - an in-browser IDE for
exploring GraphQL.
If you wish to receive JSON, provide the header "Accept: application/json" or
add "&raw" to the end of the URL within a browser.
-->
<!DOCTYPE html>
<html>
<head>
<style>
html, body {
height: 100%;
margin: 0;
overflow: hidden;
width: 100%;
}
</style>
<meta name="referrer" content="no-referrer">
<link
href="//cdn.jsdelivr.net/graphiql/{{graphiql_version}}/graphiql.css"
rel="stylesheet" />
<script src="//cdn.jsdelivr.net/fetch/0.9.0/fetch.min.js"></script>
<script src="//cdn.jsdelivr.net/react/15.0.0/react.min.js"></script>
<script src="//cdn.jsdelivr.net/react/15.0.0/react-dom.min.js"></script>
<script
src="//cdn.jsdelivr.net/graphiql/{{graphiql_version}}/graphiql.min.js">
</script>
</head>
<body>
<script>
// Collect the URL parameters
var parameters = {};
window.location.search.substr(1).split('&').forEach(function (entry) {
var eq = entry.indexOf('=');
if (eq >= 0) {
parameters[decodeURIComponent(entry.slice(0, eq))] =
decodeURIComponent(entry.slice(eq + 1));
}
});
// Produce a Location query string from a parameter object.
function locationQuery(params) {
return '?' + Object.keys(params).map(function (key) {
return encodeURIComponent(key) + '=' +
encodeURIComponent(params[key]);
}).join('&');
}
// Derive a fetch URL from the current URL, sans the GraphQL parameters.
var graphqlParamNames = {
query: true,
variables: true,
operationName: true
};
var otherParams = {};
for (var k in parameters) {
if (parameters.hasOwnProperty(k) && graphqlParamNames[k] !== true) {
otherParams[k] = parameters[k];
}
}
var fetchURL = locationQuery(otherParams);
// Defines a GraphQL fetcher using the fetch API.
function graphQLFetcher(graphQLParams) {
return fetch(fetchURL, {
method: 'post',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(graphQLParams),
credentials: 'include',
}).then(function (response) {
return response.text();
}).then(function (responseBody) {
try {
return JSON.parse(responseBody);
} catch (error) {
return responseBody;
}
});
}
// When the query and variables string is edited, update the URL bar so
// that it can be easily shared.
function onEditQuery(newQuery) {
parameters.query = newQuery;
updateURL();
}
function onEditVariables(newVariables) {
parameters.variables = newVariables;
updateURL();
}
function onEditOperationName(newOperationName) {
parameters.operationName = newOperationName;
updateURL();
}
function updateURL() {
history.replaceState(null, null, locationQuery(parameters));
}
// Render <GraphiQL /> into the body.
ReactDOM.render(
React.createElement(GraphiQL, {
fetcher: graphQLFetcher,
onEditQuery: onEditQuery,
onEditVariables: onEditVariables,
onEditOperationName: onEditOperationName,
query: {{query|tojson}},
response: {{result|tojson}},
variables: {{variables|tojson}},
operationName: {{operation_name|tojson}},
}),
document.body
);
</script>
</body>
</html>"""


def escape_js_value(value):
quotation = False
if value.startswith('"') and value.endswith('"'):
quotation = True
value = value[1 : len(value) - 1]

value = value.replace("\\\\n", "\\\\\\n").replace("\\n", "\\\\n")
if quotation:
value = '"' + value.replace('\\\\"', '"').replace('"', '\\"') + '"'

return value


def process_var(template, name, value, jsonify=False):
pattern = r"{{\s*" + name + r"(\s*|[^}]+)*\s*}}"
if jsonify and value not in ["null", "undefined"]:
value = json.dumps(value)
value = escape_js_value(value)

return re.sub(pattern, value, template)


def simple_renderer(template, **values):
replace = ["graphiql_version"]
replace_jsonify = ["query", "result", "variables", "operation_name"]

for r in replace:
template = process_var(template, r, values.get(r, ""))

for r in replace_jsonify:
template = process_var(template, r, values.get(r, ""), True)

return template


async def render_graphiql(
jinja_env=None,
graphiql_version=None,
graphiql_template=None,
params=None,
result=None,
):
graphiql_version = graphiql_version or GRAPHIQL_VERSION
template = graphiql_template or TEMPLATE
template_vars = {
"graphiql_version": graphiql_version,
"query": params and params.query,
"variables": params and params.variables,
"operation_name": params and params.operation_name,
"result": result,
}

if jinja_env:
template = jinja_env.from_string(template)
if jinja_env.is_async:
source = await template.render_async(**template_vars)
else:
source = template.render(**template_vars)
else:
source = simple_renderer(template, **template_vars)

return html(source)
1 change: 1 addition & 0 deletions setup.cfg
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
[flake8]
exclude = docs
max-line-length = 88
ignore = E203, E501, W503

[isort]
known_first_party=graphql_server
Expand Down
Loading