NDOJ/judge/utils/celery.py

68 lines
1.6 KiB
Python
Raw Normal View History

2020-01-21 06:35:58 +00:00
from django.http import HttpResponseRedirect
from django.urls import reverse
from django.utils.http import urlencode
class Progress:
def __init__(self, task, total, stage=None):
self.task = task
self._total = total
self._done = 0
self._stage = stage
def _update_state(self):
self.task.update_state(
2022-05-14 17:57:27 +00:00
state="PROGRESS",
2020-01-21 06:35:58 +00:00
meta={
2022-05-14 17:57:27 +00:00
"done": self._done,
"total": self._total,
"stage": self._stage,
2020-01-21 06:35:58 +00:00
},
)
@property
def done(self):
return self._done
@done.setter
def done(self, value):
self._done = value
self._update_state()
@property
def total(self):
return self._total
@total.setter
def total(self, value):
self._total = value
self._done = min(self._done, value)
self._update_state()
def did(self, delta):
self._done += delta
self._update_state()
def __enter__(self):
return self
def __exit__(self, exc_type, exc_val, exc_tb):
if exc_type is None:
self.done = self._total
def task_status_url(result, message=None, redirect=None):
args = {}
if message:
2022-05-14 17:57:27 +00:00
args["message"] = message
2020-01-21 06:35:58 +00:00
if redirect:
2022-05-14 17:57:27 +00:00
args["redirect"] = redirect
url = reverse("task_status", args=[result.id])
2020-01-21 06:35:58 +00:00
if args:
2022-05-14 17:57:27 +00:00
url += "?" + urlencode(args)
2020-01-21 06:35:58 +00:00
return url
def redirect_to_task_status(result, message=None, redirect=None):
return HttpResponseRedirect(task_status_url(result, message, redirect))