-
Notifications
You must be signed in to change notification settings - Fork 46
/
Copy pathclient.py
37 lines (30 loc) · 1.14 KB
/
client.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
from six.moves import urllib
import certifi
import ssl
import json
class GraphQLClient:
def __init__(self, endpoint):
self.endpoint = endpoint
self.token = None
self.headername = None
def execute(self, query, variables=None):
return self._send(query, variables)
def inject_token(self, token, headername='Authorization'):
self.token = token
self.headername = headername
def _send(self, query, variables):
data = {'query': query,
'variables': variables}
headers = {'Accept': 'application/json',
'Content-Type': 'application/json'}
if self.token is not None:
headers[self.headername] = '{}'.format(self.token)
req = urllib.request.Request(self.endpoint, json.dumps(data).encode('utf-8'), headers)
try:
context = ssl.create_default_context(cafile=certifi.where())
response = urllib.request.urlopen(req, context=context)
return response.read().decode('utf-8')
except urllib.error.HTTPError as e:
print((e.read()))
print('')
raise e