Last active
November 2, 2023 02:07
-
-
Save andrewmatte/9dae67008681ced2bb74ef46c0e818df to your computer and use it in GitHub Desktop.
Better than accessing the hard drive every time
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
"""This class provides a way to access to most up-to-date version of a file without reading the whole file from the harddrive. | |
It does this by first reading when the file was last updated from the filesystem and only reads the whole file if the | |
file has been updated since. This is more useful for large files and works because RAM has faster access than the harddrive.""" | |
from datetime import datetime | |
import os | |
class CachedFile: | |
def __init__(self, filename): | |
self.filename = filename, | |
self.updated_when = datetime.now().timestamp() | |
self.blob = self.get_by_filename() | |
def get_value(self): | |
last_updated = self.check_updated() | |
if last_updated == False: | |
return '{}' | |
if last_updated > self.updated_when: | |
value = self.get_by_filename() | |
self.updated_when = datetime.now().timestamp() | |
return value | |
return self.blob | |
def get_by_filename(self): | |
return open(self.filename[0], 'r').read() | |
def check_updated(self): | |
try: | |
return os.path.getmtime(self.filename[0]) | |
except: | |
return False |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment