-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
167 lines (147 loc) · 4.96 KB
/
main.py
File metadata and controls
167 lines (147 loc) · 4.96 KB
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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
from fastapi import FastAPI, Request, Response, status
from fastapi.responses import JSONResponse
from fastapi.templating import Jinja2Templates
from fastapi.staticfiles import StaticFiles
import boto3
from botocore.exceptions import ClientError
import os
import configparser
import logging
import io
import zipfile
from typing import Optional
config = configparser.ConfigParser()
config.read("config.ini")
aws_region = config["DEFAULT"]["AWS_REGION"]
target_bucket = config["DEFAULT"]["BUCKET_NAME"]
s3 = boto3.client("s3", region_name=aws_region)
app = FastAPI()
app.mount(
"/_next/static", StaticFiles(directory="ui/.next/static"), name="static"
)
templates = Jinja2Templates(directory="ui/.next/serverless/pages")
def _get_metadata():
file = s3.get_object(Bucket=target_bucket, Key="metadata.txt")
contents = file["Body"].iter_lines()
metadata = dict()
attributes = next(contents).decode("utf-8").split("\t")
for remaining in contents:
vals = remaining.decode("utf-8").split("\t")
key = vals[0]
metadata[key] = dict()
for idx, val in enumerate(attributes):
if idx == 0:
metadata[key]["imageName"] = vals[0]
else:
metadata[key][val] = vals[idx]
return metadata
@app.get("/")
def root(request: Request):
return templates.TemplateResponse("index.html", {"request": request})
@app.get("/api/v1/files")
def get_files(start_dt: Optional[str] = None, end_dt: Optional[str] = None):
"""
List all files.
"""
try:
resp = [v for v in _get_metadata().values()]
if start_dt and end_dt:
return list(
map(
lambda x: x["imageName"],
filter(
lambda x: x["dateTime"] <= end_dt and x["dateTime"] >= start_dt,
resp,
),
)
)
elif start_dt:
return list(
map(
lambda x: x["imageName"],
filter(lambda x: x["dateTime"] >= start_dt, resp),
)
)
elif end_dt:
return list(
map(
lambda x: x["imageName"],
filter(lambda x: x["dateTime"] <= end_dt, resp),
)
)
else:
return [file for file in resp]
except ClientError as ce:
logging.error(ce)
return JSONResponse(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
content={
"error": f"{ce.response['Error']['Code']}",
"message": f"{ce.response['Error']['Message']}",
},
)
@app.get("/api/v1/file/{file_id}")
def get_file(file_id: str):
"""
Get metadata for a file with file_id.
"""
try:
resp = _get_metadata()
return resp[file_id]
except ClientError as ce:
logging.error(ce)
return JSONResponse(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
content={
"error": f"{ce.response['Error']['Code']}",
"message": f"{ce.response['Error']['Message']}",
},
)
@app.get("/api/v1/download")
def download_all():
"""
Downloads a zip file of all files.
"""
try:
zip_buffer = io.BytesIO()
with zipfile.ZipFile(zip_buffer, "a", zipfile.ZIP_DEFLATED, False) as zipper:
all_files = s3.list_objects_v2(Bucket=target_bucket)
for s3Key in list(map(lambda x: x["Key"], all_files["Contents"])):
infile_object = s3.get_object(Bucket=target_bucket, Key=s3Key)
infile_content = infile_object["Body"].read()
zipper.writestr(s3Key, infile_content)
return Response(
content=zip_buffer.getvalue(),
media_type="application/zip",
headers={"Content-Disposition": f"attachment;filename=All-Files.zip"},
)
except ClientError as ce:
logging.error(ce)
return JSONResponse(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
content={
"error": f"{ce.response['Error']['Code']}",
"message": f"{ce.response['Error']['Message']}",
},
)
@app.get("/api/v1/download/{file_id}")
def download_file(file_id: str):
"""
Download a specific file with file_id.
"""
try:
file = s3.get_object(Bucket=target_bucket, Key=file_id)
return Response(
content=file["Body"].read(),
media_type=file["ContentType"],
headers={"Content-Disposition": f"attachment;filename={file_id}"},
)
except ClientError as ce:
logging.error(ce)
return JSONResponse(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
content={
"error": f"{ce.response['Error']['Code']}",
"message": f"{ce.response['Error']['Message']}",
},
)