Skip to content

Commit

Permalink
[pre-commit.ci] auto fixes from pre-commit.com hooks
Browse files Browse the repository at this point in the history
for more information, see https://pre-commit.ci
  • Loading branch information
pre-commit-ci[bot] committed Aug 24, 2024
1 parent c95fe0f commit c9fe635
Show file tree
Hide file tree
Showing 5 changed files with 30 additions and 32 deletions.
17 changes: 8 additions & 9 deletions contest/contest/celery.py
Original file line number Diff line number Diff line change
@@ -1,19 +1,18 @@
from __future__ import absolute_import #, unicode_literals
import os

from celery import Celery
from celery.schedules import crontab
from django.utils import timezone

# set the default Django settings module for the 'celery' program.
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'contest.settings')
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "contest.settings")

app = Celery('contest')
app = Celery("contest")

# Using a string here means the worker doesn't have to serialize
# the configuration object to child processes.
# - namespace='CELERY' means all celery-related configuration keys
# should have a `CELERY_` prefix.
app.config_from_object('django.conf:settings', namespace='CELERY')
app.config_from_object("django.conf:settings", namespace="CELERY")

# 解决时区问题,定时任务启动就循环输出
# app.now = timezone.now()
Expand All @@ -24,8 +23,8 @@
# import contest.contest.tasks

app.conf.beat_schedule = {
'clean-specific-time' : {
'task': 'contest.tasks.auto_save_redis_to_database',
'schedule': crontab()
"clean-specific-time": {
"task": "contest.tasks.auto_save_redis_to_database",
"schedule": crontab(),
}
}
}
8 changes: 4 additions & 4 deletions contest/contest/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ def _debug_only(*args) -> tuple:
# Application definition

INSTALLED_APPS = [
'django_celery_beat',
"django_celery_beat",
"quiz.apps.QuizConfig",
"quiz.templatetags",
"django.contrib.humanize",
Expand Down Expand Up @@ -258,13 +258,13 @@ def _debug_only(*args) -> tuple:
}

if DEBUG:
CELERY_BROKER_URL = 'redis://127.0.0.1:6379/0'
CELERY_BROKER_URL = "redis://127.0.0.1:6379/0"
else:
CELERY_BROKER_URL = 'redis://localhost:6379/0' # Modify in Release
CELERY_BROKER_URL = "redis://localhost:6379/0" # Modify in Release

CELERY_TIMEZONE = TIME_ZONE
# DJANGO_CELERY_BEAT_TZ_AWARE = False
CELERY_BEAT_SCHEDULER = 'django_celery_beat.schedulers:DatabaseScheduler'
CELERY_BEAT_SCHEDULER = "django_celery_beat.schedulers:DatabaseScheduler"
# CELERY_ENABLE_UTC = False

# 防止本地注册表出现损坏导致的MIME类型解析错误,导致后端无法处理JS文件
Expand Down
25 changes: 14 additions & 11 deletions contest/contest/tasks.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
import logging

import redis
from celery import shared_task
from django.core.cache import cache
import redis
import logging
from django.utils import timezone
from django.shortcuts import get_object_or_404
from django.utils import timezone

# 这里的Lint报错是因为celery运行的时候需要cd到非根目录,
# 导致运行的时候如果直接import contest.quiz.models会找不到
# 所以就直接默认已经在contest路径里开始索引,因此lint会报错
Expand All @@ -13,24 +15,25 @@
DraftAnswer,
DraftResponse,
)

# Get an instance of a logger
logger = logging.getLogger('django')
logger = logging.getLogger("django")


@shared_task
def auto_save_redis_to_database():
# 获取 Redis 连接
r = redis.Redis(host='127.0.0.1', port=6379, db=1)
r = redis.Redis(host="127.0.0.1", port=6379, db=1)
# 使用 scan_iter 获取所有键
keys = r.scan_iter('*_ddl')
keys = r.scan_iter("*_ddl")
for key in keys:
ddl_key = key.decode('utf-8')[3:]
ddl_key = key.decode("utf-8")[3:]
print(ddl_key)
ddl = cache.get(ddl_key)
now = timezone.now()
if ddl is not None:
if ddl < now:
print(f'{ddl_key} redis auto save')
print(f"{ddl_key} redis auto save")
draft_response = DraftResponse.objects.get(pk=ddl_key[:-4])

cache_key = f"{ddl_key[:-4]}_json"
Expand All @@ -43,7 +46,7 @@ def auto_save_redis_to_database():
continue

if not isinstance(choice_id, str) or not choice_id.startswith("choice-"):
print(f'{key} not choice-')
print(f"{key} not choice-")
return

answer: DraftAnswer = get_object_or_404(
Expand Down Expand Up @@ -71,8 +74,8 @@ def auto_save_redis_to_database():
cache.delete(f"{draft_response.id}_ddl")
cache.delete(f"{draft_response.id}_sequence")
else:
print(f'{key} None')
print(f"{key} None")

# 关闭 Redis 连接
del keys
r.close()
r.close()
2 changes: 1 addition & 1 deletion contest/quiz/constants.py
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ class ConstantsNamespace:
DEADLINE_DURATION = timedelta(seconds=3)
"""作答限时"""

MAX_TRIES = 2
MAX_TRIES = 2
"""答题次数上限"""

YEAR = 2024
Expand Down
10 changes: 3 additions & 7 deletions contest/quiz/views.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
from __future__ import annotations

import time
from http import HTTPStatus
from random import sample
from typing import TYPE_CHECKING
Expand Down Expand Up @@ -80,7 +79,7 @@ def continue_or_finalize(student_: Student) -> bool:

cache.delete(f"{student_.user}_json")
cache.delete(f"{student_.user}_ddl")

# 1. Convert from draft
response, answers = student_.draft_response.finalize(submit_at=timezone.now())

Expand Down Expand Up @@ -263,7 +262,7 @@ def contest_update(request: AuthenticatedHttpRequest) -> HttpResponse:

cache.set(f"{cache_key}_ddl", draft_response.deadline, timeout=None)
cache.set(f"{cache_key}_json", request.POST, timeout=None)

return HttpResponse("Updated.")


Expand All @@ -272,10 +271,7 @@ def contest_update(request: AuthenticatedHttpRequest) -> HttpResponse:
@pass_or_forbid(is_student_taking_contest, "请先前往答题再提交答卷。")
@require_POST
def contest_submit(request: AuthenticatedHttpRequest) -> HttpResponse:
"""交卷
"""
"""交卷"""
student: Student = request.user.student
draft_response: DraftResponse = student.draft_response

Expand Down

0 comments on commit c9fe635

Please sign in to comment.