-
Notifications
You must be signed in to change notification settings - Fork 0
/
cloud.py
54 lines (44 loc) · 1.27 KB
/
cloud.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
import boto3
import json
import os
from datetime import datetime, timedelta
client = boto3.client("s3")
BUCKET = os.environ["BUCKET"]
REGION = os.environ["REGION"]
FILE_NAME = "data.json"
def upload(data):
try:
client.create_bucket(
Bucket=BUCKET,
CreateBucketConfiguration={ "LocationConstraint": REGION })
except client.exceptions.BucketAlreadyOwnedByYou:
pass
except client.exceptions.BucketAlreadyExists:
print("BucketAlreadyExists: review your AWS credentials")
raise
client.put_object(
Bucket=BUCKET,
Key=FILE_NAME,
Body=json.dumps(data),
Expires=datetime.utcnow() + timedelta(days=15)) # serve fresh data only
def temporal_url():
if not object_exists(FILE_NAME):
return None
url = client.generate_presigned_url(
ClientMethod="get_object",
Params={
"Bucket": BUCKET,
"Key": FILE_NAME
},
ExpiresIn=300
)
return url
def object_exists(path):
try:
boto3.resource('s3').Object(BUCKET, path).load() # load = HEAD request
except client.exceptions.ClientError as e:
if e.response['Error']['Code'] == "404":
return False
else:
raise
return True