forked from hasura/graphql-engine
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgraphql_server.py
643 lines (534 loc) · 22.1 KB
/
graphql_server.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
# -*- coding: utf-8 -*-
from http import HTTPStatus
import graphene
import copy
from webserver import RequestHandler, WebServer, MkHandlers, Response
from enum import Enum
def mkJSONResp(graphql_result):
return Response(HTTPStatus.OK, graphql_result.to_dict(),
{'Content-Type': 'application/json'})
class HelloWorldHandler(RequestHandler):
def get(self, request):
return Response(HTTPStatus.OK, 'hello world')
def post(self, request):
return Response(HTTPStatus.METHOD_NOT_ALLOWED)
class Hello(graphene.ObjectType):
hello = graphene.String(arg=graphene.String(default_value="world"))
def resolve_hello(self, info, arg):
return "Hello " + arg
hello_schema = graphene.Schema(query=Hello, subscription=Hello)
class HelloGraphQL(RequestHandler):
def get(self, request):
return Response(HTTPStatus.METHOD_NOT_ALLOWED)
def post(self, request):
if not request.json:
return Response(HTTPStatus.BAD_REQUEST)
res = hello_schema.execute(request.json['query'])
return mkJSONResp(res)
class User(graphene.ObjectType):
id = graphene.Int()
username = graphene.String()
def __init__(self, id, username):
self.id = id
self.username = username
def resolve_id(self, info):
return self.id
def resolve_username(self, info):
return self.username
@staticmethod
def get_by_id(_id):
xs = list(filter(lambda u: u.id == _id, all_users))
if not xs:
return None
return xs[0]
all_users = [
User(1, 'jane'),
User(2, 'john'),
User(3, 'joe'),
]
class CreateUser(graphene.Mutation):
class Arguments:
id = graphene.Int(required=True)
username = graphene.String(required=True)
ok = graphene.Boolean()
user = graphene.Field(lambda: User)
def mutate(self, info, id, username):
user = User(id, username)
all_users.append(user)
return CreateUser(ok=True, user=user)
class UserQuery(graphene.ObjectType):
user = graphene.Field(User, id=graphene.Int(required=True))
allUsers = graphene.List(User)
def resolve_user(self, info, id):
return User.get_by_id(id)
def resolve_allUsers(self, info):
return all_users
class UserMutation(graphene.ObjectType):
createUser = CreateUser.Field()
user_schema = graphene.Schema(query=UserQuery, mutation=UserMutation)
class UserGraphQL(RequestHandler):
def get(self, req):
return Response(HTTPStatus.METHOD_NOT_ALLOWED)
def post(self, req):
if not req.json:
return Response(HTTPStatus.BAD_REQUEST)
res = user_schema.execute(req.json['query'])
return mkJSONResp(res)
class timestamptz(graphene.types.Scalar):
@staticmethod
def serialize(t):
return "2018-12-20"
@staticmethod
def parse_literal(s):
return "2018-12-20"
@staticmethod
def parse_value(s):
return "2018-12-20"
class Country(graphene.ObjectType):
name = graphene.String()
def __init__(self, name):
self.name = name
def resolve_name(self, info):
return self.name
class CountryQuery(graphene.ObjectType):
country = graphene.Field(Country)
def resolve_country(self, info):
return Country("India")
country_schema = graphene.Schema(query=CountryQuery)
class CountryGraphQL(RequestHandler):
def get(self, req):
return Response(HTTPStatus.METHOD_NOT_ALLOWED)
def post(self, req):
if not req.json:
return Response(HTTPStatus.BAD_REQUEST)
res = country_schema.execute(req.json['query'])
return mkJSONResp(res)
class person(graphene.ObjectType):
id = graphene.Int(required=True)
name = graphene.String()
created = graphene.Field(timestamptz)
def resolve_id(self, info):
return 42
def resolve_name(self, info):
return 'Arthur Dent'
def resolve_created(self, info):
return '2018-12-20'
class PersonQuery(graphene.ObjectType):
person_ = graphene.Field(person)
def resolve_person_(self, info):
return person()
person_schema = graphene.Schema(query=PersonQuery)
class PersonGraphQL(RequestHandler):
def get(self, req):
return Response(HTTPStatus.METHOD_NOT_ALLOWED)
def post(self, req):
if not req.json:
return Response(HTTPStatus.BAD_REQUEST)
res = person_schema.execute(req.json['query'])
return mkJSONResp(res)
#GraphQL server with interfaces
class Character(graphene.Interface):
id = graphene.ID(required=True)
name = graphene.String(required=True)
def __init__(self, id, name):
self.id = id
self.name = name
class Human(graphene.ObjectType):
class Meta:
interfaces = (Character, )
home_planet = graphene.String()
def __init__(self, home_planet, character):
self.home_planet = home_planet
self.character = character
def resolve_id(self, info):
return self.character.id
def resolve_name(self, info):
return self.character.name
def refolve_primary_function(self, info):
return self.home_planet
class Droid(graphene.ObjectType):
class Meta:
interfaces = (Character, )
primary_function = graphene.String()
def __init__(self, primary_function, character):
self.primary_function = primary_function
self.character = character
def resolve_id(self, info):
return self.character.id
def resolve_name(self, info):
return self.character.name
def resolve_primary_function(self, info):
return self.primary_function
class CharacterSearchResult(graphene.Union):
class Meta:
types = (Human,Droid)
all_characters = {
4: Droid("Astromech", Character(1,'R2-D2')),
5: Human("Tatooine", Character(2, "Luke Skywalker")),
}
character_search_results = {
1: Droid("Astromech", Character(6,'R2-D2')),
2: Human("Tatooine", Character(7, "Luke Skywalker")),
}
class CharacterIFaceQuery(graphene.ObjectType):
hero = graphene.Field(
Character,
required=False,
episode=graphene.Int(required=True)
)
def resolve_hero(_, info, episode):
return all_characters.get(episode)
schema = graphene.Schema(query=CharacterIFaceQuery, types=[Human, Droid])
character_interface_schema = graphene.Schema(query=CharacterIFaceQuery, types=[Human, Droid])
class CharacterInterfaceGraphQL(RequestHandler):
def get(self, req):
return Response(HTTPStatus.METHOD_NOT_ALLOWED)
def post(self, req):
if not req.json:
return Response(HTTPStatus.BAD_REQUEST)
res = character_interface_schema.execute(req.json['query'])
return mkJSONResp(res)
class InterfaceGraphQLErrEmptyFieldList(RequestHandler):
def get(self, req):
return Response(HTTPStatus.METHOD_NOT_ALLOWED)
def post(self, req):
if not req.json:
return Response(HTTPStatus.BAD_REQUEST)
res = character_interface_schema.execute(req.json['query'])
respDict = res.to_dict()
typesList = respDict.get('data',{}).get('__schema',{}).get('types',None)
if typesList is not None:
for t in typesList:
if t['kind'] == 'INTERFACE':
t['fields'] = []
return Response(HTTPStatus.OK, respDict,
{'Content-Type': 'application/json'})
class InterfaceGraphQLErrUnknownInterface(RequestHandler):
def get(self, req):
return Response(HTTPStatus.METHOD_NOT_ALLOWED)
def post(self, req):
if not req.json:
return Response(HTTPStatus.BAD_REQUEST)
res = character_interface_schema.execute(req.json['query'])
respDict = res.to_dict()
typesList = respDict.get('data',{}).get('__schema',{}).get('types',None)
if typesList is not None:
for t in typesList:
if t['kind'] == 'OBJECT' and t['name'] == 'Droid':
t['interfaces'][0]['name'] = 'UnknownIFace'
return Response(HTTPStatus.OK, respDict,
{'Content-Type': 'application/json'})
class InterfaceGraphQLErrWrongFieldType(RequestHandler):
def get(self, req):
return Response(HTTPStatus.METHOD_NOT_ALLOWED)
def post(self, req):
if not req.json:
return Response(HTTPStatus.BAD_REQUEST)
res = character_interface_schema.execute(req.json['query'])
respDict = res.to_dict()
typesList = respDict.get('data',{}).get('__schema',{}).get('types',None)
if typesList is not None:
for t in typesList:
#Remove id field from Droid
if t['kind'] == 'OBJECT' and t['name'] == 'Droid':
for f in t['fields'].copy():
if f['name'] == 'id':
f['type']['ofType']['name'] = 'String'
return Response(HTTPStatus.OK, respDict,
{'Content-Type': 'application/json'})
class InterfaceGraphQLErrMissingField(RequestHandler):
def get(self, req):
return Response(HTTPStatus.METHOD_NOT_ALLOWED)
def post(self, req):
if not req.json:
return Response(HTTPStatus.BAD_REQUEST)
res = character_interface_schema.execute(req.json['query'])
respDict = res.to_dict()
typesList = respDict.get('data',{}).get('__schema',{}).get('types',None)
if typesList is not None:
for t in typesList:
#Remove id field from Droid
if t['kind'] == 'OBJECT' and t['name'] == 'Droid':
for f in t['fields'].copy():
if f['name'] == 'id':
t['fields'].remove(f)
return Response(HTTPStatus.OK, respDict,
{'Content-Type': 'application/json'})
ifaceArg = {
"name": "ifaceArg",
"description": None,
"type": {
"kind": "NON_NULL",
"name": None,
"ofType": {
"kind": "SCALAR",
"name": "Int",
"ofType": None
}
},
"defaultValue": None
}
class InterfaceGraphQLErrMissingArg(RequestHandler):
def get(self, req):
return Response(HTTPStatus.METHOD_NOT_ALLOWED)
def post(self, req):
if not req.json:
return Response(HTTPStatus.BAD_REQUEST)
res = character_interface_schema.execute(req.json['query'])
respDict = res.to_dict()
typesList = respDict.get('data',{}).get('__schema',{}).get('types',None)
if typesList is not None:
for t in typesList:
if t['kind'] == 'INTERFACE':
for f in t['fields']:
if f['name'] == 'id':
f['args'].append(ifaceArg)
return Response(HTTPStatus.OK, respDict,
{'Content-Type': 'application/json'})
class InterfaceGraphQLErrWrongArgType(RequestHandler):
def get(self, req):
return Response(HTTPStatus.METHOD_NOT_ALLOWED)
def post(self, req):
if not req.json:
return Response(HTTPStatus.BAD_REQUEST)
res = character_interface_schema.execute(req.json['query'])
respDict = res.to_dict()
objArg = copy.deepcopy(ifaceArg)
objArg['type']['ofType']['name'] = 'String'
typesList = respDict.get('data',{}).get('__schema',{}).get('types',None)
if typesList is not None:
for t in filter(lambda ty : ty['kind'] == 'INTERFACE', typesList):
for f in filter(lambda fld: fld['name'] == 'id', t['fields']):
f['args'].append(ifaceArg)
for t in filter(lambda ty: ty['name'] in ['Droid','Human'], typesList):
for f in filter(lambda fld: fld['name'] == 'id', t['fields']):
f['args'].append(ifaceArg if t['name'] == 'Droid' else objArg)
return Response(HTTPStatus.OK, respDict,
{'Content-Type': 'application/json'})
class InterfaceGraphQLErrExtraNonNullArg(RequestHandler):
def get(self, req):
return Response(HTTPStatus.METHOD_NOT_ALLOWED)
def post(self, req):
if not req.json:
return Response(HTTPStatus.BAD_REQUEST)
res = character_interface_schema.execute(req.json['query'])
respDict = res.to_dict()
typesList = respDict.get('data',{}).get('__schema',{}).get('types',None)
if typesList is not None:
for t in typesList:
if t['kind'] == 'OBJECT' and t['name'] == 'Droid':
for f in t['fields']:
if f['name'] == 'id':
f['args'].append({
"name": "extraArg",
"description": None,
"type": {
"kind": "NON_NULL",
"name": None,
"ofType": {
"kind": "SCALAR",
"name": "Int",
"ofType": None
}
},
"defaultValue": None
})
return Response(HTTPStatus.OK, respDict,
{'Content-Type': 'application/json'})
#GraphQL server involving union type
class UnionQuery(graphene.ObjectType):
search = graphene.Field(
CharacterSearchResult,
required=False,
episode=graphene.Int(required=True)
)
def resolve_search(_, info, episode):
return character_search_results.get(episode)
union_schema = graphene.Schema(query=UnionQuery, types=[Human, Droid])
class UnionGraphQL(RequestHandler):
def get(self, req):
return Response(HTTPStatus.METHOD_NOT_ALLOWED)
def post(self, req):
if not req.json:
return Response(HTTPStatus.BAD_REQUEST)
res = union_schema.execute(req.json['query'])
return mkJSONResp(res)
class UnionGraphQLSchemaErrUnknownTypes(RequestHandler):
def get(self, req):
return Response(HTTPStatus.METHOD_NOT_ALLOWED)
def post(self, req):
if not req.json:
return Response(HTTPStatus.BAD_REQUEST)
res = union_schema.execute(req.json['query'])
respDict = res.to_dict()
typesList = respDict.get('data',{}).get('__schema',{}).get('types',None)
if typesList is not None:
for t in typesList:
if t['kind'] == 'UNION':
for i, p in enumerate(t['possibleTypes']):
p['name'] = 'Unknown' + str(i)
return Response(HTTPStatus.OK, respDict,
{'Content-Type': 'application/json'})
class UnionGraphQLSchemaErrSubTypeInterface(RequestHandler):
def get(self, req):
return Response(HTTPStatus.METHOD_NOT_ALLOWED)
def post(self, req):
if not req.json:
return Response(HTTPStatus.BAD_REQUEST)
res = union_schema.execute(req.json['query'])
respDict = res.to_dict()
typesList = respDict.get('data',{}).get('__schema',{}).get('types',None)
if typesList is not None:
for t in typesList:
if t['kind'] == 'UNION':
for p in t['possibleTypes']:
p['name'] = 'Character'
return Response(HTTPStatus.OK, respDict,
{'Content-Type': 'application/json'})
class UnionGraphQLSchemaErrNoMemberTypes(RequestHandler):
def get(self, req):
return Response(HTTPStatus.METHOD_NOT_ALLOWED)
def post(self, req):
if not req.json:
return Response(HTTPStatus.BAD_REQUEST)
res = union_schema.execute(req.json['query'])
respDict = res.to_dict()
typesList = respDict.get('data',{}).get('__schema',{}).get('types',None)
if typesList is not None:
for t in typesList:
if t['kind'] == 'UNION':
t['possibleTypes'] = []
return Response(HTTPStatus.OK, respDict,
{'Content-Type': 'application/json'})
class UnionGraphQLSchemaErrWrappedType(RequestHandler):
def get(self, req):
return Response(HTTPStatus.METHOD_NOT_ALLOWED)
def post(self, req):
if not req.json:
return Response(HTTPStatus.BAD_REQUEST)
res = union_schema.execute(req.json['query'])
respDict = res.to_dict()
typesList = respDict.get('data',{}).get('__schema',{}).get('types',None)
if typesList is not None:
for t in typesList:
if t['kind'] == 'UNION':
for i, p in enumerate(t['possibleTypes']):
t['possibleTypes'][i] = {
"kind": "NON_NULL",
"name": None,
"ofType": p
}
return Response(HTTPStatus.OK, respDict,
{'Content-Type': 'application/json'})
#GraphQL server with default values for inputTypes
class InpObjType(graphene.InputObjectType):
@classmethod
def default(cls):
meta = cls._meta
fields = meta.fields
default_fields = {name: field.default_value for name, field in fields.items()}
container = meta.container
return container(**default_fields)
class SizeObj(graphene.ObjectType):
width = graphene.Int()
height = graphene.Float()
shape = graphene.String()
hasTag = graphene.Boolean()
class Color(Enum):
RED = 1
GREEN = 2
BLUE = 3
GQColorEnum = graphene.Enum.from_enum(Color)
class SizeInput(InpObjType):
width = graphene.Int(default_value=100)
height = graphene.Float(default_value=100.1)
shape = graphene.String(default_value="cube")
hasTag = graphene.Boolean(default_value=False)
def asSizeObj(self):
return SizeObj(width=self.width, height=self.height, shape=self.shape, hasTag=self.hasTag)
class Echo(graphene.ObjectType):
intFld = graphene.Int()
listFld = graphene.List(graphene.String)
objFld = graphene.Field(SizeObj)
enumFld = graphene.Field(GQColorEnum)
class EchoQuery(graphene.ObjectType):
echo = graphene.Field(
Echo,
int_input=graphene.Int( default_value=1234),
list_input=graphene.Argument(graphene.List(graphene.String), default_value=["hi","there"]),
obj_input=graphene.Argument(SizeInput, default_value=SizeInput.default()),
enum_input=graphene.Argument(GQColorEnum, default_value=GQColorEnum.RED.name),
)
def resolve_echo(self, info, int_input, list_input, obj_input, enum_input):
#print (int_input, list_input, obj_input)
return Echo(intFld=int_input, listFld=list_input, objFld=obj_input, enumFld=enum_input)
echo_schema = graphene.Schema(query=EchoQuery)
class EchoGraphQL(RequestHandler):
def get(self, req):
return Response(HTTPStatus.METHOD_NOT_ALLOWED)
def post(self, req):
if not req.json:
return Response(HTTPStatus.BAD_REQUEST)
res = echo_schema.execute(req.json['query'])
respDict = res.to_dict()
typesList = respDict.get('data',{}).get('__schema',{}).get('types',None)
#Hack around enum default_value serialization issue: https://github.com/graphql-python/graphql-core/issues/166
if typesList is not None:
for t in filter(lambda ty: ty['name'] == 'EchoQuery', typesList):
for f in filter(lambda fld: fld['name'] == 'echo', t['fields']):
for a in filter(lambda arg: arg['name'] == 'enumInput', f['args']):
a['defaultValue'] = 'RED'
return Response(HTTPStatus.OK, respDict,
{'Content-Type': 'application/json'})
class HeaderTest(graphene.ObjectType):
wassup = graphene.String(arg=graphene.String(default_value='world'))
def resolve_wassup(self, info, arg):
headers = info.context
print('recvd headers: ', headers)
if not (headers.get_all('x-hasura-test') == ['abcd'] and
headers.get_all('x-hasura-role') == ['user'] and
headers.get_all('x-hasura-user-id') == ['abcd1234'] and
headers.get_all('content-type') == ['application/json'] and
headers.get_all('Authorization') == ['Bearer abcdef']):
raise Exception('headers dont match')
return "Hello " + arg
header_test_schema = graphene.Schema(query=HeaderTest)
class HeaderTestGraphQL(RequestHandler):
def get(self, request):
return Response(HTTPStatus.METHOD_NOT_ALLOWED)
def post(self, request):
if not request.json:
return Response(HTTPStatus.BAD_REQUEST)
res = header_test_schema.execute(request.json['query'],
context=request.headers)
return mkJSONResp(res)
handlers = MkHandlers({
'/hello': HelloWorldHandler,
'/hello-graphql': HelloGraphQL,
'/user-graphql': UserGraphQL,
'/country-graphql': CountryGraphQL,
'/character-iface-graphql' : CharacterInterfaceGraphQL,
'/iface-graphql-err-empty-field-list' : InterfaceGraphQLErrEmptyFieldList,
'/iface-graphql-err-unknown-iface' : InterfaceGraphQLErrUnknownInterface,
'/iface-graphql-err-missing-field' : InterfaceGraphQLErrMissingField,
'/iface-graphql-err-wrong-field-type' : InterfaceGraphQLErrWrongFieldType,
'/iface-graphql-err-missing-arg' : InterfaceGraphQLErrMissingArg,
'/iface-graphql-err-wrong-arg-type' : InterfaceGraphQLErrWrongArgType,
'/iface-graphql-err-extra-non-null-arg' : InterfaceGraphQLErrExtraNonNullArg,
'/union-graphql' : UnionGraphQL,
'/union-graphql-err-unknown-types' : UnionGraphQLSchemaErrUnknownTypes,
'/union-graphql-err-subtype-iface' : UnionGraphQLSchemaErrSubTypeInterface,
'/union-graphql-err-no-member-types' : UnionGraphQLSchemaErrNoMemberTypes,
'/union-graphql-err-wrapped-type' : UnionGraphQLSchemaErrWrappedType,
'/default-value-echo-graphql' : EchoGraphQL,
'/person-graphql': PersonGraphQL,
'/header-graphql': HeaderTestGraphQL
})
def create_server(host='127.0.0.1', port=5000):
return WebServer((host, port), handlers)
def stop_server(server):
server.shutdown()
server.server_close()
if __name__ == '__main__':
s = create_server(host='0.0.0.0')
s.serve_forever()