django.core.exceptions.ImproperlyConfigured: Requested setting CACHES, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings
django.core.exceptions.ImproperlyConfigured: Requested setting CACHES, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.
django.core.exceptions.配置不正确:已请求的设置缓存,但未配置设置。必须定义环境变量DJANGO_SETTINGS_MODULE或调用设置。访问设置之前配置()。
原因:已经安装了django-redis,并在dev.py配置文件中配置了CACHES信息,但在坐测试的时候,没有把Django的配置文件加载进来
from django.core.cache import cache
cache.set('Django_test', 'success')
settings.py:
CACHES = {
"default": {
"BACKEND": "django_redis.cache.RedisCache",
"LOCATION": "redis://127.0.0.1:6379/2",
"OPTIONS": {
"CLIENT_CLASS": "django_redis.client.DefaultClient",
"CONNECTION_POOL_KWARGS": {"max_connections": 100}
# "PASSWORD": "123",
}
}
}
解决: 做测试环境,加载DJANGO_SETTINGS_MODULE
import os
if __name__ == '__main__':
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'luffy_api1.settings.dev')
import django
django.setup()
from django.core.cache import cache
cache.set('Django_test', 'success')