all repos — myprecious @ 5acbe103e332613faff043d102cc215dc13380d2

A lightweight web service to backup precious game saves.

myprecious/GamesApi.py (view raw)

 1from igdb.wrapper import IGDBWrapper
 2from urllib.parse import urlencode
 3from contextlib import suppress
 4import Constants as c
 5import requests
 6import os, json
 7
 8def get_token():
 9    url = f"{ c.AUTH_URL }?{ urlencode(c.AUTH_URL_PARAMS) }"
10    response = requests.request("POST", url).json()
11    return response['access_token']
12
13def construct_wrapper(token):
14    return IGDBWrapper(c.CLIENT_ID, token)
15
16def get_wrapper():
17    with suppress(FileExistsError):
18        os.makedirs(c.BASE_DIRECTORY)
19    try:
20        with open(c.TOKEN_PATH, "r", encoding="utf-8") as in_file:
21            token = in_file.readline()
22        # we got a token, it may be expired
23        w = construct_wrapper(token)
24        try:
25            w.api_request("games", "limit 1;")
26        except requests.exceptions.HTTPError as e:
27            if e.response.status_code == 401:
28                print("Invalid token. Getting a new one.")
29                raise FileNotFoundError
30            print("API connection error.")
31            exit(1)
32        return w # valid token
33    except FileNotFoundError:
34        # invalid or missing token
35        token = get_token()
36        with open(c.TOKEN_PATH, "w", encoding="utf-8") as out_file:
37            out_file.write(token)
38        return construct_wrapper(token)
39
40def req(endpoint, query):
41    result_bs = wrapper.api_request(endpoint, query)
42    result_str = result_bs.decode("utf-8")
43    return json.loads(result_str)
44
45def search_game(query: str):
46    cleaned_up_query = query.replace('"', '').replace("'","")
47    return req("games", f'search "{ cleaned_up_query }"; fields *, cover.*, platforms.*;')
48
49wrapper = get_wrapper()