【问题标题】:Load static data on django startup using AppConfig ready method in Django 1.7在 Django 1.7 中使用 AppConfig ready 方法在 django 启动时加载静态数据
【发布时间】:2015-02-04 23:03:07
【问题描述】:

我有一些静态位置数据要加载,以便它在整个应用程序中都可用,就像内存中的缓存一样。

我试图在 AppConfig 上覆盖 ready(),但没有从数据库中加载数据,ready() 也被调用了两次。

from django.apps import AppConfig


class WebConfig(AppConfig):
    name = 'useraccount'
    verbose_name = 'User Accounts'
    locations = []

   def ready(self):
        print("Initialising...")
        location = self.get_model('Location')
        all_locations = location.objects.all()
        print(all_locations.count())
        self.locations = list(all_locations)

有什么提示吗?

【问题讨论】:

    标签: django django-1.7


    【解决方案1】:

    好吧,文档 (https://docs.djangoproject.com/en/1.7/ref/applications/#django.apps.AppConfig.ready) 告诉您避免在 ready() 函数中使用数据库调用,而且它可能会被调用两次。

    避免双重调用很容易:

    def ready(self):
        if self.has_attr('ready_run'): return
        self.ready_run = True
        ...
    

    但我仍在努力寻找正确的方法来进行基于数据库的初始化。如果我发现了什么,我会更新。

    【讨论】:

    • 不。据我所知,不支持在加载时运行数据库内容。我最终解决了我的问题,方法是将其重写为我们部署时运行的管理命令。管理命令生成数据并将其存储在数据库中,然后应用程序能够从数据库中获取数据。
    【解决方案2】:

    为了在应用中加载一些静态数据,创建一个单独的文件来获取数据

    # file /app_util.py
    def get_country():
        if Student.objects.all().count == 0:
           ... # your code 
        else:
           ...  # your code
    

    导入 app_util 并从 url.py 调用它

    # file /url.py
    admin.autodiscover()
    urlpatterns = patterns('equity_funds_investor_app',
                           # Examples:
                           url(r'^$', 'views.index'),
                          )
    # make a call to save/get method
    app_util.get_country()
    

    注意:当您想在您的应用程序启动时保存/获取一些数据时,您可以遵循相同的过程 当您在 runserver 之后发出第一个请求时,url.py 文件只处理一次 并调用您的自定义函数

    【讨论】:

      猜你喜欢
      • 2015-04-17
      • 1970-01-01
      • 2015-05-07
      • 2011-08-06
      • 2011-12-04
      • 2020-11-12
      • 2014-09-03
      • 1970-01-01
      相关资源
      最近更新 更多