Django / Python中的日常流程 [英] Everyday process in Django/Python

查看:99
本文介绍了Django / Python中的日常流程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个功能,从一些网站获取当前的美元币值:

I have a function that gets current currency of dollar from some site:

def update_currency(request):
    import urllib2
    import ast
    from django.conf import settings
    s = urllib2.urlopen('https://api.privatbank.ua/p24api/pubinfo?exchange=&json&coursid=11').read(1000)
    data = ast.literal_eval(s)  #parse string list to list
    settings.CURRENCY_USD = float(data[2]['sale'])
    return redirect(reverse('manager_page'))

按按钮更新货币。但是,如果经理忘了这样做,那么货币是不实际的。所以我需要这个功能在某个时候每天叫一次。如何实现?

Manager update currency by pressing button. But what if manager forgot to do this, then currency is not actual. So I need this function to be called one time per day at some time. How to implement it?

我在 settings.py 中保存货币,因为这种方法 update_currency 需要几秒钟才能从服务器获取货币,而且每次客户购买某些东西都不需要它。

I'm saving currency in settings.py, because this method update_currency takes a few seconds to get currency from server, and I don't want it every time a customer buy something

推荐答案

您可以通过 CRON ,或者 芹菜 在Django。
我建议你遵循以下步骤:

You can schedule routine tasks by CRON in CLI or Celery in Django. I suggesting you that follow below steps:


  1. 将数据存储在设置文件中(存储在db或JSON文件或XML文件中)

  2. 制作Django管理指令,例如 update_currency 运行 update_currency function

  3. 在特定时间内使用CRON文件或设置芹菜,以运行 ./ manage.py update_currency 命令。

  1. store data out of settings file(store in db or JSON file or XML file)
  2. Make a Django management instruction for example update_currency that running update_currency function.
  3. make a CRON file or setup celery for running ./manage.py update_currency command in certain time of days.

更新:
如果您希望将数据存储在数据库中,您可以创建新的模型并使其这个模型与其他模型之间的一对多关系,我建议你重写这个模型的保存方法,如下所示:

Update: If you want store data in Database you can create new Model and make One-To-Many relation between this model to other models, i suggesting to you that override save method of this Model similar below:

class Currency(models.Model):
    value = models.IntegerField()
    ...
    def save(self, *args, **kwargs):
        if Currency.objects.all().count()  > 0 and self != Currency.objects.all()[0]:
            obj = Currency.objects.all()[0]
            obj.value = self.value
            obj.save(*args, **kwargs)
        else:
            super(Currency, self).save(*args, **kwargs)
    ...

通过保存方法,您在下次最多只能有一个实例。

by upon save method you have maximum only one instance in next times.

还要感谢@martinarroyo, django-priodically 项目非常完美,非常有用。

Also by thanks of @martinarroyo, django-priodically project is very perfect and so useful.

这篇关于Django / Python中的日常流程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆