-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
257 lines (207 loc) · 6.23 KB
/
main.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
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
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
"""
Module for the main application.
"""
from datetime import datetime
import json
import os
from enum import Enum
from pydantic import BaseModel
from pydantic import Json
from pydantic import constr
from pydantic import validator
from pydantic.typing import Literal
from typing import List
from typing import Optional
from fastapi import APIRouter
from fastapi import Depends
from fastapi import FastAPI
from fastapi import HTTPException
from fastapi.security import APIKeyHeader
from models import database, db_session, MediaAsset
X_API_KEY = APIKeyHeader(name='X-API-Key')
app = FastAPI()
@app.on_event('startup')
def startup():
"""
Initialize the database.
"""
database.generate_mapping(create_tables=True)
media_lake_router = APIRouter()
class MediaModel(BaseModel):
"""
Validation model for the media field in media asset.
"""
payload: Optional[str]
sourceUrl: Optional[str]
sourceUrlValidUntil: Optional[datetime]
@validator('payload')
def validate_payload(cls, value, values, **kwargs):
if value:
if values.get('sourceUrl') or values.get('sourceUrlValidUntil'):
raise ValueError(
'Only 1 of payload or sourceUrl/sourceUrlValidUntil may be '
'entered at the same time.'
)
return value
class MediaAssetQueryModel(BaseModel):
"""
Query model for searching Media Asset model.
"""
gtin: Optional[str]
channel: Optional[str]
mediaId: Optional[str]
contentType: Optional[Literal[
"image/tiff",
"image/png",
"image/jpeg",
"image/gif",
"image/bmp"
]]
mediaType: Optional[Literal[
"MainImage",
"AuxiliaryImage",
"AdditionalImage",
"SwatchImage"
]]
resolutionKey: Optional[Literal[
"ORIGINAL",
"X240",
"X1024",
"X2048"
]]
class BaseMediaAssetModel(BaseModel):
"""
Base model for create and response model.
"""
gtin: str
channel: str
mediaId: str
contentType: Literal[
"image/tiff",
"image/png",
"image/jpeg",
"image/gif",
"image/bmp"
]
mediaType: Optional[Literal[
"MainImage",
"AuxiliaryImage",
"AdditionalImage",
"SwatchImage"
]]
description: Optional[str]
brand: Optional[str]
category: Optional[str]
status: Optional[Literal[
"ML010New",
"ML030Imported",
"ML060QaPending",
"ML070QaApproved",
"ML090Retired",
"ML099Error"
]]
resolutionKey: Optional[Literal[
"ORIGINAL",
"X240",
"X1024",
"X2048"
]]
resolutionInPx: Optional[str]
hasCopyright: bool
class MediaAssetCreateModel(BaseMediaAssetModel):
"""
Create model for Media Asset model.
"""
media: Optional[MediaModel] = None
class MediaAssetResponseModel(BaseMediaAssetModel):
"""
Response model for Media Asset model.
"""
licenseValidFrom: datetime
licenseValidUntil: datetime
sourceUrl: str
sourceUrlValidFrom: datetime
sourceUrlValidUntil: datetime
class MediaAssetDeleteModel(BaseModel):
"""
Delete model for Media Asset model.
"""
channel: Optional[str]
gtin: Optional[str]
mediaId: Optional[str]
contentType: Optional[Literal[
"image/tiff",
"image/png",
"image/jpeg",
"image/gif",
"image/bmp"
]]
@media_lake_router.get('/', response_model=List[MediaAssetResponseModel])
async def get_media_assets(params: MediaAssetQueryModel = Depends()):
"""
View for fetching media assets matching the params.
"""
with db_session:
media_assets = MediaAsset.select(**params.dict(exclude_none=True))
media_assets = [media_asset.to_dict() for media_asset in media_assets]
return media_assets
@media_lake_router.post('/', status_code=202, response_model=List[MediaAssetResponseModel])
async def create_media_assets(media_assets: List[MediaAssetCreateModel]):
"""
View for creating media assets.
"""
try:
with db_session:
for media_asset in media_assets:
data = media_asset.dict()
if media_asset.media and media_asset.media.sourceUrl:
data['sourceUrl'] = media_asset.media.sourceUrl
# NOTE: I don't know where to get this so I'll get this from this
# for the mean time :P
data['sourceUrlValidFrom'] = (
media_asset.media.sourceUrlValidUntil
)
data['sourceUrlValidUntil'] = (
media_asset.media.sourceUrlValidUntil
)
data['media'] = json.dumps(data['media'], default=str)
MediaAsset(**data)
except Exception as e:
raise HTTPException(status_code=400, detail=str(e))
return media_assets
@media_lake_router.patch('/', status_code=202, response_model=List[MediaAssetResponseModel])
async def update_media_assets(media_assets: List[MediaAssetResponseModel]):
"""
View for creating media assets.
"""
with db_session:
for media_asset in media_assets:
media_asset_object = MediaAsset.get(gtin=media_asset.gtin)
if not media_asset_object:
continue
media_asset_object.set(**media_asset.dict())
return media_assets
@media_lake_router.delete('/', status_code=200)
async def delete_media_asset(media_asset: MediaAssetDeleteModel):
"""
View for creating media assets.
"""
with db_session:
media_asset_object = MediaAsset.get(**media_asset.dict())
if not media_asset_object:
raise HTTPException(status_code=404)
media_asset_object.delete()
return None
async def is_authenticated(api_key: str = Depends(X_API_KEY)):
"""
Makes sure that the api key lives in the header.
"""
if api_key != os.environ.get('API_KEY', ''):
raise HTTPException(status_code=401, detail="Invalid API Key")
return
app.include_router(
media_lake_router,
prefix='/media',
tags=['Media Lake'],
dependencies=[Depends(is_authenticated)]
)