|
| 1 | +import copy |
| 2 | +import sys |
| 3 | +from collections.abc import MutableMapping |
| 4 | +from functools import partial |
| 5 | +from typing import List |
| 6 | + |
| 7 | +from graphql import ExecutionResult |
| 8 | +from graphql.error import GraphQLError |
| 9 | +from graphql.type.schema import GraphQLSchema |
| 10 | +from quart import Response, render_template_string, request |
| 11 | +from quart.views import View |
| 12 | + |
| 13 | +from graphql_server import ( |
| 14 | + GraphQLParams, |
| 15 | + HttpQueryError, |
| 16 | + encode_execution_results, |
| 17 | + format_error_default, |
| 18 | + json_encode, |
| 19 | + load_json_body, |
| 20 | + run_http_query, |
| 21 | +) |
| 22 | +from graphql_server.render_graphiql import ( |
| 23 | + GraphiQLConfig, |
| 24 | + GraphiQLData, |
| 25 | + GraphiQLOptions, |
| 26 | + render_graphiql_sync, |
| 27 | +) |
| 28 | + |
| 29 | + |
| 30 | +class GraphQLView(View): |
| 31 | + schema = None |
| 32 | + root_value = None |
| 33 | + context = None |
| 34 | + pretty = False |
| 35 | + graphiql = False |
| 36 | + graphiql_version = None |
| 37 | + graphiql_template = None |
| 38 | + graphiql_html_title = None |
| 39 | + middleware = None |
| 40 | + batch = False |
| 41 | + enable_async = False |
| 42 | + subscriptions = None |
| 43 | + headers = None |
| 44 | + default_query = None |
| 45 | + header_editor_enabled = None |
| 46 | + should_persist_headers = None |
| 47 | + |
| 48 | + methods = ["GET", "POST", "PUT", "DELETE"] |
| 49 | + |
| 50 | + format_error = staticmethod(format_error_default) |
| 51 | + encode = staticmethod(json_encode) |
| 52 | + |
| 53 | + def __init__(self, **kwargs): |
| 54 | + super(GraphQLView, self).__init__() |
| 55 | + for key, value in kwargs.items(): |
| 56 | + if hasattr(self, key): |
| 57 | + setattr(self, key, value) |
| 58 | + |
| 59 | + assert isinstance( |
| 60 | + self.schema, GraphQLSchema |
| 61 | + ), "A Schema is required to be provided to GraphQLView." |
| 62 | + |
| 63 | + def get_root_value(self): |
| 64 | + return self.root_value |
| 65 | + |
| 66 | + def get_context(self): |
| 67 | + context = ( |
| 68 | + copy.copy(self.context) |
| 69 | + if self.context and isinstance(self.context, MutableMapping) |
| 70 | + else {} |
| 71 | + ) |
| 72 | + if isinstance(context, MutableMapping) and "request" not in context: |
| 73 | + context.update({"request": request}) |
| 74 | + return context |
| 75 | + |
| 76 | + def get_middleware(self): |
| 77 | + return self.middleware |
| 78 | + |
| 79 | + async def dispatch_request(self): |
| 80 | + try: |
| 81 | + request_method = request.method.lower() |
| 82 | + data = await self.parse_body() |
| 83 | + |
| 84 | + show_graphiql = request_method == "get" and self.should_display_graphiql() |
| 85 | + catch = show_graphiql |
| 86 | + |
| 87 | + pretty = self.pretty or show_graphiql or request.args.get("pretty") |
| 88 | + all_params: List[GraphQLParams] |
| 89 | + execution_results, all_params = run_http_query( |
| 90 | + self.schema, |
| 91 | + request_method, |
| 92 | + data, |
| 93 | + query_data=request.args, |
| 94 | + batch_enabled=self.batch, |
| 95 | + catch=catch, |
| 96 | + # Execute options |
| 97 | + run_sync=not self.enable_async, |
| 98 | + root_value=self.get_root_value(), |
| 99 | + context_value=self.get_context(), |
| 100 | + middleware=self.get_middleware(), |
| 101 | + ) |
| 102 | + exec_res = ( |
| 103 | + [ |
| 104 | + ex if ex is None or isinstance(ex, ExecutionResult) else await ex |
| 105 | + for ex in execution_results |
| 106 | + ] |
| 107 | + if self.enable_async |
| 108 | + else execution_results |
| 109 | + ) |
| 110 | + result, status_code = encode_execution_results( |
| 111 | + exec_res, |
| 112 | + is_batch=isinstance(data, list), |
| 113 | + format_error=self.format_error, |
| 114 | + encode=partial(self.encode, pretty=pretty), # noqa |
| 115 | + ) |
| 116 | + |
| 117 | + if show_graphiql: |
| 118 | + graphiql_data = GraphiQLData( |
| 119 | + result=result, |
| 120 | + query=getattr(all_params[0], "query"), |
| 121 | + variables=getattr(all_params[0], "variables"), |
| 122 | + operation_name=getattr(all_params[0], "operation_name"), |
| 123 | + subscription_url=self.subscriptions, |
| 124 | + headers=self.headers, |
| 125 | + ) |
| 126 | + graphiql_config = GraphiQLConfig( |
| 127 | + graphiql_version=self.graphiql_version, |
| 128 | + graphiql_template=self.graphiql_template, |
| 129 | + graphiql_html_title=self.graphiql_html_title, |
| 130 | + jinja_env=None, |
| 131 | + ) |
| 132 | + graphiql_options = GraphiQLOptions( |
| 133 | + default_query=self.default_query, |
| 134 | + header_editor_enabled=self.header_editor_enabled, |
| 135 | + should_persist_headers=self.should_persist_headers, |
| 136 | + ) |
| 137 | + source = render_graphiql_sync( |
| 138 | + data=graphiql_data, config=graphiql_config, options=graphiql_options |
| 139 | + ) |
| 140 | + return await render_template_string(source) |
| 141 | + |
| 142 | + return Response(result, status=status_code, content_type="application/json") |
| 143 | + |
| 144 | + except HttpQueryError as e: |
| 145 | + parsed_error = GraphQLError(e.message) |
| 146 | + return Response( |
| 147 | + self.encode(dict(errors=[self.format_error(parsed_error)])), |
| 148 | + status=e.status_code, |
| 149 | + headers=e.headers, |
| 150 | + content_type="application/json", |
| 151 | + ) |
| 152 | + |
| 153 | + @staticmethod |
| 154 | + async def parse_body(): |
| 155 | + # We use mimetype here since we don't need the other |
| 156 | + # information provided by content_type |
| 157 | + content_type = request.mimetype |
| 158 | + if content_type == "application/graphql": |
| 159 | + refined_data = await request.get_data(raw=False) |
| 160 | + return {"query": refined_data} |
| 161 | + |
| 162 | + elif content_type == "application/json": |
| 163 | + refined_data = await request.get_data(raw=False) |
| 164 | + return load_json_body(refined_data) |
| 165 | + |
| 166 | + elif content_type == "application/x-www-form-urlencoded": |
| 167 | + return await request.form |
| 168 | + |
| 169 | + # TODO: Fix this check |
| 170 | + elif content_type == "multipart/form-data": |
| 171 | + return await request.files |
| 172 | + |
| 173 | + return {} |
| 174 | + |
| 175 | + def should_display_graphiql(self): |
| 176 | + if not self.graphiql or "raw" in request.args: |
| 177 | + return False |
| 178 | + |
| 179 | + return self.request_wants_html() |
| 180 | + |
| 181 | + @staticmethod |
| 182 | + def request_wants_html(): |
| 183 | + best = request.accept_mimetypes.best_match(["application/json", "text/html"]) |
| 184 | + |
| 185 | + # Needed as this was introduced at Quart 0.8.0: https://gitlab.com/pgjones/quart/-/issues/189 |
| 186 | + def _quality(accept, key: str) -> float: |
| 187 | + for option in accept.options: |
| 188 | + if accept._values_match(key, option.value): |
| 189 | + return option.quality |
| 190 | + return 0.0 |
| 191 | + |
| 192 | + if sys.version_info >= (3, 7): |
| 193 | + return ( |
| 194 | + best == "text/html" |
| 195 | + and request.accept_mimetypes[best] |
| 196 | + > request.accept_mimetypes["application/json"] |
| 197 | + ) |
| 198 | + else: |
| 199 | + return best == "text/html" and _quality( |
| 200 | + request.accept_mimetypes, best |
| 201 | + ) > _quality(request.accept_mimetypes, "application/json") |
0 commit comments