Skip to content
This repository has been archived by the owner on Jun 24, 2024. It is now read-only.

Commit

Permalink
Feat: 유저 레시피 생성 코드 추가
Browse files Browse the repository at this point in the history
-
  • Loading branch information
tomorrow9913 committed Dec 3, 2023
1 parent 2143e42 commit 1aac7bf
Show file tree
Hide file tree
Showing 7 changed files with 132 additions and 3 deletions.
39 changes: 39 additions & 0 deletions core/schemas/recipe.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import datetime

from fastapi import UploadFile
from pydantic import BaseModel, field_validator


class Recipe(BaseModel):
id: int
set_id: int
user_id: int
title: str
description: str
image_url: str
create_time: datetime.datetime


class RecipeCreate(BaseModel):
set_id: int
title: str
description: str

@field_validator('title', 'description')
def not_empty(cls, v):
if not v or not v.strip():
raise ValueError('빈 값은 허용되지 않습니다.')
return v


class RecipeUsePerfume(BaseModel):
id: int
recipe_id: int
cartridge_id: int
count: int


class RecipeUsePerfumeCreate(BaseModel):
recipe_id: int
cartridge_id: int
count: int
2 changes: 2 additions & 0 deletions main.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
from internal import admin
from routers.user import users_router as user
from routers.tag import tag_router as tag
from routers.recipe import recipe_router as recipe

app = FastAPI()

Expand All @@ -24,6 +25,7 @@
# routers
app.include_router(user.router)
app.include_router(tag.router)
app.include_router(recipe.router)

@app.get("/")
async def root():
Expand Down
Empty file added routers/recipe/__init__.py
Empty file.
22 changes: 22 additions & 0 deletions routers/recipe/recipe_crud.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
from passlib.context import CryptContext
from sqlalchemy.orm import Session
from sqlalchemy import func

from core.models import models
from core.models.models import UserRecipe, UserRecipeUsePerfume
from core.schemas.recipe import RecipeCreate
from datetime import datetime


def create_recipe(db: Session, image_url: str, recipe_create: RecipeCreate, current_user: models.User | None = None):
db_recipe = UserRecipe(
user_id=1,
set_id=recipe_create.set_id,
title=recipe_create.title,
description=recipe_create.description,
image_url=image_url,
create_time=datetime.now(),
)
db.add(db_recipe)
db.commit()

59 changes: 59 additions & 0 deletions routers/recipe/recipe_router.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
from datetime import timedelta, datetime
from typing import Optional, Annotated

import aiofiles
from fastapi import APIRouter, Depends, HTTPException, UploadFile, File, Form
from fastapi.security import OAuth2PasswordRequestForm, OAuth2PasswordBearer
from jose import jwt
from sqlalchemy.orm import Session
from starlette import status
from starlette.config import Config
import hashlib
import json

from core.database import get_db
from core.models import models
from core.models.models import UserRecipe, UserRecipeUsePerfume
from core.schemas import recipe
from core.schemas import tag
from dependencies import get_current_user
import routers.recipe.recipe_crud as recipe_crud

config = Config('.env')

router = APIRouter(
prefix="/api/recipe",
tags=["Recipe"]
)

# Todo 계정 관련하여 추가하여야 함.
# Create
@router.post("/", status_code=status.HTTP_204_NO_CONTENT,
description='new_recipe는 다음과 같이 입력해주세요. new_recipe={"set_id": 0, "title": "string", "description": "string"}')
async def create_recipe(new_recipe: str = Form(...),
file: UploadFile = File(None),
db: Session = Depends(get_db)
):
data = json.loads(new_recipe.replace("new_recipe=", ""))
create_recipe = recipe.RecipeCreate(**data)

if file:
file_name = (hashlib.sha256(
f"{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}{file.filename}".encode())
.hexdigest() + "." + file.filename.split('.')[-1])

file_location = f"./static/img/recipe/"

# 파일 경로가 없다면 생성
import os
if not os.path.exists(os.path.dirname(file_location)):
os.makedirs(file_location)

file_location = os.path.join(file_location,file_name)
async with aiofiles.open(file_location, 'wb+') as f:
while content := await file.read(1024):
await f.write(content)
else:
file_location = None

recipe_crud.create_recipe(db, file_location, create_recipe)
3 changes: 1 addition & 2 deletions routers/tag/tag_crud.py
Original file line number Diff line number Diff line change
Expand Up @@ -71,8 +71,7 @@ def add_tag(db: Session, tag_list: AddTag):
for tag_name in tag_list.tag_list:
if not get_tag_info(db, tag_name):
create_tag_info(db, TagInfoCreate(name=tag_name))
tag_id = get_tag_info(db, tag_name).id
create_tag(db, TagCreate(recipe_id=tag_list.recipe_id, tag_id=tag_id))
create_tag(db, TagCreate(recipe_id=tag_list.recipe_id, tag_id=get_tag_info(db, tag_name).id))


def delete_tag(db: Session, tag_id: int, recipe_id: int):
Expand Down
10 changes: 9 additions & 1 deletion routers/tag/tag_router.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,16 @@


# Create
@router.post("/add_tag", status_code=status.HTTP_204_NO_CONTENT)
def add_tag(_add_tag: tag.AddTag, db: Session = Depends(get_db)):
tag_crud.add_tag(db, _add_tag)


@router.post("/tag_list", response_model=tag.TagList)
def create_tag(tag_list: tag.TagStrList, db: Session = Depends(get_db)):
def get_tag_id(tag_list: tag.TagStrList, db: Session = Depends(get_db)):
return {"tag_list": tag_crud.get_tag_info_list(db, tag_list.tag_list)}


@router.delete("/{recipe_id}/{tag_id}", status_code=status.HTTP_204_NO_CONTENT)
def delete_tag(recipe_id: int, tag_id: int, db: Session = Depends(get_db)):
tag_crud.delete_tag(db, recipe_id, tag_id)

0 comments on commit 1aac7bf

Please sign in to comment.