def parse_body(self): content_type = request.mimetype if content_type == 'application/graphql': return {'query': request.data.decode('utf8')} elif content_type == 'application/json': return load_json_body(request.data.decode('utf8')) elif content_type == 'application/x-www-form-urlencoded': return request.form elif content_type == 'multipart/form-data': # -------------------------------------------------------- # See spec: # https://github.com/jaydenseric/graphql-multipart-request-spec # # When processing multipart/form-data, we need to take # files (from "parts") and place them in the "operations" # data structure (list or dict) according to the "map". # -------------------------------------------------------- operations = load_json_body(request.form['operations']) files_map = load_json_body(request.form['map']) return place_files_in_operations(operations, files_map, request.files) return {}
def parse_body(self): content_type = request.mimetype if content_type == 'multipart/form-data': operations = load_json_body(request.form.get('operations', '{}')) files_map = load_json_body(request.form.get('map', '{}')) return place_files_in_operations(operations, files_map, request.files) return super(FileUploadGraphQLView, self).parse_body()
def parse_body(self): """Handle multipart request spec for multipart/form-data""" content_type = request.mimetype if content_type == "multipart/form-data": operations = load_json_body(request.form.get("operations", "{}")) files_map = load_json_body(request.form.get("map", "{}")) return place_files_in_operations(operations, files_map, request.files) return super(FileUploadGraphQLView, self).parse_body()
def test_batch_supports_post_json_query_with_json_variables(): data = load_json_body( '[{"query":"query helloWho($who: String){ test(who: $who) }",' '"variables":{"who":"Dolly"}}]') results, params = run_http_query(schema, "post", data, batch_enabled=True) assert as_dicts(results) == [{"data": {"test": "Hello Dolly"}}]
def parse_body(self): # We use mimetype here since we don't need the other # information provided by content_type content_type = request.mimetype if content_type == 'application/graphql': return {'query': request.data.decode('utf8')} elif content_type == 'application/json': try: return load_json_body(request.data.decode('utf8')) except UnicodeDecodeError: return load_json_body(request.data.decode('utf8', "backslashreplace")) elif content_type in ('application/x-www-form-urlencoded', 'multipart/form-data'): return request.form return {}
def test_load_json_body_with_variables(): result = load_json_body(""" { "query": "query helloWho($who: String){ test(who: $who) }", "variables": {"who": "Dolly"} } """) assert result["variables"] == {"who": "Dolly"}
def parse_body(request): content_type = request.mimetype if content_type == 'application/graphql': return {'query': request.data.decode('utf8')} elif content_type == 'application/json': return load_json_body(request.data.decode('utf8')) elif content_type in ('application/x-www-form-urlencoded', 'multipart/form-data'): return request.form return {}
def parse_body(self): # We use mimetype here since we don't need the other # information provided by content_type content_type = request.mimetype if content_type == 'application/graphql': return {'query': request.data.decode('utf8')} elif content_type == 'application/json': return load_json_body(request.data.decode('utf8')) elif content_type in ('application/x-www-form-urlencoded', 'multipart/form-data'): return request.form return {}
def parse_body(self, request): """ - """ content_type = self.get_mime_type(request) if content_type == 'application/graphql': return {'query': request.body.decode('utf8')} elif content_type == 'application/json': return load_json_body(request.body.decode('utf8')) elif content_type in ('application/x-www-form-urlencoded', 'multipart/form-data'): return request.form return {}
def _parse_body(self): req = http.request.httprequest # We use mimetype here since we don't need the other # information provided by content_type content_type = req.mimetype if content_type == "application/graphql": return {"query": req.data.decode("utf8")} elif content_type == "application/json": return load_json_body(req.data.decode("utf8")) elif content_type in ( "application/x-www-form-urlencoded", "multipart/form-data", ): return http.request.params return {}
def parse_body(self, request): content_type = self.get_mime_type(request) if content_type == "application/graphql": return {"query": request.body.decode("utf8")} elif content_type == "application/json": return load_json_body(request.body.decode("utf8")) elif content_type in ( "application/x-www-form-urlencoded", "multipart/form-data", ): return request.form return {}
def parse_body(request): # We use mimetype here since we don't need the other # information provided by content_type content_type = request.content_type if content_type == 'application/graphql': return {'query': request.body.decode('utf8')} elif content_type == 'application/json': return load_json_body(request.body.decode('utf8')) elif content_type in ('application/x-www-form-urlencoded', 'multipart/form-data'): return request.params return {}
def parse_body(request): content_type = request.headers.get('content-type', '') if "application/graphql" in content_type: return {"query": request.raw_body.decode("utf8")} elif "application/json" in content_type: return load_json_body(request.raw_body.decode("utf8")) elif "application/x-www-form-urlencoded" in content_type: return dict(parse_qsl(request.raw_body.decode("utf8"))) # TODO: Chalice lacks support for multipart requests # https://github.com/aws/chalice/issues/796 # elif content_type == "multipart/form-data": # return request.json_body return {}
async def parse_body(self): content_type = request.mimetype if content_type == "application/graphql": request_data = await request.data return {"query": request_data.decode("utf8")} elif content_type == "application/json": request_data = await request.data return load_json_body(request_data.decode("utf8")) elif content_type in ( "application/x-www-form-urlencoded", "multipart/form-data", ): request_form = await request.form return request_form return {}
async def parse_body(self) -> Dict: # We use mimetype here since we don't need the other # information provided by content_type content_type = request.mimetype if content_type == "application/graphql": request_data = await request.data return {"query": request_data.decode("utf8")} elif content_type == "application/json": request_data = await request.data return load_json_body(request_data.decode("utf8")) elif content_type in ("application/x-www-form-urlencoded", "multipart/form-data"): request_form = await request.form return request_form return {}
def parse_body(self, request): logger.info('start-parse-body') content_type = request.mimetype query = None if content_type == 'application/graphql': query = {'query': request.data.decode('utf8')} elif content_type == 'application/json': query = load_json_body(request.data.decode('utf8')) elif content_type in ('application/x-www-form-urlencoded', 'multipart/form-data'): query = request.form logger.info('parse-body', query=query, content_type=content_type) logger.info('end-parse-body') return query
def _parse_body(environ): try: content_length = int(environ.get('CONTENT_LENGTH')) except ValueError as e: print('can\'t parse content_length "{}" (ValueError {})'.format( environ.get('CONTENT_LENGTH'), e)) return {} content_type = environ['CONTENT_TYPE'].split(';') body = environ['wsgi.input'].read(content_length) if content_type[0] == 'application/graphql': return {'query': body.decode('utf8')} if content_type[0] in ('application/json', 'text/plain'): return graphql_server.load_json_body(body.decode('utf8')) if content_type[0] == 'application/x-www-form-urlencoded': return dict(parse_qsl(body.decode('utf8'))) else: raise graphql_server.HttpQueryError( 400, 'Content of type "{}" is not supported.'.format(content_type[0]))
async def parse_body(self, request): if request.content_type == 'application/graphql': r_text = await request.text() return {'query': r_text} elif request.content_type == 'application/json': text = await request.text() return load_json_body(text) elif request.content_type in ( 'application/x-www-form-urlencoded', 'multipart/form-data', ): # TODO: seems like a multidict would be more appropriate # than casting it and de-duping variables. Alas, it's what # graphql-python wants. return dict(await request.post()) return {}
async def parse_body(): # We use mimetype here since we don't need the other # information provided by content_type content_type = request.mimetype if content_type == "application/graphql": refined_data = await request.get_data(raw=False) return {"query": refined_data} elif content_type == "application/json": refined_data = await request.get_data(raw=False) return load_json_body(refined_data) elif content_type == "application/x-www-form-urlencoded": return await request.form # TODO: Fix this check elif content_type == "multipart/form-data": return await request.files return {}
def graphql(): request_method = request.method.lower() if request_method == 'get': return render_template( 'graphiql.html', graphiql_version="0.11.11", graphiql_html_title="Cyber GraphiQL", ) # token = requestHandler(request) token = {'permission': ['view:*']} data = load_json_body(request.data.decode()) pretty = request.args.get('pretty') context = {'token': token} execution_results, _ = run_http_query( schema, request_method, data, query_data=request.args, batch_enabled=False, catch=False, backend=None, # Execute options root=None, context=context, middleware=None, ) result, status_code = encode_execution_results( execution_results, is_batch=False, format_error=default_format_error, encode=partial(json_encode, pretty=pretty)) return Response(result, status=status_code, content_type='application/json')
def test_batch_allows_post_with_operation_name(): data = [ dict( query=""" query helloYou { test(who: "You"), ...shared } query helloWorld { test(who: "World"), ...shared } query helloDolly { test(who: "Dolly"), ...shared } fragment shared on QueryRoot { shared: test(who: "Everyone") } """, operationName="helloWorld", ) ] data = load_json_body(json_encode(data)) results, params = run_http_query(schema, "post", data, batch_enabled=True) assert results == [({ "test": "Hello World", "shared": "Hello Everyone" }, None)]
async def parse_body(self, request): content_type = request.content_type # request.text() is the aiohttp equivalent to # request.body.decode("utf8") if content_type == "application/graphql": r_text = await request.text() return {"query": r_text} if content_type == "application/json": text = await request.text() return load_json_body(text) if content_type in ( "application/x-www-form-urlencoded", "multipart/form-data", ): # TODO: seems like a multidict would be more appropriate # than casting it and de-duping variables. Alas, it's what # graphql-python wants. return dict(await request.post()) return {}
def test_batch_allows_post_with_json_encoding(): data = load_json_body('[{"query": "{test}"}]') results, params = run_http_query(schema, "post", data, batch_enabled=True) assert as_dicts(results) == [{"data": {"test": "Hello World"}}]
def test_handles_incomplete_json_bodies(): with raises(HttpQueryError) as exc_info: run_http_query(schema, "post", load_json_body('{"query":')) assert exc_info.value == HttpQueryError(400, "POST body sent invalid JSON.")
def test_load_json_body_as_dict(): result = load_json_body('{"query": "{test}"}') assert result == {"query": "{test}"}
def test_allows_post_with_json_encoding(): result = load_json_body('{"query": "{test}"}') assert result == {"query": "{test}"}
def test_load_invalid_json_body(): with raises(HttpQueryError) as exc_info: load_json_body('{"query":') assert exc_info.value == HttpQueryError(400, "POST body sent invalid JSON.")
def test_load_json_body_as_list(): result = load_json_body('[{"query": "{test}"}]') assert result == [{"query": "{test}"}]
def create_response(event, context, schema=None, enable_batch=False, enable_graphiql=False): """Creates an API-Gateway response object for a graphql request.""" # This is shamelessly adapted from # https://github.com/graphql-python/flask-graphql/blob/master/flask_graphql/graphqlview.py assert event, 'Expects event, got `{}`'.format(event) assert schema, 'Expects schema, got `{}`'.format(schema) request_method = event.get('httpMethod', 'get').lower() # sam-local header keys are inconsistently mixed-cased, so we lower-case em headers = dict((k.lower(), v) for k, v in event.get('headers', {}).items()) body = event.get('body', '') query_data = event.get('queryStringParameters', {}) content_type = headers.get('content-type') if content_type == 'application/graphql': data = {'query': body} elif content_type == 'application/json': data = load_json_body(body) elif content_type in ('application/x-www-form-urlencoded', 'multipart/form-data'): data = urllib.parse.parse_qs(body) else: data = {} wants_graphiql = request_method == 'get' catch_http_errors = wants_graphiql execution_results, all_params = run_http_query( schema, request_method, data, query_data=query_data, batch_enabled=enable_batch, catch=catch_http_errors, # Execute options root_value=None, # TODO: enabling root value context_value=context, middleware=None, # TODO: consider middleware support executor=None, # TODO: consider executor ) result, status_code = encode_execution_results( execution_results, is_batch=isinstance(data, list), format_error=default_format_error, encode=json_encode) if wants_graphiql and enable_graphiql: return { 'statusCode': 200, 'body': TEMPLATE, 'headers': { 'content-type': 'text/html' } } # Else always render json response return { 'statusCode': status_code, 'body': result, 'headers': { 'content-type': 'application/json' } }