Skip to content

Commit

Permalink
Refactored code using graphql_server
Browse files Browse the repository at this point in the history
  • Loading branch information
syrusakbary committed Mar 19, 2017
1 parent 182782c commit 05a6077
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 182 deletions.
201 changes: 20 additions & 181 deletions flask_graphql/graphqlview.py
Original file line number Diff line number Diff line change
@@ -1,34 +1,14 @@
import json
from promise import Promise
from collections import namedtuple

import six
from flask import Response, request
from flask.views import View

from graphql import Source, execute, parse, validate
from graphql.error import format_error as format_graphql_error
from graphql.error import GraphQLError
from graphql.execution import ExecutionResult
from graphql.type.schema import GraphQLSchema
from graphql.utils.get_operation_ast import get_operation_ast
from graphql_server import run_http_query, HttpQueryError, default_format_error, load_json_body

from .render_graphiql import render_graphiql


GraphQLParams = namedtuple('GraphQLParams', 'query,variables,operation_name,id')
GraphQLResponse = namedtuple('GraphQLResponse', 'result,status_code')


class HttpQueryError(Exception):
def __init__(self, status_code, message=None, is_graphql_error=False, headers=None):
self.status_code = status_code
self.message = message
self.is_graphql_error = is_graphql_error
self.headers = headers
super(HttpQueryError, self).__init__(message)


class GraphQLView(View):
schema = None
executor = None
Expand All @@ -51,22 +31,18 @@ def __init__(self, **kwargs):

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

# Flask
# noinspection PyUnusedLocal
def get_root_value(self):
return self.root_value

# Flask
def get_context(self):
if self.context is not None:
return self.context
return request

# Flask
def get_middleware(self):
return self.middleware

# Flask
def get_executor(self):
return self.executor

Expand All @@ -82,57 +58,30 @@ def dispatch_request(self):

try:
request_method = request.method.lower()
if request_method not in ('get', 'post'):
raise HttpQueryError(
405,
'GraphQL only supports GET and POST requests.',
headers={
'Allow': ['GET, POST']
}
)

data = self.parse_body()
is_batch = isinstance(data, list)
if isinstance(data, dict):
data = dict(data, **request.args.to_dict())

show_graphiql = not is_batch and self.should_display_graphiql(data)
show_graphiql = request_method == 'get' and self.should_display_graphiql()
catch = HttpQueryError if show_graphiql else None
only_allow_query = request_method == 'get'

if not is_batch:
if not isinstance(data, dict):
raise HttpQueryError(
400,
'GraphQL params should be a dict. Received {}.'.format(data)
)
data = dict(data, **request.args.to_dict())
data = [data]
elif not self.batch:
raise HttpQueryError(
400,
'Batch GraphQL requests are not enabled.'
)

all_params = [self.get_graphql_params(entry) for entry in data]
pretty = self.pretty or show_graphiql or request.args.get('pretty')

responses = [self.get_response(
result, status_code, all_params = run_http_query(
self.schema,
params,
catch,
only_allow_query,
request_method,
data,
batch_enabled=self.batch,
catch=catch,

# Execute options
root_value=self.get_root_value(),
context_value=self.get_context(),
middleware=self.get_middleware(),
executor=self.get_executor(),
) for params in all_params]

response, status_codes = zip(*responses)
status_code = max(status_codes)

if not is_batch:
response = response[0]
)

pretty = self.pretty or show_graphiql or request.args.get('pretty')
result = self.json_encode(response, pretty)
result = self.json_encode(result, pretty)

if show_graphiql:
return self.render_graphiql(
Expand All @@ -149,49 +98,13 @@ def dispatch_request(self):
except HttpQueryError as e:
return Response(
self.json_encode({
'errors': [self.format_error(e)]
'errors': [default_format_error(e)]
}),
status=e.status_code,
headers=e.headers,
content_type='application/json'
)

def get_response(self, schema, params, catch=None, only_allow_query=False, **kwargs):
try:
execution_result = self.execute_graphql_request(
schema,
params,
only_allow_query,
**kwargs
)
except catch:
return GraphQLResponse(None, 400)

return self.format_execution_result(execution_result, params.id, self.format_error)

@staticmethod
def format_execution_result(execution_result, id, format_error):
status_code = 200
if execution_result:
response = {}

if execution_result.errors:
response['errors'] = [format_error(e) for e in execution_result.errors]

if execution_result.invalid:
status_code = 400
else:
status_code = 200
response['data'] = execution_result.data

if id:
response['id'] = id

else:
response = None

return GraphQLResponse(response, status_code)

# Flask
# noinspection PyBroadException
def parse_body(self):
Expand All @@ -202,61 +115,14 @@ def parse_body(self):
return {'query': request.data.decode()}

elif content_type == 'application/json':
try:
return json.loads(request.data.decode('utf8'))
except:
raise HttpQueryError(
400,
'POST body sent invalid JSON.'
)

elif content_type == 'application/x-www-form-urlencoded':
return request.form.to_dict()
return load_json_body(request.data.decode('utf8'))

elif content_type == 'multipart/form-data':
elif content_type == 'application/x-www-form-urlencoded' \
or content_type == 'multipart/form-data':
return request.form.to_dict()

return {}

@staticmethod
def execute_graphql_request(schema, params, only_allow_query=False, **kwargs):
if not params.query:
raise HttpQueryError(400, 'Must provide query string.')

try:
source = Source(params.query, name='GraphQL request')
ast = parse(source)
validation_errors = validate(schema, ast)
if validation_errors:
return ExecutionResult(
errors=validation_errors,
invalid=True,
)
except Exception as e:
return ExecutionResult(errors=[e], invalid=True)

if only_allow_query:
operation_ast = get_operation_ast(ast, params.operation_name)
if operation_ast and operation_ast.operation != 'query':
raise HttpQueryError(
405,
'Can only perform a {} operation from a POST request.'.format(operation_ast.operation),
headers={
'Allow': ['POST'],
}
)

try:
return execute(
schema,
ast,
operation_name=params.operation_name,
variable_values=params.variables,
**kwargs
)
except Exception as e:
return ExecutionResult(errors=[e], invalid=True)

@staticmethod
def json_encode(data, pretty=False):
if not pretty:
Expand All @@ -268,42 +134,15 @@ def json_encode(data, pretty=False):
separators=(',', ': ')
)

# Flask
def should_display_graphiql(self, data):
if not self.graphiql or 'raw' in data:
def should_display_graphiql(self):
if not self.graphiql or 'raw' in request.args:
return False

return self.request_wants_html()

# Flask
def request_wants_html(self):
best = request.accept_mimetypes \
.best_match(['application/json', 'text/html'])
return best == 'text/html' and \
request.accept_mimetypes[best] > \
request.accept_mimetypes['application/json']

@staticmethod
def get_variables(variables):
if variables and isinstance(variables, six.text_type):
try:
return json.loads(variables)
except:
raise HttpQueryError(400, 'Variables are invalid JSON.')
return variables

@classmethod
def get_graphql_params(cls, data):
query = data.get('query')
variables = cls.get_variables(data.get('variables'))
id = data.get('id')
operation_name = data.get('operationName')

return GraphQLParams(query, variables, operation_name, id)

@staticmethod
def format_error(error):
if isinstance(error, GraphQLError):
return format_graphql_error(error)

return {'message': six.text_type(error)}
2 changes: 1 addition & 1 deletion tests/app.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
from flask import Flask
from flask_graphql import GraphQLView
from .schema import Schema
from schema import Schema


def create_app(path='/graphql', **kwargs):
Expand Down

0 comments on commit 05a6077

Please sign in to comment.