* Update yuan rate via Celery task

This commit is contained in:
Phil Zhitnikov 2023-12-07 07:07:41 +04:00
parent 1085107f2b
commit c0f17df7a6
4 changed files with 26 additions and 18 deletions

View File

@ -14,6 +14,11 @@ app.conf.beat_schedule = {
'task': 'store.tasks.schedule_cdek_status_update',
'schedule': timedelta(hours=1),
},
'update-yuan-rate-every-hour': {
'task': 'store.tasks.update_yuan_rate',
'schedule': timedelta(hours=1),
},
}

View File

@ -200,7 +200,6 @@ DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
CHECKLIST_ID_LENGTH = 10
COMMISSION_OVER_150K = 1.1
YUAN_RATE_UPDATE_PERIOD_MINUTES = 60
# Logging
SENTRY_DSN = "***REMOVED***"

View File

@ -68,22 +68,6 @@ class GlobalSettings(models.Model):
@property
def full_yuan_rate(self):
""" Get rate either from CurrencyAPI or from DB (if fresh enough) """
if self.yuan_rate_last_updated is not None:
diff_minutes = (timezone.now() - self.yuan_rate_last_updated).total_seconds() / 60
else:
diff_minutes = None
if diff_minutes is None or diff_minutes > settings.YUAN_RATE_UPDATE_PERIOD_MINUTES:
# Get fresh rate from API
rate = CurrencyAPIClient.get_cny_rate()
if rate:
# Save rate in DB for future usage
self.yuan_rate = rate
self.yuan_rate_last_updated = timezone.now()
self.save()
# Default
return self.yuan_rate + self.yuan_rate_commission

View File

@ -1,8 +1,10 @@
from celery import shared_task
from django.db.models import Q
from django.utils import timezone
from external_api.cdek import client as cdek_client, CDEKStatus
from .models import Checklist
from external_api.currency import client as CurrencyAPIClient
from .models import Checklist, GlobalSettings
@shared_task
@ -44,3 +46,21 @@ def schedule_cdek_status_update():
check_cdek_status.delay(order_id=obj.id)
return order_count
@shared_task(autoretry_for=(Exception,), retry_backoff=True, retry_kwargs={'max_retries': 5})
def update_yuan_rate():
# Get fresh rate from API
rate = CurrencyAPIClient.get_cny_rate()
if not rate:
raise Exception("Failed to get yuan rate")
print(f"Fetched new yuan rate: {rate}")
# Save rate in DB for future usage
settings = GlobalSettings.load()
settings.yuan_rate = rate
settings.yuan_rate_last_updated = timezone.now()
settings.save()
return rate