-
Notifications
You must be signed in to change notification settings - Fork 4
/
MtgJsonUtil.py
87 lines (55 loc) · 1.9 KB
/
MtgJsonUtil.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
85
86
87
import logging
import os
import requests
import Model
def changeDirectory() -> None:
# change working directory to directory of file
abspath = os.path.abspath(__file__)
dname = os.path.dirname(abspath)
os.chdir(dname)
def cacheResult(func):
# Function Decorator for Cacheing Results
cache = dict()
def wrapper(*args):
if args in cache:
return cache[args]
result = func(*args)
cache[args] = result
return result
return wrapper
@cacheResult
def getMtgJson() -> str:
# Fetch JSON File from MTGJSON
# url for MTGJSONv5 API
url = "https://mtgjson.com/api/v5/AllPrintings.json"
# need user agent header to avoid 403
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.116 Safari/537.36"
}
logging.info("Fetching MTGJSON File from MTGJSON: " + url)
# send request and recieve response
response = requests.get(url, headers=headers)
# make sure response was successful
if response.status_code == 200:
return response.content.decode("utf-8")
else:
raise Exception(
"Could not get MTGJSON File, STATUS CODE: " + str(response.status_code)
)
def downloadMtgJson() -> None:
# Download JSON File from MTGJSON
logging.info("Saving MTGJSON File")
changeDirectory()
with open("resources/AllPrintings.json", "w") as json_file:
json_file.write(getMtgJson())
def parseMtgJson() -> Model.MtgData:
# Parse JSON File from MTGJSON into local models
return Model.MtgData.fromMtgJson(getMtgJson())
def saveParsedMtgJson() -> None:
# Save parsed data as json file
logging.info("Saving Parsed Data")
changeDirectory()
with open("static/cardData.json", "w") as json_file:
json_file.write(parseMtgJson().toJson())
if __name__ == "__main__":
pass