问题描述
当Django启动时,如何从mysql数据库加载资源并将其放入内存(Redis)中,以供所有应用程序使用。
我已经看到了此[
class MyAppConfig(AppConfig):
def ready(self):
但是他们提到在ready函数中不使用db连接。当我的网站启动时该怎么办??
我还可以在ready中设置缓存值吗?
<$ p来自django.core.cache的$ p>
导入缓存
cache.set()
由于您仅加载到Redis中,而不是创建保存在内存中并由网站中所有应用共享的模型实例,因此最好的方法是使用。
第二种解决方案是创建Django CLI,如 -文档:
由于您正在使用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:
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在启动时加载资源的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!