django - 使用 Python/Django 每小时更新数据库字段

标签 django python-3.x

假设我在一个表中有 1000 个 user_id,我将每小时运行一次以从 Google API 获取信息并更新该表中的 3 个字段。影响如何以及如何有效地完成?

我见过这个变体:

m = Module.objects.get(user_id=1).update(field_one=100, field_two=200, field_three=300)

还有这个:

m = Module.objects.get(user_id=1)
m.field_one = 100
m.field_two = 200
m.field_three = 300
m.save()

还有如何才能让它每小时运行一次并获取该信息?从来没有做过这样的事情。

最佳答案

每小时使用Redis、Celery设置异步任务队列。看这里https://realpython.com/blog/python/asynchronous-tasks-with-django-and-celery/有关如何为 Django 设置异步任务队列系统的更多信息。

这是tasks.py

的代码
from celery.task import periodic_task
from celery.schedules import crontab  


@periodic_task(run_every=crontab(minute=0, hour='*/1'))
def get_data_from_google_api():
    data_from_google =ping_google_api() # ping google api to get data
    return Module.objects.get(user_id=1).update(field_one= data_from_google['field_one'], field_two= data_from_google['field_two'], field_three= data_from_google['field_three'])

在这里查看更多信息:

  1. https://www.caktusgroup.com/blog/2014/06/23/scheduling-tasks-celery/
  2. How to run a Django celery task every 6am and 6pm daily?

关于django - 使用 Python/Django 每小时更新数据库字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38285797/

相关文章:

python - 如何使用 python 在图形中添加标记,如下所示?

python - 如何将列表的值与其索引的幂相加

python - python 中的标准偏差 - 浮点对象不可迭代

python - 创建一个假请求以在 django 中将 View 呈现为字符串

python - Django导入错误: Could not import settings

javascript - 如何进行 django 就地编辑以及基于 AJAX 的 django 无尽分页

python - 根据规则将数字转换为另一个数字

css - Django:在 CSS 中引用的图像在本地显示但在 Heroku 上不显示

django - 在 Django 模型中测试 'class Meta'

python - 如何实时更新 NetworkX 图?