Skip to content

Commit

Permalink
feat: save reviews to s3
Browse files Browse the repository at this point in the history
  • Loading branch information
ZacHooper committed Feb 21, 2024
1 parent 5980977 commit 45ea151
Show file tree
Hide file tree
Showing 6 changed files with 32 additions and 3 deletions.
11 changes: 8 additions & 3 deletions api/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,16 @@
from fastapi.staticfiles import StaticFiles
from fastapi.templating import Jinja2Templates
from mangum import Mangum
from utils import s3

app = FastAPI()

app.mount("/static", StaticFiles(directory="static"), name="static")


templates = Jinja2Templates(directory="templates")

BUCKET = "coffee-review"


@app.get("/", response_class=HTMLResponse)
async def home(request: Request):
Expand All @@ -24,8 +26,11 @@ async def home(request: Request):
async def review(request: Request):
# Get the form data
form = await request.form()
print(form)
return templates.TemplateResponse(request=request, name="success.html")
res = s3.upload_review(dict(form), BUCKET)
if res:
return templates.TemplateResponse(request=request, name="success.html")
else:
return templates.TemplateResponse(request=request, name="error.html")


@app.get("/api/review", response_class=HTMLResponse)
Expand Down
1 change: 1 addition & 0 deletions api/requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ fastapi
jinja2
mangum
python-multipart
boto3

# Testing
# uvicorn
5 changes: 5 additions & 0 deletions api/templates/error.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
<div class="text-center flex flex-col items-center justify-center h-screen">
<h1 class="text-5xl mb-16">Something went wrong submitted review</h1>
<button class="btn btn-primary" hx-get="/api/review" hx-swap="innerHTML" hx-target="body">
Make another review</button>
</div>
Empty file added api/utils/__init__.py
Empty file.
15 changes: 15 additions & 0 deletions api/utils/s3.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import boto3
import json
import uuid


def upload_review(review: dict, bucket: str) -> bool:
"""Uploads a review to S3"""
s3 = boto3.client("s3")
key = f"{uuid.uuid4()}.json"
try:
s3.put_object(Bucket=bucket, Key=key, Body=json.dumps(review))
return True
except Exception as e:
print(e)
return False
3 changes: 3 additions & 0 deletions template.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,9 @@ Resources:
CodeUri: api
Handler: main.handler
Runtime: python3.11
Policies:
- S3CrudPolicy:
BucketName: coffee-review
Events:
Api:
Type: HttpApi
Expand Down

0 comments on commit 45ea151

Please sign in to comment.