新功能(dvadmin): 可配置取消redis,文件上传问题修复
parent
e17e5cc513
commit
a56e064924
|
@ -1,6 +1,7 @@
|
|||
from django.core.cache import cache
|
||||
from django.db.models import IntegerField, ForeignKey, CharField, CASCADE, Q
|
||||
|
||||
from application import settings
|
||||
from apps.vadmin.op_drf.models import CoreModel
|
||||
|
||||
|
||||
|
@ -42,7 +43,8 @@ class Menu(CoreModel):
|
|||
:return:
|
||||
"""
|
||||
try:
|
||||
interface_dict = cache.get('permission_interface_dict', {})
|
||||
interface_dict = cache.get('permission_interface_dict', {}) if getattr(settings, "REDIS_ENABLE",
|
||||
False) else {}
|
||||
except:
|
||||
interface_dict = {}
|
||||
if not interface_dict:
|
||||
|
@ -52,7 +54,8 @@ class Menu(CoreModel):
|
|||
interface_dict[ele.get('interface_method', '')].append(ele.get('interface_path'))
|
||||
else:
|
||||
interface_dict[ele.get('interface_method', '')] = [ele.get('interface_path')]
|
||||
cache.set('permission_interface_dict', interface_dict, 84600)
|
||||
if getattr(settings, "REDIS_ENABLE", False):
|
||||
cache.set('permission_interface_dict', interface_dict, 84600)
|
||||
return interface_dict
|
||||
|
||||
@classmethod
|
||||
|
@ -61,7 +64,8 @@ class Menu(CoreModel):
|
|||
清空缓存中的接口列表
|
||||
:return:
|
||||
"""
|
||||
cache.delete('permission_interface_dict')
|
||||
if getattr(settings, "REDIS_ENABLE", False):
|
||||
cache.delete('permission_interface_dict')
|
||||
|
||||
class Meta:
|
||||
verbose_name = '菜单管理'
|
||||
|
|
|
@ -30,7 +30,8 @@ class UserProfile(AbstractUser, CoreModel):
|
|||
|
||||
@property
|
||||
def get_user_interface_dict(self):
|
||||
interface_dict = cache.get(f'permission_interface_dict_{self.username}', {})
|
||||
interface_dict = cache.get(f'permission_interface_dict_{self.username}', {}) if \
|
||||
getattr(settings, "REDIS_ENABLE", False) else {}
|
||||
if not interface_dict:
|
||||
for ele in self.role.filter(status='1', menu__status='1').values('menu__interface_path',
|
||||
'menu__interface_method').distinct():
|
||||
|
@ -41,7 +42,8 @@ class UserProfile(AbstractUser, CoreModel):
|
|||
interface_dict[ele.get('menu__interface_method', '')].append(interface_path)
|
||||
else:
|
||||
interface_dict[ele.get('menu__interface_method', '')] = [interface_path]
|
||||
cache.set(f'permission_interface_dict_{self.username}', interface_dict, 84600)
|
||||
if getattr(settings, "REDIS_ENABLE", False):
|
||||
cache.set(f'permission_interface_dict_{self.username}', interface_dict, 84600)
|
||||
return interface_dict
|
||||
|
||||
@property
|
||||
|
@ -50,6 +52,7 @@ class UserProfile(AbstractUser, CoreModel):
|
|||
清空缓存中的接口列表
|
||||
:return:
|
||||
"""
|
||||
if not getattr(settings, "REDIS_ENABLE", False): return ""
|
||||
return cache.delete(f'permission_interface_dict_{self.username}')
|
||||
|
||||
class Meta:
|
||||
|
|
|
@ -1,6 +1,7 @@
|
|||
from django.core.cache import cache
|
||||
from rest_framework import serializers
|
||||
|
||||
from application import settings
|
||||
from apps.vadmin.op_drf.serializers import CustomModelSerializer
|
||||
from apps.vadmin.system.models import DictData, DictDetails, ConfigSettings, SaveFile, MessagePush, MessagePushUser
|
||||
from apps.vadmin.system.models import LoginInfor, OperationLog, CeleryLog
|
||||
|
@ -81,7 +82,8 @@ class DictDetailsCreateUpdateSerializer(CustomModelSerializer):
|
|||
"""
|
||||
|
||||
def save(self, **kwargs):
|
||||
cache.delete('system_dict_details')
|
||||
if getattr(settings, "REDIS_ENABLE", False):
|
||||
cache.delete('system_dict_details')
|
||||
return super().save(**kwargs)
|
||||
|
||||
class Meta:
|
||||
|
@ -120,7 +122,8 @@ class ConfigSettingsCreateUpdateSerializer(CustomModelSerializer):
|
|||
"""
|
||||
|
||||
def save(self, **kwargs):
|
||||
cache.delete('system_configKey')
|
||||
if getattr(settings, "REDIS_ENABLE", False):
|
||||
cache.delete('system_configKey')
|
||||
return super().save(**kwargs)
|
||||
|
||||
class Meta:
|
||||
|
@ -147,7 +150,10 @@ class SaveFileCreateUpdateSerializer(CustomModelSerializer):
|
|||
"""
|
||||
文件管理 创建/更新时的列化器
|
||||
"""
|
||||
file_url = serializers.CharField(source='file.url', read_only=True)
|
||||
file_url = serializers.SerializerMethodField(read_only=True)
|
||||
|
||||
def get_file_url(self, obj: SaveFile):
|
||||
return getattr(obj.file, "url", obj.file) if hasattr(obj, "file") else ""
|
||||
|
||||
def save(self, **kwargs):
|
||||
files = self.context.get('request').FILES.get('file')
|
||||
|
|
|
@ -72,7 +72,7 @@ class DictDetailsModelViewSet(CustomModelViewSet):
|
|||
:param kwargs:
|
||||
:return:
|
||||
"""
|
||||
dict_details_dic = cache.get('system_dict_details', {})
|
||||
dict_details_dic = cache.get('system_dict_details', {}) if getattr(settings, "REDIS_ENABLE", False) else {}
|
||||
if not dict_details_dic:
|
||||
queryset = self.filter_queryset(self.get_queryset())
|
||||
queryset_dic = queryset.order_by('sort').values('dict_data__dictType', 'dictLabel', 'dictValue',
|
||||
|
@ -83,7 +83,8 @@ class DictDetailsModelViewSet(CustomModelViewSet):
|
|||
dict_details_dic[dictType].append(ele)
|
||||
else:
|
||||
dict_details_dic[dictType] = [ele]
|
||||
cache.set('system_dict_details', dict_details_dic, 84600)
|
||||
if getattr(settings, "REDIS_ENABLE", False):
|
||||
cache.set('system_dict_details', dict_details_dic, 84600)
|
||||
return SuccessResponse(dict_details_dic.get(kwargs.get('pk'), []))
|
||||
|
||||
def clearCache(self, request: Request, *args, **kwargs):
|
||||
|
@ -94,7 +95,8 @@ class DictDetailsModelViewSet(CustomModelViewSet):
|
|||
:param kwargs:
|
||||
:return:
|
||||
"""
|
||||
cache.delete('system_dict_details')
|
||||
if getattr(settings, "REDIS_ENABLE", False):
|
||||
cache.delete('system_dict_details')
|
||||
return SuccessResponse(msg='清理成功!')
|
||||
|
||||
def export(self, request: Request, *args, **kwargs):
|
||||
|
@ -137,12 +139,13 @@ class ConfigSettingsModelViewSet(CustomModelViewSet):
|
|||
:param kwargs:
|
||||
:return:
|
||||
"""
|
||||
config_key_dic = cache.get('system_configKey')
|
||||
config_key_dic = cache.get('system_configKey') if getattr(settings, "REDIS_ENABLE", False) else ""
|
||||
if not config_key_dic:
|
||||
queryset = self.filter_queryset(self.get_queryset())
|
||||
config_key_dic = {ele.get('configKey'): ele.get('configValue') for ele in
|
||||
queryset.values('configValue', 'configKey')}
|
||||
cache.set('system_configKey', config_key_dic, 84600)
|
||||
if getattr(settings, "REDIS_ENABLE", False):
|
||||
cache.set('system_configKey', config_key_dic, 84600)
|
||||
return SuccessResponse(msg=config_key_dic.get(kwargs.get('pk'), ''))
|
||||
|
||||
def clearCache(self, request: Request, *args, **kwargs):
|
||||
|
@ -153,7 +156,8 @@ class ConfigSettingsModelViewSet(CustomModelViewSet):
|
|||
:param kwargs:
|
||||
:return:
|
||||
"""
|
||||
cache.delete('system_configKey')
|
||||
if getattr(settings, "REDIS_ENABLE", False):
|
||||
cache.delete('system_configKey')
|
||||
return SuccessResponse(msg='清理成功!')
|
||||
|
||||
|
||||
|
@ -173,6 +177,13 @@ class SaveFileModelViewSet(CustomModelViewSet):
|
|||
search_fields = ('configName',)
|
||||
ordering = '-create_datetime' # 默认排序
|
||||
|
||||
def create(self, request: Request, *args, **kwargs):
|
||||
serializer = self.get_serializer(data=request.data)
|
||||
serializer.is_valid(raise_exception=True)
|
||||
self.perform_create(serializer)
|
||||
headers = self.get_success_headers(serializer.data)
|
||||
return SuccessResponse(serializer.data, status=201, headers=headers)
|
||||
|
||||
def clearsavefile(self, request: Request, *args, **kwargs):
|
||||
"""
|
||||
清理废弃文件
|
||||
|
@ -185,8 +196,8 @@ class SaveFileModelViewSet(CustomModelViewSet):
|
|||
file_list = get_all_files(os.path.join(settings.MEDIA_ROOT, 'system'))
|
||||
queryset_files = [os.path.join(os.path.join(settings.MEDIA_ROOT) + os.sep, ele) for ele in
|
||||
list(self.get_queryset().values_list('file', flat=True))]
|
||||
|
||||
delete_list = list(set(file_list) - set(queryset_files))
|
||||
queryset_files_dir = set(map(lambda absdir: os.path.abspath(absdir), queryset_files))
|
||||
delete_list = list(set(file_list) - queryset_files_dir)
|
||||
# 进行文件删除操作
|
||||
delete_files(delete_list)
|
||||
# 递归删除空文件
|
||||
|
|
|
@ -92,7 +92,7 @@ class RedisOpAuthJwtAuthentication(OpAuthJwtAuthentication):
|
|||
|
||||
def authenticate(self, request):
|
||||
res = super().authenticate(request)
|
||||
if res:
|
||||
if res and getattr(settings, "REDIS_ENABLE", False):
|
||||
user, token = res
|
||||
session_id = jwt_get_session_id(token)
|
||||
key = f"{self.prefix}_{session_id}_{user.username}"
|
||||
|
|
|
@ -306,7 +306,7 @@ class CacheResponse(object):
|
|||
is_no_cache = True
|
||||
response = None
|
||||
if not is_no_cache:
|
||||
response = self.cache.get(key)
|
||||
response = self.cache.get(key) if getattr(settings, "REDIS_ENABLE", False) else None
|
||||
if not response:
|
||||
response = view_method(view_instance, request, *args, **kwargs)
|
||||
response = view_instance.finalize_response(request, response, *args, **kwargs)
|
||||
|
@ -314,10 +314,11 @@ class CacheResponse(object):
|
|||
|
||||
if not response.status_code >= 400 or self.cache_errors:
|
||||
if not is_no_cache:
|
||||
if isinstance(response, Response):
|
||||
self.cache.set(key, response.data, self.timeout)
|
||||
else:
|
||||
self.cache.set(key, response, self.timeout)
|
||||
if getattr(settings, "REDIS_ENABLE", False):
|
||||
if isinstance(response, Response):
|
||||
self.cache.set(key, response.data, self.timeout)
|
||||
else:
|
||||
self.cache.set(key, response, self.timeout)
|
||||
handle_refresh_cache_fun = getattr(view_instance, 'handle_refresh_cache', None)
|
||||
if handle_refresh_cache_fun:
|
||||
handle_refresh_cache_fun(request=request, key=key, cache=self.cache)
|
||||
|
|
|
@ -31,7 +31,8 @@ class LogoutView(APIView):
|
|||
user.user_secret = uuid4()
|
||||
user.save()
|
||||
key = f"{self.prefix}_{user.username}"
|
||||
cache.delete(key)
|
||||
if getattr(settings, "REDIS_ENABLE", False):
|
||||
cache.delete(key)
|
||||
return SuccessResponse()
|
||||
|
||||
|
||||
|
@ -87,7 +88,8 @@ class LoginView(ObtainJSONWebToken):
|
|||
username = user.username
|
||||
session_id = jwt_get_session_id(token)
|
||||
key = f"{self.prefix}_{session_id}_{username}"
|
||||
cache.set(key, token, self.ex.total_seconds())
|
||||
if getattr(settings, "REDIS_ENABLE", False):
|
||||
cache.set(key, token, self.ex.total_seconds())
|
||||
self.save_login_infor(request, '登录成功', session_id=session_id)
|
||||
if self.JWT_AUTH_COOKIE and token:
|
||||
expiration = (datetime.datetime.utcnow() + self.ex)
|
||||
|
|
|
@ -10,6 +10,7 @@ from django.core.cache import cache
|
|||
from django.urls.resolvers import ResolverMatch
|
||||
from user_agents import parse
|
||||
|
||||
from application import settings
|
||||
from apps.vadmin.utils.authentication import OpAuthJwtAuthentication
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
@ -161,11 +162,12 @@ def get_login_location(request, *args, **kwargs):
|
|||
:param kwargs:
|
||||
:return:
|
||||
"""
|
||||
if not getattr(settings, "ENABLE_LOGIN_LOCATION", False): return ""
|
||||
import requests
|
||||
import eventlet # 导入eventlet这个模块
|
||||
request_ip = get_request_ip(request)
|
||||
# 从缓存中获取
|
||||
location = cache.get(request_ip)
|
||||
location = cache.get(request_ip) if getattr(settings, "REDIS_ENABLE", False) else ""
|
||||
if location:
|
||||
return location
|
||||
# 通过api 获取,再缓存redis
|
||||
|
@ -176,7 +178,8 @@ def get_login_location(request, *args, **kwargs):
|
|||
r = requests.get(apiurl)
|
||||
content = r.content.decode('GBK')
|
||||
location = str(content).replace('\r', '').replace('\n', '')[:64]
|
||||
cache.set(request_ip, location, 86400)
|
||||
if getattr(settings, "REDIS_ENABLE", False):
|
||||
cache.set(request_ip, location, 86400)
|
||||
return location
|
||||
except Exception as e:
|
||||
pass
|
||||
|
|
|
@ -44,3 +44,5 @@ API_LOG_ENABLE = True
|
|||
API_LOG_METHODS = ['POST', 'DELETE', 'PUT'] # 'ALL' or ['POST', 'DELETE']
|
||||
# 接口权限
|
||||
INTERFACE_PERMISSION = True
|
||||
# 是否开启
|
||||
ENABLE_LOGIN_LOCATION = False
|
||||
|
|
Loading…
Reference in New Issue