Created
October 29, 2020 17:50
-
-
Save jimbol/f2841932537b6d36698e98adba2e2894 to your computer and use it in GitHub Desktop.
use_cache.py
This file contains hidden or 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
def get_bucket(): | |
return 'your bucket key' | |
def get_key(): | |
return 'get cache key' | |
def use_cache(f): | |
@wraps(f) | |
def decorated_function(*args, **kwargs): | |
client = boto3.client('s3') | |
bucket = get_bucket() | |
key = get_key() | |
try: | |
result = client.get_object( | |
Bucket=bucket, | |
Key=key, | |
) | |
return json.loads(result['Body'].read()) | |
except: | |
print('Could not fetch ' + key + ' from S3: ' + bucket) | |
results = f(*args, **kwargs) | |
if 'status' in results.keys() and results['status'] != 200: | |
return results | |
try: | |
results_bytes = json.dumps(results).encode('utf-8') | |
client.put_object( | |
ACL='private', | |
Body=results_bytes, | |
Bucket=bucket, | |
Key=key, | |
) | |
except: | |
print('Could not put ' + key + ' to S3: ' + bucket) | |
return results | |
return decorated_function |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment