Skip to content

Commit

Permalink
Merge pull request #88 from OZ-Coding-School/database
Browse files Browse the repository at this point in the history
main 브랜치로 이동
  • Loading branch information
dayeonkimm authored Aug 12, 2024
2 parents 56cc71a + 9498333 commit f1e1244
Show file tree
Hide file tree
Showing 16 changed files with 402 additions and 104 deletions.
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

17 changes: 4 additions & 13 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,15 +70,5 @@ services:
# env_file:
# - .env



db: # PostgreSQL Database
image: postgres:16-alpine
volumes:
- ./data/db:/var/lib/postgresql/data
environment:
- POSTGRES_DB=${POSTGRES_DB}
- POSTGRES_USER=${POSTGRES_USER}
- POSTGRES_PASSWORD=${POSTGRES_PASSWORD}
env_file:
- .env

57 changes: 54 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,51 @@
}
}

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"

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")

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.DateField(default=timezone.now)
date = models.DateField()

def __str__(self):
return f"{self.date}-{self.commit_num}"
150 changes: 150 additions & 0 deletions potato_project/githubs/signals.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,150 @@
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, **kwargs):
# 새 Github 데이터가 생성 or 업데이트, 날짜가 크리스마스이며, commit_num이 >
if (
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, **kwargs):
if (
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, **kwargs):
if instance.commit_num >= 1:
# 30일 전 날짜 계산
thirty_days_ago = instance.date - timedelta(days=30)

# 30일치 데이터가 있는지 확인
oldest_record = (
Github.objects.filter(user=instance.user).order_by("date").first()
)
if oldest_record and (instance.date - oldest_record.date).days >= 30:
# 30일 연속 커밋 여부 확인
commits_in_30_days = (
Github.objects.filter(
user=instance.user,
date__gte=thirty_days_ago,
date__lte=instance.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
else:
# 30일치 데이터가 없는 경우 로그 남기기 또는 다른 처리
print(
f"Not enough data for user {instance.user.id}. Oldest record date: {oldest_record.date if oldest_record else 'No records'}"
)


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

# 30일치 데이터가 있는지 확인
oldest_record = (
Github.objects.filter(user=instance.user).order_by("date").first()
)
if oldest_record and (instance.date - oldest_record.date).days >= 30:
# 30일 동안 커밋이 있었는지 확인
any_commits_in_30_days = Github.objects.filter(
user=instance.user,
date__gte=thirty_days_ago,
date__lte=instance.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 # 필요에 따라 에러 처리 추가
else:
# 30일치 데이터가 없는 경우 로그 남기기 또는 다른 처리
print(
f"Not enough data for user {instance.user.id}. Oldest record date: {oldest_record.date if oldest_record else 'No records'}"
)


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

# 90일치 데이터가 있는지 확인
oldest_record = (
Github.objects.filter(user=instance.user).order_by("date").first()
)
if oldest_record and (instance.date - oldest_record.date).days >= 90:
# 90일 동안 커밋이 있었는지 확인
any_commits_in_90_days = Github.objects.filter(
user=instance.user,
date__gte=ninety_days_ago,
date__lte=instance.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 # 필요에 따라 에러 처리 추가
else:
# 90일치 데이터가 없는 경우 로그 남기기 또는 다른 처리
print(
f"Not enough data for user {instance.user.id}. Oldest record date: {oldest_record.date if oldest_record else 'No records'}"
)
Loading

0 comments on commit f1e1244

Please sign in to comment.