|
| 1 | +import json |
| 2 | +from werkzeug.exceptions import BadRequest, MethodNotAllowed |
| 3 | +from flask import Response, request |
| 4 | +from flask.views import View |
| 5 | +from graphql.core import Source, parse |
| 6 | +from graphql.core.error import GraphQLError, format_error as format_graphql_error |
| 7 | +from graphql.core.execution import ExecutionResult, get_default_executor |
| 8 | +from graphql.core.type.schema import GraphQLSchema |
| 9 | +from graphql.core.utils.get_operation_ast import get_operation_ast |
| 10 | +import six |
| 11 | + |
| 12 | + |
| 13 | +class HttpError(Exception): |
| 14 | + def __init__(self, response, message=None, *args, **kwargs): |
| 15 | + self.response = response |
| 16 | + self.message = message = message or response.description.decode() |
| 17 | + super(HttpError, self).__init__(message, *args, **kwargs) |
| 18 | + |
| 19 | + |
| 20 | +class GraphQLView(View): |
| 21 | + schema = None |
| 22 | + executor = None |
| 23 | + root_value = None |
| 24 | + pretty = False |
| 25 | + |
| 26 | + methods = ['GET', 'POST', 'PUT', 'DELETE'] |
| 27 | + |
| 28 | + def __init__(self, **kwargs): |
| 29 | + super(GraphQLView, self).__init__() |
| 30 | + for key, value in kwargs.items(): |
| 31 | + if hasattr(self, key): |
| 32 | + setattr(self, key, value) |
| 33 | + |
| 34 | + if not self.executor: |
| 35 | + self.executor = get_default_executor() |
| 36 | + |
| 37 | + assert isinstance(self.schema, GraphQLSchema), 'A Schema is required to be provided to GraphQLView.' |
| 38 | + |
| 39 | + # noinspection PyUnusedLocal |
| 40 | + def get_root_value(self, request): |
| 41 | + return self.root_value |
| 42 | + |
| 43 | + def get_request_context(self, request): |
| 44 | + return request |
| 45 | + |
| 46 | + def dispatch_request(self): |
| 47 | + try: |
| 48 | + if request.method.lower() not in ('get', 'post'): |
| 49 | + raise HttpError(MethodNotAllowed(['GET', 'POST'], 'GraphQL only supports GET and POST requests.')) |
| 50 | + |
| 51 | + execution_result = self.execute_graphql_request(request) |
| 52 | + response = {} |
| 53 | + |
| 54 | + if execution_result.errors: |
| 55 | + response['errors'] = [self.format_error(e) for e in execution_result.errors] |
| 56 | + |
| 57 | + if execution_result.invalid: |
| 58 | + status_code = 400 |
| 59 | + else: |
| 60 | + status_code = 200 |
| 61 | + response['data'] = execution_result.data |
| 62 | + |
| 63 | + return Response( |
| 64 | + status=status_code, |
| 65 | + response=self.json_encode(request, response), |
| 66 | + content_type='application/json' |
| 67 | + ) |
| 68 | + |
| 69 | + except HttpError as e: |
| 70 | + return Response( |
| 71 | + self.json_encode(request, { |
| 72 | + 'errors': [self.format_error(e)] |
| 73 | + }), |
| 74 | + status=e.response.code, |
| 75 | + headers={'Allow': ['GET, POST']}, |
| 76 | + content_type='application/json' |
| 77 | + ) |
| 78 | + |
| 79 | + def json_encode(self, request, d): |
| 80 | + if not self.pretty and not request.args.get('pretty'): |
| 81 | + return json.dumps(d, separators=(',', ':')) |
| 82 | + |
| 83 | + return json.dumps(d, sort_keys=True, |
| 84 | + indent=2, separators=(',', ': ')) |
| 85 | + |
| 86 | + # noinspection PyBroadException |
| 87 | + def parse_body(self, request): |
| 88 | + content_type = self.get_content_type(request) |
| 89 | + |
| 90 | + if content_type == 'application/graphql': |
| 91 | + return {'query': request.data.decode()} |
| 92 | + |
| 93 | + elif content_type == 'application/json': |
| 94 | + try: |
| 95 | + request_json = json.loads(request.data.decode()) |
| 96 | + assert isinstance(request_json, dict) |
| 97 | + return request_json |
| 98 | + except: |
| 99 | + raise HttpError(BadRequest('POST body sent invalid JSON.')) |
| 100 | + |
| 101 | + elif content_type == 'application/x-www-form-urlencoded': |
| 102 | + return request.form |
| 103 | + |
| 104 | + return {} |
| 105 | + |
| 106 | + def execute(self, *args, **kwargs): |
| 107 | + return self.executor.execute(self.schema, *args, **kwargs) |
| 108 | + |
| 109 | + def execute_graphql_request(self, request): |
| 110 | + query, variables, operation_name = self.get_graphql_params(request, self.parse_body(request)) |
| 111 | + |
| 112 | + if not query: |
| 113 | + raise HttpError(BadRequest('Must provide query string.')) |
| 114 | + |
| 115 | + source = Source(query, name='GraphQL request') |
| 116 | + |
| 117 | + try: |
| 118 | + document_ast = parse(source) |
| 119 | + except Exception as e: |
| 120 | + return ExecutionResult(errors=[e], invalid=True) |
| 121 | + |
| 122 | + if request.method.lower() == 'get': |
| 123 | + operation_ast = get_operation_ast(document_ast, operation_name) |
| 124 | + if operation_ast and operation_ast.operation != 'query': |
| 125 | + raise HttpError(MethodNotAllowed( |
| 126 | + ['POST'], 'Can only perform a {} operation from a POST request.'.format(operation_ast.operation) |
| 127 | + )) |
| 128 | + |
| 129 | + try: |
| 130 | + return self.execute( |
| 131 | + document_ast, |
| 132 | + self.get_root_value(request), |
| 133 | + variables, |
| 134 | + operation_name=operation_name, |
| 135 | + request_context=self.get_request_context(request) |
| 136 | + ) |
| 137 | + except Exception as e: |
| 138 | + return ExecutionResult(errors=[e], invalid=True) |
| 139 | + |
| 140 | + @staticmethod |
| 141 | + def get_graphql_params(request, data): |
| 142 | + query = request.args.get('query') or data.get('query') |
| 143 | + variables = request.args.get('variables') or data.get('variables') |
| 144 | + |
| 145 | + if variables and isinstance(variables, six.text_type): |
| 146 | + try: |
| 147 | + variables = json.loads(variables) |
| 148 | + except: |
| 149 | + raise HttpError(BadRequest('Variables are invalid JSON.')) |
| 150 | + |
| 151 | + operation_name = request.args.get('operationName') or data.get('operationName') |
| 152 | + |
| 153 | + return query, variables, operation_name |
| 154 | + |
| 155 | + @staticmethod |
| 156 | + def format_error(error): |
| 157 | + if isinstance(error, GraphQLError): |
| 158 | + return format_graphql_error(error) |
| 159 | + |
| 160 | + return {'message': six.text_type(error)} |
| 161 | + |
| 162 | + @staticmethod |
| 163 | + def get_content_type(request): |
| 164 | + return request.content_type |
0 commit comments