fix session cache bug

This commit is contained in:
Leven
2023-02-10 11:19:47 +08:00
parent 1752b1d16f
commit a68fc3f307
13 changed files with 420 additions and 360 deletions

View File

@@ -1,14 +1,22 @@
import sys
import datetime
from utils.storage.memorystorage import MemoryStorage
from traceback import format_exc
import sys
import traceback
import logging
from django_redis import get_redis_connection
from utils.storage.kvstorage import KvStorage
logger = logging.getLogger(__name__)
try:
cache_storage = MemoryStorage()
cache_storage.set('MemoryStorage', str(datetime.datetime.now()))
redis_get = cache_storage.get('MemoryStorage')
redis_conn = get_redis_connection()
cache_storage = KvStorage(redis_conn)
cache_storage.set('test_redis_connection', str(datetime.datetime))
cache_storage.get('test_redis_connection')
cache_storage.delete('test_redis_connection')
logger.info("Redis连接成功set/get/delete测试通过...")
except Exception as e:
print("MemoryStorage Exception: {}".format(format_exc()))
cache_storage = None
logger.error("Redis无法连接请排查Redis配置...")
logger.error("{}".format(traceback.format_exc()))
sys.exit(1)

View File

@@ -5,8 +5,10 @@ from django.utils.log import DEFAULT_LOGGING
APP_ENV = os.getenv('APP_ENV')
if APP_ENV == 'dev':
DEBUG = True
from conf.local_settings_dev import REDIS_LOCATION, REDIS_PASSWORD
else:
DEBUG = False
from conf.local_settings import REDIS_LOCATION, REDIS_PASSWORD
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
@@ -16,13 +18,8 @@ SECRET_KEY = 'nxnm3#&2tat_c2i6%$y74a)t$(3irh^gpwaleoja1kdv30fmcm'
ALLOWED_HOSTS = ['*']
# 不安全的内部初始密码,用于检验新密码
UN_SEC_PASSWORD = ['1qaz@WSX', '1234@Abc']
# 创建日志的路径
LOG_PATH = os.path.join(BASE_DIR, 'log')
# 如果地址不存在则会自动创建log文件夹
if not os.path.isdir(LOG_PATH):
os.mkdir(LOG_PATH)
@@ -44,7 +41,7 @@ logging.config.dictConfig({
'handlers': {
# console logs to stderr
'console': {
"level": "DEBUG",
"level": "ERROR",
'class': 'logging.StreamHandler',
'formatter': 'default',
},
@@ -53,8 +50,8 @@ logging.config.dictConfig({
'class': 'logging.handlers.RotatingFileHandler',
'filename': os.path.join(LOG_PATH, "all.log"),
'formatter': 'default',
'maxBytes': 1024 * 1024 * 50, # 日志大小 10M
'backupCount': 24, # 备份数为 2# 简单格式
'maxBytes': 1024 * 1024 * 50,
'backupCount': 24,
'encoding': 'utf-8',
},
'django.server': DEFAULT_LOGGING['handlers']['django.server'],
@@ -63,7 +60,7 @@ logging.config.dictConfig({
# default for all undefined Python modules
'': {
'level': LOGLEVEL,
'handlers': ['file'],
'handlers': ['console', 'file'],
},
# Default runserver request logging
'django.server': DEFAULT_LOGGING['loggers']['django.server'],
@@ -71,18 +68,7 @@ logging.config.dictConfig({
})
# SESSION
# 只有在settings.SESSION_SAVE_EVERY_REQUEST 为True时才有效
SESSION_SAVE_EVERY_REQUEST = True
# 过期时间分钟
SESSION_COOKIE_AGE = 300
# False 会话cookie可以在用户浏览器中保持有效期。True关闭浏览器则Cookie失效。
SESSION_EXPIRE_AT_BROWSER_CLOSE = True
# session使用的存储方式
SESSION_ENGINE = 'django.contrib.sessions.backends.cache'
INSTALLED_APPS = [
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
@@ -90,19 +76,12 @@ INSTALLED_APPS = [
'resetpwd',
]
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
'LOCATION': 'unique-snowflake',
}
}
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
@@ -119,7 +98,6 @@ TEMPLATES = [
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
@@ -128,9 +106,18 @@ TEMPLATES = [
WSGI_APPLICATION = 'pwdselfservice.wsgi.application'
# 514 66050是AD中账号被禁用的特定代码这个可以在微软官网查到。
# 可能不是太准确,如果使用者能确定还有其它状态码,可以自行在此处添加
AD_ACCOUNT_DISABLE_CODE = [514, 66050]
CACHES = {
"default": {
"BACKEND": "django_redis.cache.RedisCache",
"LOCATION": "redis://{}/1".format(REDIS_LOCATION),
"OPTIONS": {
"CLIENT_CLASS": "django_redis.client.DefaultClient",
"PASSWORD": REDIS_PASSWORD,
"COMPRESSOR": "django_redis.compressors.zlib.ZlibCompressor",
"IGNORE_EXCEPTIONS": True,
}
}
}
AUTH_PASSWORD_VALIDATORS = [
{

View File

@@ -1,12 +1,3 @@
"""
WSGI config for pwdselfservice project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/2.1/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application