Skip to content

Merge webob-graphql #45

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 6 commits into from
Jul 5, 2020
Merged
Show file tree
Hide file tree
Changes from 1 commit
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/webob/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
from .graphqlview import GraphQLView

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

from graphql.error import GraphQLError
from graphql.type.schema import GraphQLSchema
from webob import Response

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:
schema = None
request = None
root_value = None
context = None
pretty = False
graphiql = False
graphiql_version = None
graphiql_template = None
middleware = None
batch = False
charset = "UTF-8"

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_value(self):
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": self.request})
return context

def get_middleware(self):
return self.middleware

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

def dispatch_request(self):
try:
request_method = self.request.method.lower()
data = self.parse_body()

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

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

execution_results, all_params = run_http_query(
self.schema,
request_method,
data,
query_data=self.request.params,
batch_enabled=self.batch,
catch=catch,
# Execute options
root_value=self.get_root_value(),
context_value=self.get_context_value(),
middleware=self.get_middleware(),
)
result, status_code = encode_execution_results(
execution_results,
is_batch=isinstance(data, list),
format_error=self.format_error,
encode=partial(self.encode, pretty=pretty), # noqa
)

if show_graphiql:
return Response(
render_graphiql(params=all_params[0], result=result),
charset=self.charset,
content_type="text/html",
)

return Response(
result,
status=status_code,
charset=self.charset,
content_type="application/json",
)

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

# WebOb
def parse_body(self):
# We use mimetype here since we don't need the other
# information provided by content_type
content_type = self.request.content_type
if content_type == "application/graphql":
return {"query": self.request.body.decode("utf8")}

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

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

return {}

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

return self.request_wants_html()

def request_wants_html(self):
best = self.request.accept.best_match(["application/json", "text/html"])
return best == "text/html"
141 changes: 141 additions & 0 deletions graphql_server/webob/render_graphiql.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,141 @@
from string import Template

from graphql_server.webob.utils import tojson

GRAPHIQL_VERSION = "0.7.1"

TEMPLATE = 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 render_graphiql(
params, result, graphiql_version=None, graphiql_template=None, graphql_url=None
):
graphiql_version = graphiql_version or GRAPHIQL_VERSION
template = graphiql_template or TEMPLATE

if result != "null":
result = tojson(result)

return template.substitute(
graphiql_version=graphiql_version,
graphql_url=tojson(graphql_url or ""),
result=result,
query=tojson(params and params.query or None),
variables=tojson(params and params.variables or None),
operation_name=tojson(params and params.operation_name or None),
)
56 changes: 56 additions & 0 deletions graphql_server/webob/utils.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
import json

_slash_escape = "\\/" not in json.dumps("/")


def dumps(obj, **kwargs):
"""Serialize ``obj`` to a JSON formatted ``str`` by using the application's
configured encoder (:attr:`~webob.WebOb.json_encoder`) if there is an
application on the stack.
This function can return ``unicode`` strings or ascii-only bytestrings by
default which coerce into unicode strings automatically. That behavior by
default is controlled by the ``JSON_AS_ASCII`` configuration variable
and can be overridden by the simplejson ``ensure_ascii`` parameter.
"""
encoding = kwargs.pop("encoding", None)
rv = json.dumps(obj, **kwargs)
if encoding is not None and isinstance(rv, str):
rv = rv.encode(encoding)
return rv


def htmlsafe_dumps(obj, **kwargs):
"""Works exactly like :func:`dumps` but is safe for use in ``<script>``
tags. It accepts the same arguments and returns a JSON string. Note that
this is available in templates through the ``|tojson`` filter which will
also mark the result as safe. Due to how this function escapes certain
characters this is safe even if used outside of ``<script>`` tags.
The following characters are escaped in strings:
- ``<``
- ``>``
- ``&``
- ``'``
This makes it safe to embed such strings in any place in HTML with the
notable exception of double quoted attributes. In that case single
quote your attributes or HTML escape it in addition.
.. versionchanged:: 0.10
This function's return value is now always safe for HTML usage, even
if outside of script tags or if used in XHTML. This rule does not
hold true when using this function in HTML attributes that are double
quoted. Always single quote attributes if you use the ``|tojson``
filter. Alternatively use ``|tojson|forceescape``.
"""
rv = (
dumps(obj, **kwargs)
.replace(u"<", u"\\u003c")
.replace(u">", u"\\u003e")
.replace(u"&", u"\\u0026")
.replace(u"'", u"\\u0027")
)
if not _slash_escape:
rv = rv.replace("\\/", "/")
return rv


def tojson(obj, **kwargs):
return htmlsafe_dumps(obj, **kwargs)
8 changes: 7 additions & 1 deletion setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,10 +27,15 @@
"sanic>=19.9.0,<20",
]

install_webob_requires = [
"webob>=1.8.6,<2",
]

install_all_requires = \
install_requires + \
install_flask_requires + \
install_sanic_requires
install_sanic_requires + \
install_webob_requires

setup(
name="graphql-server-core",
Expand Down Expand Up @@ -62,6 +67,7 @@
"dev": install_all_requires + dev_requires,
"flask": install_flask_requires,
"sanic": install_sanic_requires,
"webob": install_webob_requires,
},
include_package_data=True,
zip_safe=False,
Expand Down
Empty file added tests/webob/__init__.py
Empty file.
Loading