因为你想打电话给
getHistoricRates()
以及
bulk_create()
你的逻辑
historical()
视图和cron作业,最好先将视图中的公共代码重构为单独的模块,例如
helpers.py
那就住在
views.py
和
cron.py
.
Help.Py
from .models import Fixerio_rates
def create_rates():
rates = getHistoricRates()
fixerio_rates = [Fixerio_rates(currency=currency, rate=rate)
for currency, rate in rates.items()]
Fixerio_rates.objects.bulk_create(fixerio_rates)
def getHistoricRates():
...
然后您可以从cron作业调用它:
克朗
from .helpers import create_rates
class MyCronJob(CronJobBase):
RUN_AT_TIMES = ['9:00']
schedule = Schedule(run_at_times=RUN_AT_TIMES)
code = 'fixerio.my_cron_job' # a unique code
def do(self):
create_rates()
从你的角度来看:
VIEW
from .helpers import create_rates
@require_http_methods(['GET', 'POST'])
def historical(request):
date_str = "2018-12-31"
if datetime.datetime.strptime(date_str,"%Y-%m-%d").weekday()<5:
create_rates()
return render(request, 'historical.html')