-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.py
84 lines (70 loc) · 2.49 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
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
import logging
import requests
import json
import sys
from typing import Tuple, Dict, Any, Optional
log = logging.getLogger(__name__)
log_stdout = logging.StreamHandler(sys.stdout)
formatter = logging.Formatter('%(asctime)s [%(name)s] '
'%(levelname)s %(message)s')
log_stdout.setFormatter(formatter)
log.addHandler(log_stdout)
class GraphQLClient(object):
"""
A GraphQLClient
"""
def __init__(self, endpoint: str, headers: Optional[Dict[str, str]]=None, retries=0):
self.endpoint = endpoint
self.headers = headers
self.retries = retries
def query(self, query: str, variables: Optional[Dict[str, Any]]=None, operation_name: Optional[str]=None):
return self.send(query, variables, operation_name=operation_name)
def query_from_file(self, file, variables: Optional[Dict[str, Any]]=None, operation_name: Optional[str]=None):
with open(file) as query:
return self.send(query.read(), variables, operation_name=operation_name)
def send(
self,
query: str,
variables: Optional[Dict[str, Any]]=None,
extra_headers: Optional[Dict[str, Any]]=None,
operation_name: Optional[str]=None,
extra_data: Optional[Dict[str, Any]]=None
):
data = {
'query': query,
'variables': variables,
'operationName': operation_name
}
if extra_data:
data.update(extra_data)
headers = {
'Accept': 'application/json',
'Content-Type': 'application/json'
}
if self.headers:
headers.update(self.headers)
if extra_headers:
headers.update(extra_headers)
if not self.retries:
r = requests.post(
self.endpoint,
data=json.dumps(data),
headers=headers
)
return r.json()
retries_count = 0
while retries_count < self.retries:
try:
log.info('*** Retrying GraphQL query.. attempt #: {}'
.format(retries_count))
r = requests.post(
self.endpoint,
data=json.dumps(data),
headers=headers
)
return r.json()
except Exception as e:
log.error('*** GraphQL request failed with exception: {}'
.format(e))
finally:
retries_count += 1