Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
def write_to_cache(db_name, data):
# cache is in: ~/safety/cache.json
# and has the following form:
# {
# "insecure.json": {
# "cached_at": 12345678
# "db": {}
# },
# "insecure_full.json": {
# "cached_at": 12345678
# "db": {}
# },
# }
if not os.path.exists(os.path.dirname(CACHE_FILE)):
try:
os.makedirs(os.path.dirname(CACHE_FILE))
with open(CACHE_FILE, "w") as _:
_.write(json.dumps({}))
except OSError as exc: # Guard against race condition
if exc.errno != errno.EEXIST:
raise
with open(CACHE_FILE, "r") as f:
try:
cache = json.loads(f.read())
except json.JSONDecodeError:
cache = {}
with open(CACHE_FILE, "w") as f:
cache[db_name] = {
def get_from_cache(db_name):
if os.path.exists(CACHE_FILE):
with open(CACHE_FILE) as f:
try:
data = json.loads(f.read())
if db_name in data:
if "cached_at" in data[db_name]:
if data[db_name]["cached_at"] + CACHE_VALID_SECONDS > time.time():
return data[db_name]["db"]
except json.JSONDecodeError:
pass
return False
# },
# "insecure_full.json": {
# "cached_at": 12345678
# "db": {}
# },
# }
if not os.path.exists(os.path.dirname(CACHE_FILE)):
try:
os.makedirs(os.path.dirname(CACHE_FILE))
with open(CACHE_FILE, "w") as _:
_.write(json.dumps({}))
except OSError as exc: # Guard against race condition
if exc.errno != errno.EEXIST:
raise
with open(CACHE_FILE, "r") as f:
try:
cache = json.loads(f.read())
except json.JSONDecodeError:
cache = {}
with open(CACHE_FILE, "w") as f:
cache[db_name] = {
"cached_at": time.time(),
"db": data
}
f.write(json.dumps(cache))
if not os.path.exists(os.path.dirname(CACHE_FILE)):
try:
os.makedirs(os.path.dirname(CACHE_FILE))
with open(CACHE_FILE, "w") as _:
_.write(json.dumps({}))
except OSError as exc: # Guard against race condition
if exc.errno != errno.EEXIST:
raise
with open(CACHE_FILE, "r") as f:
try:
cache = json.loads(f.read())
except json.JSONDecodeError:
cache = {}
with open(CACHE_FILE, "w") as f:
cache[db_name] = {
"cached_at": time.time(),
"db": data
}
f.write(json.dumps(cache))