|
| 1 | +import copy |
| 2 | +from cgi import parse_header |
| 3 | +from collections.abc import MutableMapping |
| 4 | +from functools import partial |
| 5 | + |
| 6 | +from graphql import GraphQLError |
| 7 | +from graphql.type.schema import GraphQLSchema |
| 8 | +from sanic.response import HTTPResponse |
| 9 | +from sanic.views import HTTPMethodView |
| 10 | + |
| 11 | +from graphql_server import ( |
| 12 | + HttpQueryError, |
| 13 | + encode_execution_results, |
| 14 | + format_error_default, |
| 15 | + json_encode, |
| 16 | + load_json_body, |
| 17 | + run_http_query, |
| 18 | +) |
| 19 | + |
| 20 | +from .render_graphiql import render_graphiql |
| 21 | + |
| 22 | + |
| 23 | +class GraphQLView(HTTPMethodView): |
| 24 | + schema = None |
| 25 | + root_value = None |
| 26 | + context = None |
| 27 | + pretty = False |
| 28 | + graphiql = False |
| 29 | + graphiql_version = None |
| 30 | + graphiql_template = None |
| 31 | + middleware = None |
| 32 | + batch = False |
| 33 | + jinja_env = None |
| 34 | + max_age = 86400 |
| 35 | + enable_async = False |
| 36 | + |
| 37 | + methods = ["GET", "POST", "PUT", "DELETE"] |
| 38 | + |
| 39 | + def __init__(self, **kwargs): |
| 40 | + super(GraphQLView, self).__init__() |
| 41 | + for key, value in kwargs.items(): |
| 42 | + if hasattr(self, key): |
| 43 | + setattr(self, key, value) |
| 44 | + |
| 45 | + assert isinstance( |
| 46 | + self.schema, GraphQLSchema |
| 47 | + ), "A Schema is required to be provided to GraphQLView." |
| 48 | + |
| 49 | + def get_root_value(self): |
| 50 | + return self.root_value |
| 51 | + |
| 52 | + def get_context(self, request): |
| 53 | + context = ( |
| 54 | + copy.copy(self.context) |
| 55 | + if self.context and isinstance(self.context, MutableMapping) |
| 56 | + else {} |
| 57 | + ) |
| 58 | + if isinstance(context, MutableMapping) and "request" not in context: |
| 59 | + context.update({"request": request}) |
| 60 | + return context |
| 61 | + |
| 62 | + def get_middleware(self): |
| 63 | + return self.middleware |
| 64 | + |
| 65 | + async def render_graphiql(self, params, result): |
| 66 | + return await render_graphiql( |
| 67 | + jinja_env=self.jinja_env, |
| 68 | + params=params, |
| 69 | + result=result, |
| 70 | + graphiql_version=self.graphiql_version, |
| 71 | + graphiql_template=self.graphiql_template, |
| 72 | + ) |
| 73 | + |
| 74 | + format_error = staticmethod(format_error_default) |
| 75 | + encode = staticmethod(json_encode) |
| 76 | + |
| 77 | + async def dispatch_request(self, request, *args, **kwargs): |
| 78 | + try: |
| 79 | + request_method = request.method.lower() |
| 80 | + data = self.parse_body(request) |
| 81 | + |
| 82 | + show_graphiql = request_method == "get" and self.should_display_graphiql( |
| 83 | + request |
| 84 | + ) |
| 85 | + catch = show_graphiql |
| 86 | + |
| 87 | + pretty = self.pretty or show_graphiql or request.args.get("pretty") |
| 88 | + |
| 89 | + if request_method != "options": |
| 90 | + execution_results, all_params = run_http_query( |
| 91 | + self.schema, |
| 92 | + request_method, |
| 93 | + data, |
| 94 | + query_data=request.args, |
| 95 | + batch_enabled=self.batch, |
| 96 | + catch=catch, |
| 97 | + # Execute options |
| 98 | + run_sync=not self.enable_async, |
| 99 | + root_value=self.get_root_value(), |
| 100 | + context_value=self.get_context(request), |
| 101 | + middleware=self.get_middleware(), |
| 102 | + ) |
| 103 | + exec_res = ( |
| 104 | + [await ex for ex in execution_results] |
| 105 | + if self.enable_async |
| 106 | + else execution_results |
| 107 | + ) |
| 108 | + result, status_code = encode_execution_results( |
| 109 | + exec_res, |
| 110 | + is_batch=isinstance(data, list), |
| 111 | + format_error=self.format_error, |
| 112 | + encode=partial(self.encode, pretty=pretty), # noqa: ignore |
| 113 | + ) |
| 114 | + |
| 115 | + if show_graphiql: |
| 116 | + return await self.render_graphiql( |
| 117 | + params=all_params[0], result=result |
| 118 | + ) |
| 119 | + |
| 120 | + return HTTPResponse( |
| 121 | + result, status=status_code, content_type="application/json" |
| 122 | + ) |
| 123 | + |
| 124 | + else: |
| 125 | + return self.process_preflight(request) |
| 126 | + |
| 127 | + except HttpQueryError as e: |
| 128 | + parsed_error = GraphQLError(e.message) |
| 129 | + return HTTPResponse( |
| 130 | + self.encode(dict(errors=[self.format_error(parsed_error)])), |
| 131 | + status=e.status_code, |
| 132 | + headers=e.headers, |
| 133 | + content_type="application/json", |
| 134 | + ) |
| 135 | + |
| 136 | + # noinspection PyBroadException |
| 137 | + def parse_body(self, request): |
| 138 | + content_type = self.get_mime_type(request) |
| 139 | + if content_type == "application/graphql": |
| 140 | + return {"query": request.body.decode("utf8")} |
| 141 | + |
| 142 | + elif content_type == "application/json": |
| 143 | + return load_json_body(request.body.decode("utf8")) |
| 144 | + |
| 145 | + elif content_type in ( |
| 146 | + "application/x-www-form-urlencoded", |
| 147 | + "multipart/form-data", |
| 148 | + ): |
| 149 | + return request.form |
| 150 | + |
| 151 | + return {} |
| 152 | + |
| 153 | + @staticmethod |
| 154 | + def get_mime_type(request): |
| 155 | + # We use mime type here since we don't need the other |
| 156 | + # information provided by content_type |
| 157 | + if "content-type" not in request.headers: |
| 158 | + return None |
| 159 | + |
| 160 | + mime_type, _ = parse_header(request.headers["content-type"]) |
| 161 | + return mime_type |
| 162 | + |
| 163 | + def should_display_graphiql(self, request): |
| 164 | + if not self.graphiql or "raw" in request.args: |
| 165 | + return False |
| 166 | + |
| 167 | + return self.request_wants_html(request) |
| 168 | + |
| 169 | + @staticmethod |
| 170 | + def request_wants_html(request): |
| 171 | + accept = request.headers.get("accept", {}) |
| 172 | + return "text/html" in accept or "*/*" in accept |
| 173 | + |
| 174 | + def process_preflight(self, request): |
| 175 | + """ Preflight request support for apollo-client |
| 176 | + https://www.w3.org/TR/cors/#resource-preflight-requests """ |
| 177 | + origin = request.headers.get("Origin", "") |
| 178 | + method = request.headers.get("Access-Control-Request-Method", "").upper() |
| 179 | + |
| 180 | + if method and method in self.methods: |
| 181 | + return HTTPResponse( |
| 182 | + status=200, |
| 183 | + headers={ |
| 184 | + "Access-Control-Allow-Origin": origin, |
| 185 | + "Access-Control-Allow-Methods": ", ".join(self.methods), |
| 186 | + "Access-Control-Max-Age": str(self.max_age), |
| 187 | + }, |
| 188 | + ) |
| 189 | + else: |
| 190 | + return HTTPResponse(status=400) |
0 commit comments