123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102 |
- import requests
- class GraphQLClient:
- # Constructeur, demande l'url de l'api
- def __init__(self, url):
- self.url = url
- try:
- requests.get(self.url)
- except:
- raise self.__BadURLException('bad url: ' + self.url)
-
- # Création d'une query
- def query(self, graphQlQuery, variables = None):
- query = self.__GraphQLQuery()
- return query.set(self.url, graphQlQuery, variables)
-
- def isError(self, result):
- query = self.__GraphQLQuery()
- return query.isError(result)
-
- # Class privée pour gérer les query
- class __GraphQLQuery:
- __set = False
- last = None
- url = None
- query = None
- variables = None
-
- # Verif que l'objet est bien set
- def __isSet(self):
- if(not(self.__set)):
- raise ValueError('Object attributes are not set')
-
- # Constructeur (le constructeur par defaut doit être gardé)
- def set(self, url, query, var = None):
- self.url = url
- self.query = query
- self.variables = var
- self.__set = True
- return self
-
- # Execute la query
- def execute(self, returnSelf = True):
- self.__isSet()
- # Make the HTTP Api request
- self.last = requests.post(self.url, json={'query': self.query, 'variables': self.variables})
- if returnSelf:
- return self
- else:
- return self.last.status_code
-
- def get(self):
- if self.last == None:
- return None
- elif self.last.status_code == 200:
- return self.data()
- elif self.last.status_code >= 400 and self.last.status_code < 500:
- return self.error()
- else:
- return self.last.text
-
- def data(self):
- if self.last == None or self.last.status_code != 200:
- return None
- else:
- return self.last.json()['data']
-
- def error(self):
- if self.last == None or self.last.status_code < 400 or self.last.status_code >= 500:
- return None
- else:
- if len(self.last.json()['errors']) == 1:
- return self.__GraphQLError(self.last.json()['errors'][0])
- errors = []
- for error in self.last.json()['errors']:
- errors.append(self.__GraphQLError(error))
- return errors
-
- def isError(self, result):
- return type(result) is self.__GraphQLError
-
- # Clas privée de query pour gérer les erreurs
- class __GraphQLError:
- # Constructeur
- def __init__(self, error):
- self.code = error['status']
- self.message = error['message']
- if error.get('locations') != None:
- self.line = error['locations'][0]['line']
- self.column = error['locations'][0]['column']
- else:
- self.line = 'Unknown'
- self.column = 'Unknown'
-
- # toString
- def __str__(self):
- return 'Status code: ' + str(self.code) + ', Line: ' + str(self.line) + ', Column: ' + str(self.column) + ', Message: ' + self.message
-
-
- # Class privée pour gérer les mauvaise url
- class __BadURLException(Exception):
- pass
|