Django在启动时加载资源 [英] Django load resources on startup

查看:314
本文介绍了Django在启动时加载资源的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当Django启动时,如何从mysql数据库加载资源并将其放入内存(Redis)中,以供所有应用程序使用。



我已经看到了此[ https://docs.djangoproject.com/en/dev/ref/applications/#django.apps.AppConfig.ready]

  class MyAppConfig(AppConfig):
def ready(self):

但是他们提到在ready函数中不使用db连接。当我的网站启动时该怎么办??



我还可以在ready中设置缓存值吗?



<$ p来自django.core.cache的$ p> 导入缓存
cache.set()


解决方案

由于您仅加载到Redis中,而不是创建保存在内存中并由网站中所有应用共享的模型实例,因此最好的方法是使用自定义管理命令


第二种解决方案是创建Django CLI,如 e4c5 -文档:


假设您已经设置了django项目,并且设置文件位于名为main的应用程序中,这就是初始化代码的方式

  import os,sys 

#设置环境
sys.path.append(os.getcwd())
os.environ.s etdefault( DJANGO_SETTINGS_MODULE, main.settings)

#设置django
导入django
django.setup()

#rest您的进口商品转到此处

来自main.models import MyModel

#使用Django模型的普通python代码转到此处

表示obj in MyModel.objects.all():
打印obj

以上可以作为

$执行b $ b

  python main / cli.py 


由于您正在使用Redis,您是否真的也需要将内容存储在内存缓存中?但是,如果您也需要这样做,可以通过CLI进行操作


How can I load resources from mysql database when Django starts up and put it in memory (Redis) to use by all the applications.

I have seen this [https://docs.djangoproject.com/en/dev/ref/applications/#django.apps.AppConfig.ready]

class MyAppConfig(AppConfig):
        def ready(self):

But they mention not use db connections inside ready function. How can do it when my Website starts.?

And Can I also set cache value inside ready ?

from django.core.cache import cache
cache.set()

解决方案

Since you are only loading into redis rather than creating instances of models that are held in memory and shared by all apps in your website, perhaps the best way is to use a custom management command.

A second solution is to create a Django CLI, as posted by e4c5 on the ex-documentation:

Supposing you have setup a django project, and the settings file is in an app named main, this is how you initialize your code

import os, sys

# Setup environ
sys.path.append(os.getcwd())
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "main.settings")

# Setup django
import django
django.setup()

# rest of your imports go here

from main.models import MyModel

# normal python code that makes use of Django models go here

for obj in MyModel.objects.all():
    print obj

The above can be executed as

python main/cli.py

Since you are using redis, do you really need to store things in memcache as well? But if you need to that too is something that can be done from a CLI

这篇关于Django在启动时加载资源的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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