I have some code that is intended to be a package (so that it can be accessed via import cachejson).
Here is the code for the package:
The update variable is whether the user wants to update the file or retrieve the older file? (True means use the file should be overwritten, false means it should be used.)
import requests
import json
import os
folder_name = 'json_cache'
class cj(object):
def __init__(self, url, update=False):
self.url = url
self.filename = self.make_filename() + '.json'
self.update = update
self.make_cache_directory()
def download(self):
return requests.get(URL).json()
def save(self):
# print('{}/{}'.format(folder_name, self.filename))
with open('{}/{}'.format(folder_name, self.filename), 'w') as out:
json.dump(self.raw, out)
def make_cache_directory(self):
try:
os.makedirs(folder_name)
print('new cache folder...')
except FileExistsError as e:
pass
def make_filename(self): # make the filename for the saved json file
new = self.url.replace('/', '=')
new = new.replace(':', '-')
return new
def file_exists(self): # see if the file already exists
return os.path.isfile('{}/{}'.format(folder_name, self.filename))
def load(self): # json from file to python obj
with open('{}/{}'.format(folder_name, self.filename)) as file:
return json.load(file)
def json(self):
if self.file_exists() and self.update == False:
print('file exists...')
return self.load()
else:
self.raw = self.download()
self.save()
print('new file saved...')
return self.raw
Then the usage would be something like:
repos = cachejson.cj(APIURL).json()
How can I improve this code to make it a better package?