Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feat/database edit #85

Merged
merged 21 commits into from
Aug 4, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 20 additions & 20 deletions Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -13,35 +13,34 @@ ENV PYTHONUNBUFFERED 1
# 로컬 파일 시스템의 requirements.txt 파일을 컨테이너의 /tmp/requirements.txt로 복사합니다.
# 이 파일은 필요한 Python 패키지들을 명시합니다.
COPY ./requirements.txt /tmp/requirements.txt
COPY ./requirements.dev.txt /tmp/requirements.dev.txt
COPY ./potato_project /app
WORKDIR /app
EXPOSE 8000

ARG DEV=false

RUN python -m venv /py && \
/py/bin/pip install --upgrade pip && \
/py/bin/pip install -r /tmp/requirements.txt && \
apk add --update --no-cache postgresql-client jpeg-dev && \
apk add --update --no-cache --virtual .tmp-build-deps \
build-base postgresql-dev musl-dev zlib zlib-dev linux-headers && \
if [ $DEV = "true" ]; \
then /py/bin/pip install -r /tmp/requirements.dev.txt ; \
fi && \
rm -rf /tmp && \
apk del .tmp-build-deps && \
adduser \
--disabled-password \
--no-create-home \
django-user
# 가상 환경 설정 및 패키지 설치
RUN python -m venv /py
RUN /py/bin/pip install --upgrade pip
RUN /py/bin/pip install --no-cache-dir -r /tmp/requirements.txt

# 시스템 패키지 설치
RUN apk add --update --no-cache jpeg-dev
RUN apk add --update --no-cache --virtual .tmp-build-deps \
build-base musl-dev zlib zlib-dev linux-headers \
&& apk del .tmp-build-deps

# django-user 생성 및 권한 설정
RUN if ! getent passwd django-user; then adduser -D django-user; fi
USER root
RUN chown -R django-user:django-user /py/lib/python3.11/site-packages
USER django-user

# 추가 패키지 설치
ENV PATH="/py/bin:$PATH"
RUN /py/bin/pip install --no-cache-dir pytest pytest-django django-cors-headers

USER django-user

# 이 명령어를 추가하여 pytest를 설치합니다.
RUN /py/bin/pip install pytest pytest-django


# 개발용
Expand Down Expand Up @@ -88,4 +87,5 @@ RUN /py/bin/pip install pytest pytest-django
# USER django-user

# # 이 명령어를 추가하여 pytest를 설치합니다.
# RUN /py/bin/pip install pytest pytest-django
# RUN /py/bin/pip install pytest pytest-django

6 changes: 4 additions & 2 deletions docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,8 @@ services:
- DB_PASSWORD=${DB_PASSWORD}
- PYDEVD_DISABLE_FILE_VALIDATION=1
env_file:
- .env
- .env



# 개발용
Expand Down Expand Up @@ -56,7 +57,7 @@ services:
# - .env
# depends_on:
# - db


# db: # PostgreSQL Database
# image: postgres:16-alpine
Expand All @@ -69,6 +70,7 @@ services:
# env_file:
# - .env




db: # PostgreSQL Database
Expand Down
61 changes: 58 additions & 3 deletions potato_project/app/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,8 +53,10 @@
"allauth.account",
"allauth.socialaccount",
"allauth.socialaccount.providers.github",
"corsheaders",
]


INSTALLED_APPS = DJANGO_SYSTEM_APPS + CUSTOM_USER_APPS

# Custom user model
Expand All @@ -71,6 +73,7 @@

# 미들웨어 설정
MIDDLEWARE = [
"corsheaders.middleware.CorsMiddleware",
"django.middleware.security.SecurityMiddleware",
"django.contrib.sessions.middleware.SessionMiddleware",
"django.middleware.common.CommonMiddleware",
Expand Down Expand Up @@ -115,6 +118,9 @@
"USER": os.environ.get("RDS_USERNAME"),
"PASSWORD": os.environ.get("RDS_PASSWORD"),
"PORT": os.environ.get("RDS_PORT", 5432),
"OPTIONS": {
"client_encoding": "UTF8", # UTF-8 문자셋 설정
},
}
}

Expand Down Expand Up @@ -205,6 +211,55 @@
}
}

SOCIALACCOUNT_LOGIN_ON_GET = True
LOGIN_REDIRECT_URL = "/oauth-callback/"
ACCOUNT_LOGOUT_REDIRECT_URL = "/landing/"
SOCIALACCOUNT_LOGIN_ON_GET = False
# LOGIN_REDIRECT_URL = "/oauth-callback/"
# ACCOUNT_LOGOUT_REDIRECT_URL = "/landing/"

DEFAULT_CHARSET = "utf-8"

DEFAULT_CHARSET = "utf-8"

LOGGING = {
"version": 1,
"disable_existing_loggers": False,
"handlers": {
"console": {
"class": "logging.StreamHandler",
},
},
"root": {
"handlers": ["console"],
"level": "DEBUG",
},
}

# CORS_ORIGIN_WHITELIST = ['http://localhost:5173', 'http://127.0.0.1:5173', 'https://www.gitpotatoes.com',] # 특정 Origin만 허용
CORS_ALLOWED_ORIGINS = [
"https://www.gitpotatoes.com", # 실제 배포 프론트엔드 URL
"http://localhost:5173", # 프론트엔드 로컬 서버 URL
"http://127.0.0.1:5173", # 프론트엔드 로컬 서버 URL
]
CORS_ALLOW_CREDENTIALS = True # 쿠키 등 credential 정보 허용
CORS_ALLOW_METHODS = [
"DELETE",
"GET",
"OPTIONS",
"PATCH",
"POST",
"PUT",
]
CORS_ALLOW_HEADERS = [
"accept",
"accept-encoding",
"authorization",
"content-type",
"dnt",
"origin",
"user-agent",
"x-csrftoken",
"x-requested-with",
]
SECURE_PROXY_SSL_HEADER = ("HTTP_X_FORWARDED_PROTO", "https")

CSRF_COOKIE_SECURE = True
SESSION_COOKIE_SECURE = True
8 changes: 4 additions & 4 deletions potato_project/app/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,10 @@

urlpatterns = [
path("api/admin/", admin.site.urls),
path("api/accounts/", include("dj_rest_auth.registration.urls")),
path("api/accounts/", include("dj_rest_auth.urls")),
path("api/accounts/", include("allauth.urls")),
path("api/accounts/", include("users.urls")),
path("accounts/", include("dj_rest_auth.registration.urls")),
path("accounts/", include("dj_rest_auth.urls")),
path("accounts/", include("allauth.urls")),
path("", include("users.urls")),
path("api/baekjoons/", include("baekjoons.urls")),
path("api/attendances/", include("attendances.urls")),
path("api/potatoes/", include("potatoes.urls")),
Expand Down
8 changes: 6 additions & 2 deletions potato_project/attendances/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,9 @@ def increment(self, request):
# 출석날짜가 오늘이면 이미 출석함을 반환
attendance = self.get_user_attendance(user)
if attendance and attendance.date == today:
return Response({"오늘은 출석을 이미 하셨어요!"}, status=status.HTTP_400_BAD_REQUEST)
return Response(
{"오늘은 출석을 이미 하셨어요!"}, status=status.HTTP_400_BAD_REQUEST
)

# 새로운 출석 기록 생성
new_attendance = Attendance.objects.create(
Expand Down Expand Up @@ -71,4 +73,6 @@ def decrement(self, request):
user.save()

# 성공 응답 반환
return Response({"message": "물건을 구매했습니다.", "total_coins": user.total_coins})
return Response(
{"message": "물건을 구매했습니다.", "total_coins": user.total_coins}
)
2 changes: 1 addition & 1 deletion potato_project/githubs/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
class Github(TimeStampedModel):
user = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name="User_id")
commit_num = models.BigIntegerField(verbose_name="Commit Number")
date = models.DateTimeField(default=timezone.now)
date = models.DateField(default=timezone.now)

def __str__(self):
return f"{self.date}-{self.commit_num}"
122 changes: 122 additions & 0 deletions potato_project/githubs/signals.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,122 @@
from datetime import date, timedelta

from django.db.models.signals import post_save
from django.dispatch import receiver
from githubs.models import Github
from potatoes.models import Potato


@receiver(post_save, sender=Github)
def get_winter_potato(sender, instance, created, **kwargs):
# 새 Github 데이터가 생성 or 업데이트, 날짜가 크리스마스이며, commit_num이 1 이상인 경우에만 실행
if (
created
and instance.commit_num >= 1
and instance.date.month == 12
and instance.date.day == 25
): # 월과 일만 비교
try:
# potato_type_id=6인 감자 조회
potato = Potato.objects.get(user=instance.user, potato_type_id=6)
if not potato.is_acquired: # 이미 획득한 경우에는 변경하지 않음
potato.is_acquired = True
potato.save()
except Potato.DoesNotExist:
# 해당 감자가 없는 경우 에러 처리 (필요에 따라 추가)
pass


@receiver(post_save, sender=Github)
def get_ghost_potato(sender, instance, created, **kwargs):
if (
created
and instance.commit_num >= 1
and instance.date.month == 10
and instance.date.day == 31
):
try:
potato = Potato.objects.get(user=instance.user, potato_type_id=7)
if not potato.is_acquired:
potato.is_acquired = True
potato.save()
except Potato.DoesNotExist:
pass


@receiver(post_save, sender=Github)
def get_crystal_potato(sender, instance, created, **kwargs):
if created and instance.commit_num >= 1:
# 30일 전 날짜 계산
thirty_days_ago = instance.date.date() - timedelta(days=30)

# 30일 연속 커밋 여부 확인
commits_in_30_days = (
Github.objects.filter(
user=instance.user,
date__gte=thirty_days_ago,
date__lte=instance.date.date(),
commit_num__gte=1,
)
.values("date")
.distinct()
.count()
)

if commits_in_30_days == 30:
try:
potato = Potato.objects.get(user=instance.user, potato_type_id=8)
if not potato.is_acquired:
potato.is_acquired = True
potato.save()
except Potato.DoesNotExist:
pass


@receiver(post_save, sender=Github)
def get_dirty_potato(sender, instance, created, **kwargs):
if created:
# 30일 전 날짜 계산
thirty_days_ago = instance.date.date() - timedelta(days=30)

# 30일 동안 커밋이 있었는지 확인
any_commits_in_30_days = Github.objects.filter(
user=instance.user,
date__gte=thirty_days_ago,
date__lte=instance.date.date(),
commit_num__gte=1,
).exists()

if not any_commits_in_30_days:
# 30일 연속 커밋이 없는 경우 감자 아이디 9 획득 로직 실행
try:
potato = Potato.objects.get(user=instance.user, potato_type_id=9)
if not potato.is_acquired:
potato.is_acquired = True
potato.save()
except Potato.DoesNotExist:
pass # 필요에 따라 에러 처리 추가


@receiver(post_save, sender=Github)
def get_green_potato(sender, instance, created, **kwargs):
if created:
# 90일 전 날짜 계산
ninety_days_ago = instance.date.date() - timedelta(days=90)

# 90일 동안 커밋이 있었는지 확인
any_commits_in_90_days = Github.objects.filter(
user=instance.user,
date__gte=ninety_days_ago,
date__lte=instance.date.date(),
commit_num__gte=1,
).exists()

if not any_commits_in_90_days:
# 90일 연속 커밋이 없는 경우 감자 아이디 10 획득 로직 실행
try:
potato = Potato.objects.get(user=instance.user, potato_type_id=10)
if not potato.is_acquired:
potato.is_acquired = True
potato.save()
except Potato.DoesNotExist:
pass # 필요에 따라 에러 처리 추가
Loading
Loading