Skip to content

Commit

Permalink
[Fix]레시피 추가 및 환경 수정
Browse files Browse the repository at this point in the history
  • Loading branch information
JoonHoSeong committed Aug 4, 2024
1 parent 049fa96 commit e80f055
Show file tree
Hide file tree
Showing 17 changed files with 273 additions and 22 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/deploy-aws.yml
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ jobs:
HOST=${{ secrets.BACKEND_DOMAIN }}
ALLOWED_HOSTS=${{ secrets.BACKEND_DOMAIN }},${{ secrets.EC2_IPv4 }}
PORT= ${{ secrets.Django_Port }}
CORS_ALLOWED_ORIGINS = http://${{ secrets.EC2_IPv4 }}:${{ secrets.DJANGO_PORT }}, http://${{ secrets.EC2_IPv4 }}:${{ secrets.FRONT_PORT }},http://${{ secrets.BACKEND_DOMAIN }}:${{ secrets.DJANGO_PORT }}, http://${{ secrets.FRONT_DOMAIN }}:${{ secrets.FRONT_PORT }},https://${{ secrets.BACKEND_DOMAIN }}, https://${{ secrets.FRONT_DOMAIN }},http://${{ secrets.BACKEND_DOMAIN }}, http://${{ secrets.FRONT_DOMAIN }}
CORS_ALLOWED_ORIGINS = http://${{ secrets.EC2_IPv4 }}:${{ secrets.DJANGO_PORT }}, http://${{ secrets.EC2_IPv4 }}:${{ secrets.FRONT_PORT }},http://${{ secrets.BACKEND_DOMAIN }}:${{ secrets.DJANGO_PORT }}, http://${{ secrets.FRONT_DOMAIN }}:${{ secrets.FRONT_PORT }},https://${{ secrets.BACKEND_DOMAIN }}, https://${{ secrets.FRONT_DOMAIN }},http://${{ secrets.BACKEND_DOMAIN }}, http://${{ secrets.FRONT_DOMAIN }}, http://localhost:${{ secrets.FRONT_PORT }}
SESSION_COOKIE_DOMAIN =${{ secrets.FRONT_DOMAIN }}
EOF
Expand Down
14 changes: 13 additions & 1 deletion Django/app/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,7 @@

# 애플리케이션 목록
INSTALLED_APPS = [
"management",
"django.contrib.admin",
"django.contrib.auth",
"django.contrib.contenttypes",
Expand Down Expand Up @@ -188,7 +189,7 @@
if DEBUG:
GOOGLE_CALLBACK_URI = "http://127.0.0.1:8000/api/v1/google/callback/"
else:
GOOGLE_CALLBACK_URI = "https://naengttogi.com/api/v1/google/callback/"
GOOGLE_CALLBACK_URI = "https://api.naengttogi.com/api/v1/google/callback/"

CORS_ORIGIN_ALLOW_ALL = False
CORS_ALLOWED_ORIGINS = os.environ.get("CORS_ALLOWED_ORIGINS", "").split(",")
Expand All @@ -213,3 +214,14 @@
CSRF_COOKIE_SECURE = True
CSRF_COOKIE_DOMAIN = ".naengttogi.com"
CORS_EXPOSE_HEADERS = ["Content-Type", "X-CSRFToken", "Set-Cookie"]
CORS_ALLOW_HEADERS = [
"accept",
"accept-encoding",
"authorization",
"content-type",
"dnt",
"origin",
"user-agent",
"x-csrftoken",
"x-requested-with",
]
13 changes: 8 additions & 5 deletions Django/app_user/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -73,9 +73,8 @@ def get(self, request):
"""
scope = "https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/userinfo.profile"
redirect_uri = settings.GOOGLE_CALLBACK_URI
return redirect(
f"https://accounts.google.com/o/oauth2/v2/auth?client_id={settings.GOOGLE_CLIENT_ID}&response_type=code&scope={scope}&redirect_uri={redirect_uri}&state={state}"
)
auth_url = f"https://accounts.google.com/o/oauth2/v2/auth?client_id={settings.GOOGLE_CLIENT_ID}&response_type=code&scope={scope}&redirect_uri={redirect_uri}&state={state}"
return HttpResponseRedirect(auth_url)


class GoogleCallback(APIView):
Expand Down Expand Up @@ -193,6 +192,8 @@ def get(self, request):

# Response 객체 생성 및 쿠키 설정
response = HttpResponseRedirect("https://naengttogi.com/", status=307)
response["Access-Control-Allow-Origin"] = "https://naengttogi.com"
response["Access-Control-Allow-Credentials"] = "true"
# response = HttpResponseRedirect(
# "http://localhost:5173/", status=307
# ) # 프론트 테스트용
Expand All @@ -202,15 +203,17 @@ def get(self, request):
"access",
access_token,
httponly=True,
secure=settings.DEBUG is False, # 개발 환경에 따라 secure 설정
secure=True, # HTTPS 사용 시 True
samesite="None", # Cross-site 쿠키 허용
domain=".naengttogi.com", # 도메인 설정
)
response.set_cookie(
"refresh",
str(refresh),
httponly=True,
secure=settings.DEBUG is False,
secure=True,
samesite="None",
domain=".naengttogi.com",
)

# 사용자 모델에 refresh 토큰 저장
Expand Down
Empty file added Django/management/__init__.py
Empty file.
3 changes: 3 additions & 0 deletions Django/management/admin.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
from django.contrib import admin

# Register your models here.
6 changes: 6 additions & 0 deletions Django/management/apps.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
from django.apps import AppConfig


class ManagementConfig(AppConfig):
default_auto_field = "django.db.models.BigAutoField"
name = "management"
136 changes: 136 additions & 0 deletions Django/management/management/commands/import_recipes.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,136 @@
import json
import logging

from django.core.management.base import BaseCommand
from django.db import transaction
from ingredient.models import Ingredient
from ingredient.models import IngreMajor
from recipe.models import CookingAttribute
from recipe.models import CookingMainIngre
from recipe.models import CookingMethod
from recipe.models import CookingNameList
from recipe.models import CookingSituation
from recipe.models import CookingType
from recipe.models import DetailRecipe
from recipe.models import Recipe
from recipe.models import RecipeDifficulty
from recipe.models import RecipeIngredientList

# 로깅 설정
logging.basicConfig(
level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s"
)


class Command(BaseCommand):
help = "Import recipes from JSON file"

def add_arguments(self, parser):
parser.add_argument("json_file", type=str, help="Path to the JSON file")

def handle(self, *args, **options):
json_file = options["json_file"]

# JSON 데이터 로드
with open(json_file, "r", encoding="utf-8") as f:
data = json.load(f)

self.import_recipes(data)

@transaction.atomic
def import_recipes(self, data):
for recipe_data in data.values():
try:
self.create_recipe(recipe_data)
except Exception as e:
logging.error(
f"Error inserting recipe {recipe_data.get('recipe_name', 'Unknown')}: {str(e)}"
)

def map_difficulty(self, difficulty):
difficulty = difficulty.upper()
if difficulty in ["초급", "EASY"]:
return RecipeDifficulty.EASY
elif difficulty in ["중급", "MEDIUM"]:
return RecipeDifficulty.MEDIUM
elif difficulty in ["고급", "HARD"]:
return RecipeDifficulty.HARD
else:
return RecipeDifficulty.EASY # 기본값

def get_or_create(self, model, name):
obj, created = model.objects.get_or_create(name=name)
return obj

def get_or_create_ingredient(self, ingre_name):
ingredient = Ingredient.objects.filter(name=ingre_name).first()
if ingredient:
return ingredient
else:
# 기본 IngreMajor 생성 또는 가져오기
default_major, _ = IngreMajor.objects.get_or_create(name="기타")
return Ingredient.objects.create(
name=ingre_name, major=default_major, is_custom=True
)

def create_recipe(self, recipe_data):
# CookingAttribute 관련 객체 가져오기 또는 생성
name = self.get_or_create(CookingNameList, recipe_data["cooking_name"])
method = self.get_or_create(CookingMethod, recipe_data["cooking_method"])
situation = self.get_or_create(CookingSituation, recipe_data["situation_type"])
main_ingre = self.get_or_create(
CookingMainIngre, recipe_data["main_ingredient_type"]
)
type_ = self.get_or_create(CookingType, recipe_data["cooking_type"])

# CookingAttribute 생성
attribute, _ = CookingAttribute.objects.get_or_create(
name=name,
method=method,
situation=situation,
main_ingre=main_ingre,
type=type_,
)

# Recipe 생성
recipe, created = Recipe.objects.get_or_create(
url=recipe_data["URL"],
defaults={
"recipe_name": recipe_data["recipe_name"],
"nick_name": recipe_data.get("nick_name", "None")[
:255
], # max_length=255 제한
"recommend_num": recipe_data["recommand_num"],
"recipe_intro": recipe_data["recipe_intro"],
"eat_people": int(recipe_data["eat_people"].replace("인분", "")),
"difficulty": self.map_difficulty(recipe_data["difficulty"]),
"cooking_time": int(recipe_data["cooking_time"][0]),
"thumbnail_url": recipe_data.get("thumbnail_url", ""),
"attribute": attribute,
},
)

if not created:
logging.info(f"Recipe already exists: {recipe_data['recipe_name']}")
return

# RecipeIngredientList 생성
for ingre_name, quantity in recipe_data["ingre_list"].items():
ingredient = self.get_or_create_ingredient(ingre_name)
RecipeIngredientList.objects.create(
recipe=recipe,
ingredient=ingredient,
quantity=quantity[:50], # max_length=50 제한
)

# DetailRecipe 생성
for step, detail in recipe_data["detail_recipes"].items():
DetailRecipe.objects.create(
recipe=recipe,
step=int(step),
img_url=detail.get("img_url", ""),
recipe_text=detail["recipe"],
tip=detail.get("tip", ""),
)

logging.info(f"Successfully inserted recipe: {recipe_data['recipe_name']}")
Empty file.
3 changes: 3 additions & 0 deletions Django/management/models.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
from django.db import models

# Create your models here.
3 changes: 3 additions & 0 deletions Django/management/tests.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
from django.test import TestCase

# Create your tests here.
3 changes: 3 additions & 0 deletions Django/management/views.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
from django.shortcuts import render

# Create your views here.
18 changes: 18 additions & 0 deletions Django/recipe/migrations/0006_alter_recipe_nick_name.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
# Generated by Django 5.0.7 on 2024-08-04 07:59

from django.db import migrations, models


class Migration(migrations.Migration):

dependencies = [
("recipe", "0005_alter_cookingattribute_unique_together"),
]

operations = [
migrations.AlterField(
model_name="recipe",
name="nick_name",
field=models.CharField(blank=True, max_length=255),
),
]
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
# Generated by Django 5.0.7 on 2024-08-04 08:08

from django.db import migrations, models


class Migration(migrations.Migration):

dependencies = [
("recipe", "0006_alter_recipe_nick_name"),
]

operations = [
migrations.AlterField(
model_name="cookingmainingre",
name="name",
field=models.CharField(max_length=255, unique=True),
),
migrations.AlterField(
model_name="cookingmethod",
name="name",
field=models.CharField(max_length=255, unique=True),
),
migrations.AlterField(
model_name="cookingnamelist",
name="name",
field=models.CharField(max_length=255, unique=True),
),
migrations.AlterField(
model_name="cookingsituation",
name="name",
field=models.CharField(max_length=255, unique=True),
),
migrations.AlterField(
model_name="cookingtype",
name="name",
field=models.CharField(max_length=255, unique=True),
),
]
21 changes: 21 additions & 0 deletions Django/recipe/migrations/0008_alter_recipe_nick_name.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
# Generated by Django 5.0.7 on 2024-08-04 08:20

from django.db import migrations, models


class Migration(migrations.Migration):

dependencies = [
(
"recipe",
"0007_alter_cookingmainingre_name_alter_cookingmethod_name_and_more",
),
]

operations = [
migrations.AlterField(
model_name="recipe",
name="nick_name",
field=models.CharField(blank=True, max_length=255, null=True),
),
]
14 changes: 8 additions & 6 deletions Django/recipe/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,23 +4,23 @@


class CookingNameList(models.Model):
name = models.CharField(max_length=255)
name = models.CharField(max_length=255, unique=True)


class CookingMethod(models.Model):
name = models.CharField(max_length=255)
name = models.CharField(max_length=255, unique=True)


class CookingSituation(models.Model):
name = models.CharField(max_length=255)
name = models.CharField(max_length=255, unique=True)


class CookingMainIngre(models.Model):
name = models.CharField(max_length=255)
name = models.CharField(max_length=255, unique=True)


class CookingType(models.Model):
name = models.CharField(max_length=255)
name = models.CharField(max_length=255, unique=True)


class RecipeDifficulty(models.TextChoices):
Expand Down Expand Up @@ -48,7 +48,9 @@ class CookingAttribute(models.Model):
class Recipe(models.Model):
url = models.URLField()
recipe_name = models.TextField()
nick_name = models.ForeignKey(App_User, on_delete=models.CASCADE)
nick_name = models.CharField(
max_length=255, blank=True, null=True
) # ForeignKey에서 CharField로 변경
recommend_num = models.PositiveIntegerField(default=0)
recipe_intro = models.TextField(blank=True)
eat_people = models.PositiveSmallIntegerField(default=1)
Expand Down
Loading

0 comments on commit e80f055

Please sign in to comment.