0

我的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') 

我想historical每天早上 9 点跑步,周末除外。

现在,我找不到任何关于如何运行现有方法或如何从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是我的应用程序的名称。

对此有什么想法吗?

4

1 回答 1

1

由于您希望从视图和 cron 作业中调用getHistoricRates()andbulk_create()逻辑historical(),因此最好先将视图中的通用代码重构为单独的模块 - 例如与andhelpers.py一起存在的模块。views.pycron.py

助手.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 作业中调用它:

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

而且从你的角度来看:

视图.py

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') 
于 2019-01-13T22:39:39.750 回答