-
Notifications
You must be signed in to change notification settings - Fork 0
/
bmaker.py
70 lines (61 loc) · 2.01 KB
/
bmaker.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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
"""
N.B. This class is related to the first version of this lambda function,
where the attachments were saved on a S3 bucket.
In the current version, this is not used anymore.
"""
import os
import mimetypes
import re
import boto3
from botocore import exceptions
import datetime
class BucketMaker():
def __init__(self, company_name, bucket_name, bucket_region):
self.__folder_name = self.__get_folder_name(company_name)
self.__client = boto3.client('s3')
self.__bucket_name = bucket_name
self.__bucket_region = bucket_region
def __get_folder_name(self, company_name):
"""
Return the folder name
"""
return company_name.lower().title()+"/"+str(datetime.datetime.now().year)+"/"+datetime.datetime.now().strftime("%B")+"/"
def __bucket_exists(self):
"""
Check if bucket exists
"""
try:
self.__client.head_bucket(Bucket=self.__bucket_name)
return True
except exceptions.ClientError:
return False
def __create_bucket(self):
"""
Create the bucket
"""
self.__client.create_bucket(
Bucket=self.__bucket_name,
CreateBucketConfiguration={
'LocationConstraint':self.__bucket_region
}
)
def __upload(self, file):
"""
Upload file in the bucket
"""
mimetypes.init()
mime_type = mimetypes.guess_type(file)
filename = re.sub(r'\/tmp\/', '', file)
if mime_type[0] is not None:
self.__client.upload_file(file,
self.__bucket_name,
self.__folder_name+filename,
ExtraArgs={'ContentType':mime_type[0]})
def archive(self, file):
"""
Creates the bucket if it doesn't exist
and uplads the file.
"""
if not self.__bucket_exists():
self.__create_bucket()
self.__upload(file)