Add basic smash.gg request function

master
Lertsenem 2020-07-07 00:48:14 +02:00
parent 25a1117caf
commit 660fa7a7a9
1 changed files with 83 additions and 0 deletions

83
lokrez/smashgg.py Normal file
View File

@ -0,0 +1,83 @@
# =============================================================================
API_HOST = "api.smash.gg"
API_ENDPOINT = "gql/alpha"
API_SCHEME = "https"
API_URL = "{scheme}://{host}/{endpoint}".format(
scheme = API_SCHEME,
host = API_HOST,
endpoint = API_ENDPOINT,
)
# =============================================================================
def run_query(
query_name,
variables = {},
query_dir = "queries",
query_extension = "gql",
api_url = API_URL,
log = None,
):
# Load query
query_path = os.path.join(
query_dir,
"{}.{}".format(
query_name,
query_extension,
)
)
query = ""
with open(query_path, 'r') as query_file:
query = query_file.read()
# Build payload
payload = {
"query": query,
"variables": json.dumps(variables),
}
# Build headers
headers = {
"Authorization": "Bearer {token}".format(token = args.token),
"Accept": "application/json",
"Content-Type": "application/json"
}
# Send the query
try:
log.debug("Sending query '{}' with variables:".format(query_name))
log.debug(json.dumps(variables))
except AttributeError:
pass
rv = requests.post(
API_URL,
json.dumps(payload).encode("utf-8"),
headers = headers,
proxies = {"http": args.proxy, "https": args.proxy},
)
try:
rv_json = rv.json()
except Exception as e:
log.error("HTTP request failed")
log.error(e)
log.debug(e, exc_info=True)
log.debug(rv)
# Try to return the data, or log the error and return None
try:
log.debug("query complexity : {}" \
.format(
rv_json["extensions"]["queryComplexity"],
))
return rv_json["data"]
except KeyError:
try:
log.error("GraphQL error")
log.error(rv_json)
except AttributeError:
pass
return None