在django_cron上运行特定的views.py方法

时间:2019-01-13 18:26:37

标签: python django django-cron

我的views.py文件中有此方法:

def getHistoricRates():
    """ Here we have the function that will retrieve the historical rates from fixer.io, since last month """
    rates = {}
    response = urlopen('http://data.fixer.io/api/2018-12-31?access_key=c2f5070ad78b0748111281f6475c0bdd')
    data = response.read()
    rdata = json.loads(data.decode(), parse_float=float) 
    rates_from_rdata = rdata.get('rates', {})
    for rate_symbol in ['USD', 'GBP', 'HKD', 'AUD', 'JPY', 'SEK', 'NOK', 'EUR']:
        try:
            rates[rate_symbol] = rates_from_rdata[rate_symbol]
        except KeyError:
            logging.warning('rate for {} not found in rdata'.format(rate_symbol)) 
            pass

    return 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:
        rates = getHistoricRates()
        fixerio_rates = [Fixerio_rates(currency=currency, rate=rate)
                     for currency, rate in rates.items()]
        Fixerio_rates.objects.bulk_create(fixerio_rates) 
        return render(request, 'historical.html') 

除了周末,我想每天早上9点运行historical

现在,我找不到任何有关如何运行现有方法或如何从cron.py文件进行调用的示例。

我确实为django_cron配置了所有内容,但我只是想不出如何在我的cron文件中“使用”此方法在特定时间运行它。

这是我到目前为止的cron.py文件:

from django_cron import CronJobBase, Schedule
from .views import historical

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):
        pass    # do your thing here

fixerio是我应用程序的名称。

对此有何想法?

1 个答案:

答案 0 :(得分:1)

由于您希望同时从getHistoricRates()视图和cron作业中调用bulk_create()historical()逻辑,因此最好先从该视图进入一个单独的模块-例如进入helpers.pyviews.py的{​​{1}}。

helpers.py

cron.py

然后您可以从cron作业中调用它:

cron.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():
    ...

从您的角度来看:

views.py

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