commit
7b9cdec1a6
|
@ -8,6 +8,7 @@ https://docs.djangoproject.com/en/3.2/howto/deployment/asgi/
|
|||
"""
|
||||
|
||||
import os
|
||||
|
||||
from django.core.asgi import get_asgi_application
|
||||
from channels.auth import AuthMiddlewareStack
|
||||
from channels.routing import ProtocolTypeRouter, URLRouter
|
||||
|
@ -15,7 +16,6 @@ os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'application.settings')
|
|||
os.environ["DJANGO_ALLOW_ASYNC_UNSAFE"] = "true"
|
||||
|
||||
|
||||
|
||||
http_application = get_asgi_application()
|
||||
from application.routing import websocket_urlpatterns
|
||||
application = ProtocolTypeRouter({
|
||||
|
@ -25,4 +25,4 @@ application = ProtocolTypeRouter({
|
|||
websocket_urlpatterns #指明路由文件是devops/routing.py
|
||||
)
|
||||
),
|
||||
})
|
||||
})
|
||||
|
|
|
@ -170,92 +170,117 @@ CORS_ALLOW_CREDENTIALS = True # 指明在跨域访问中,后端是否支持
|
|||
# ********************* channels配置 ******************* #
|
||||
# ================================================= #
|
||||
ASGI_APPLICATION = 'application.asgi.application'
|
||||
CHANNEL_LAYERS = {
|
||||
"default": {
|
||||
"BACKEND": "channels.layers.InMemoryChannelLayer"
|
||||
if not locals().get('REDIS_HOST', ""):
|
||||
CHANNEL_LAYERS = {
|
||||
"default": {
|
||||
"BACKEND": "channels.layers.InMemoryChannelLayer"
|
||||
}
|
||||
}
|
||||
else:
|
||||
REDIS_URL = locals().get('REDIS_URL', "")
|
||||
CHANNEL_LAYERS = {
|
||||
'default': {
|
||||
'BACKEND': 'channels_redis.core.RedisChannelLayer',
|
||||
'CONFIG': {
|
||||
"hosts": [(REDIS_URL)], # 需修改
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
# CHANNEL_LAYERS = {
|
||||
# 'default': {
|
||||
# 'BACKEND': 'channels_redis.core.RedisChannelLayer',
|
||||
# 'CONFIG': {
|
||||
# "hosts": [('127.0.0.1', 6379)], #需修改
|
||||
# },
|
||||
# },
|
||||
# }
|
||||
|
||||
|
||||
# ================================================= #
|
||||
# ********************* 日志配置 ******************* #
|
||||
# ================================================= #
|
||||
|
||||
# log 配置部分BEGIN #
|
||||
# # ================================================= #
|
||||
# # ********************* 日志配置 ******************* #
|
||||
# # ================================================= #
|
||||
# # log 配置部分BEGIN #
|
||||
SERVER_LOGS_FILE = os.path.join(BASE_DIR, "logs", "server.log")
|
||||
ERROR_LOGS_FILE = os.path.join(BASE_DIR, "logs", "error.log")
|
||||
LOGS_FILE = os.path.join(BASE_DIR, "logs")
|
||||
if not os.path.exists(os.path.join(BASE_DIR, "logs")):
|
||||
os.makedirs(os.path.join(BASE_DIR, "logs"))
|
||||
|
||||
# 格式:[2020-04-22 23:33:01][micoservice.apps.ready():16] [INFO] 这是一条日志:
|
||||
# 格式:[日期][模块.函数名称():行号] [级别] 信息
|
||||
STANDARD_LOG_FORMAT = (
|
||||
"[%(asctime)s][%(name)s.%(funcName)s():%(lineno)d] [%(levelname)s] %(message)s"
|
||||
)
|
||||
CONSOLE_LOG_FORMAT = (
|
||||
"[%(asctime)s][%(name)s.%(funcName)s():%(lineno)d] [%(levelname)s] %(message)s"
|
||||
)
|
||||
LOGGING = {
|
||||
"version": 1,
|
||||
"disable_existing_loggers": False,
|
||||
"formatters": {
|
||||
"servers": {
|
||||
"format": "%(message)s",
|
||||
"standard": {"format": STANDARD_LOG_FORMAT},
|
||||
"console": {
|
||||
"format": CONSOLE_LOG_FORMAT,
|
||||
"datefmt": "%Y-%m-%d %H:%M:%S",
|
||||
}
|
||||
},
|
||||
"file": {
|
||||
"format": CONSOLE_LOG_FORMAT,
|
||||
"datefmt": "%Y-%m-%d %H:%M:%S",
|
||||
},
|
||||
},
|
||||
"handlers": {
|
||||
"servers": {
|
||||
"logging_levels": ["info", "error", "warning"],
|
||||
"class": "dvadmin.utils.log.InterceptTimedRotatingFileHandler", # 这个路径看你本地放在哪里(下面的log文件)
|
||||
"filename": os.path.join(LOGS_FILE, "server.log"),
|
||||
"when": "D",
|
||||
"interval": 1,
|
||||
"file": {
|
||||
"level": "INFO",
|
||||
"class": "logging.handlers.RotatingFileHandler",
|
||||
"filename": SERVER_LOGS_FILE,
|
||||
"maxBytes": 1024 * 1024 * 100, # 100 MB
|
||||
"backupCount": 1,
|
||||
"formatter": "servers",
|
||||
"backupCount": 5, # 最多备份5个
|
||||
"formatter": "standard",
|
||||
"encoding": "utf-8",
|
||||
}
|
||||
},
|
||||
"error": {
|
||||
"level": "ERROR",
|
||||
"class": "logging.handlers.RotatingFileHandler",
|
||||
"filename": ERROR_LOGS_FILE,
|
||||
"maxBytes": 1024 * 1024 * 100, # 100 MB
|
||||
"backupCount": 3, # 最多备份3个
|
||||
"formatter": "standard",
|
||||
"encoding": "utf-8",
|
||||
},
|
||||
"console": {
|
||||
"level": "INFO",
|
||||
"class": "logging.StreamHandler",
|
||||
"formatter": "console",
|
||||
},
|
||||
|
||||
},
|
||||
"loggers": {
|
||||
# default日志
|
||||
'django': {
|
||||
'handlers': ['servers'],
|
||||
'propagate': False,
|
||||
'level': "INFO"
|
||||
"": {
|
||||
"handlers": ["console", "error", "file"],
|
||||
"level": "INFO",
|
||||
},
|
||||
'': {
|
||||
'handlers': ['servers'],
|
||||
'propagate': False,
|
||||
'level': "ERROR"
|
||||
"django": {
|
||||
"handlers": ["console", "error", "file"],
|
||||
"level": "INFO",
|
||||
"propagate": False,
|
||||
},
|
||||
'celery': {
|
||||
'handlers': ['servers'],
|
||||
'handlers': ["console", "error", "file"],
|
||||
'propagate': False,
|
||||
'level': "INFO"
|
||||
},
|
||||
'django.db.backends': {
|
||||
'handlers': ['servers'],
|
||||
'handlers': ["console", "error", "file"],
|
||||
'propagate': False,
|
||||
'level': "INFO"
|
||||
},
|
||||
'django.request': {
|
||||
'handlers': ['servers'],
|
||||
'handlers': ["console", "error", "file"],
|
||||
'propagate': False,
|
||||
'level': "DEBUG"
|
||||
},
|
||||
"uvicorn.error": {
|
||||
"level": "INFO",
|
||||
"handlers": ["servers"],
|
||||
"handlers": ["console", "error", "file"],
|
||||
},
|
||||
"uvicorn.access": {
|
||||
"handlers": ["servers"],
|
||||
"level": "INFO",
|
||||
"propagate": False
|
||||
"handlers": ["console", "error", "file"],
|
||||
"level": "INFO"
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
# ================================================= #
|
||||
# *************** REST_FRAMEWORK配置 *************** #
|
||||
# ================================================= #
|
||||
|
|
|
@ -11,20 +11,17 @@ from jwt import InvalidSignatureError
|
|||
from rest_framework.request import Request
|
||||
|
||||
from application import settings
|
||||
from dvadmin.system.models import MessageCenter, Users, MessageCenterTargetUser
|
||||
from dvadmin.system.views.message_center import MessageCenterTargetUserSerializer
|
||||
from dvadmin.utils.serializers import CustomModelSerializer
|
||||
|
||||
send_dict = {}
|
||||
|
||||
|
||||
# 发送消息结构体
|
||||
def set_message(sender, msg_type, msg, unread=0):
|
||||
def set_message(sender, msg_type, msg, refresh_unread=False):
|
||||
text = {
|
||||
'sender': sender,
|
||||
'contentType': msg_type,
|
||||
'content': msg,
|
||||
'unread': unread
|
||||
'refresh_unread': refresh_unread
|
||||
}
|
||||
return text
|
||||
|
||||
|
@ -62,10 +59,14 @@ class DvadminWebSocket(AsyncJsonWebsocketConsumer):
|
|||
decoded_result = jwt.decode(self.service_uid, settings.SECRET_KEY, algorithms=["HS256"])
|
||||
if decoded_result:
|
||||
self.user_id = decoded_result.get('user_id')
|
||||
self.chat_group_name = "user_" + str(self.user_id)
|
||||
self.room_name = "user_" + str(self.user_id)
|
||||
# 收到连接时候处理,
|
||||
await self.channel_layer.group_add(
|
||||
self.chat_group_name,
|
||||
"dvadmin",
|
||||
self.channel_name
|
||||
)
|
||||
await self.channel_layer.group_add(
|
||||
self.room_name,
|
||||
self.channel_name
|
||||
)
|
||||
await self.accept()
|
||||
|
@ -77,13 +78,14 @@ class DvadminWebSocket(AsyncJsonWebsocketConsumer):
|
|||
else:
|
||||
await self.send_json(
|
||||
set_message('system', 'SYSTEM', "请查看您的未读消息~",
|
||||
unread=unread_count))
|
||||
refresh_unread=True))
|
||||
except InvalidSignatureError:
|
||||
await self.disconnect(None)
|
||||
|
||||
async def disconnect(self, close_code):
|
||||
# Leave room group
|
||||
await self.channel_layer.group_discard(self.chat_group_name, self.channel_name)
|
||||
await self.channel_layer.group_discard(self.room_name, self.channel_name)
|
||||
await self.channel_layer.group_discard("dvadmin", self.channel_name)
|
||||
print("连接关闭")
|
||||
try:
|
||||
await self.close(close_code)
|
||||
|
@ -99,13 +101,13 @@ class MegCenter(DvadminWebSocket):
|
|||
async def receive(self, text_data):
|
||||
# 接受客户端的信息,你处理的函数
|
||||
text_data_json = json.loads(text_data)
|
||||
message_id = text_data_json.get('message_id', None)
|
||||
user_list = await _get_message_center_instance(message_id)
|
||||
for send_user in user_list:
|
||||
await self.channel_layer.group_send(
|
||||
"user_" + str(send_user),
|
||||
{'type': 'push.message', 'json': text_data_json}
|
||||
)
|
||||
# message_id = text_data_json.get('message_id', None)
|
||||
# user_list = await _get_message_center_instance(message_id)
|
||||
# for send_user in user_list:
|
||||
# await self.channel_layer.group_send(
|
||||
# "user_" + str(send_user),
|
||||
# {'type': 'push.message', 'json': text_data_json}
|
||||
# )
|
||||
|
||||
async def push_message(self, event):
|
||||
"""消息发送"""
|
||||
|
@ -113,69 +115,18 @@ class MegCenter(DvadminWebSocket):
|
|||
await self.send(text_data=json.dumps(message))
|
||||
|
||||
|
||||
class MessageCreateSerializer(CustomModelSerializer):
|
||||
"""
|
||||
消息中心-新增-序列化器
|
||||
"""
|
||||
class Meta:
|
||||
model = MessageCenter
|
||||
fields = "__all__"
|
||||
read_only_fields = ["id"]
|
||||
|
||||
def websocket_push(user_id,message):
|
||||
username = "user_" + str(user_id)
|
||||
def websocket_push(room_name,message):
|
||||
"""
|
||||
主动推送
|
||||
@param room_name: 群组名称
|
||||
@param message: 消息内容
|
||||
"""
|
||||
channel_layer = get_channel_layer()
|
||||
async_to_sync(channel_layer.group_send)(
|
||||
username,
|
||||
room_name,
|
||||
{
|
||||
"type": "push.message",
|
||||
"json": message
|
||||
}
|
||||
)
|
||||
|
||||
def create_message_push(title: str, content: str, target_type: int=0, target_user: list=[], target_dept=None, target_role=None,
|
||||
message: dict = {'contentType': 'INFO', 'content': '测试~'}, request= Request):
|
||||
if message is None:
|
||||
message = {"contentType": "INFO", "content": None}
|
||||
if target_role is None:
|
||||
target_role = []
|
||||
if target_dept is None:
|
||||
target_dept = []
|
||||
data = {
|
||||
"title": title,
|
||||
"content": content,
|
||||
"target_type": target_type,
|
||||
"target_user":target_user,
|
||||
"target_dept":target_dept,
|
||||
"target_role":target_role
|
||||
}
|
||||
message_center_instance = MessageCreateSerializer(data=data,request=request)
|
||||
message_center_instance.is_valid(raise_exception=True)
|
||||
message_center_instance.save()
|
||||
users = target_user or []
|
||||
if target_type in [1]: # 按角色
|
||||
users = Users.objects.filter(role__id__in=target_role).values_list('id', flat=True)
|
||||
if target_type in [2]: # 按部门
|
||||
users = Users.objects.filter(dept__id__in=target_dept).values_list('id', flat=True)
|
||||
if target_type in [3]: # 系统通知
|
||||
users = Users.objects.values_list('id', flat=True)
|
||||
targetuser_data = []
|
||||
for user in users:
|
||||
targetuser_data.append({
|
||||
"messagecenter": message_center_instance.instance.id,
|
||||
"users": user
|
||||
})
|
||||
targetuser_instance = MessageCenterTargetUserSerializer(data=targetuser_data, many=True, request=request)
|
||||
targetuser_instance.is_valid(raise_exception=True)
|
||||
targetuser_instance.save()
|
||||
for user in users:
|
||||
username = "user_" + str(user)
|
||||
unread_count = async_to_sync(_get_message_unread)(user)
|
||||
channel_layer = get_channel_layer()
|
||||
async_to_sync(channel_layer.group_send)(
|
||||
username,
|
||||
{
|
||||
"type": "push.message",
|
||||
"json": {**message,'unread':unread_count}
|
||||
}
|
||||
)
|
||||
|
|
|
@ -397,12 +397,20 @@ class SystemConfig(CoreModel):
|
|||
return f"{self.title}"
|
||||
|
||||
def save(self, force_insert=False, force_update=False, using=None, update_fields=None):
|
||||
# from application.websocketConfig import websocket_push
|
||||
# websocket_push("dvadmin", message={"sender": 'system', "contentType": 'SYSTEM',
|
||||
# "content": '系统配置有变化~', "systemConfig": True})
|
||||
|
||||
super().save(force_insert, force_update, using, update_fields)
|
||||
dispatch.refresh_system_config() # 有更新则刷新系统配置
|
||||
|
||||
def delete(self, using=None, keep_parents=False):
|
||||
res = super().delete(using, keep_parents)
|
||||
dispatch.refresh_system_config()
|
||||
from application.websocketConfig import websocket_push
|
||||
websocket_push("dvadmin", message={"sender": 'system', "contentType": 'SYSTEM',
|
||||
"content": '系统配置有变化~', "systemConfig": True})
|
||||
|
||||
return res
|
||||
|
||||
|
||||
|
|
|
@ -8,6 +8,7 @@ from rest_framework import serializers
|
|||
from rest_framework.decorators import action, permission_classes
|
||||
from rest_framework.permissions import IsAuthenticated, AllowAny
|
||||
|
||||
from application.websocketConfig import websocket_push
|
||||
from dvadmin.system.models import MessageCenter, Users, MessageCenterTargetUser
|
||||
from dvadmin.utils.json_response import SuccessResponse, DetailResponse
|
||||
from dvadmin.utils.serializers import CustomModelSerializer
|
||||
|
@ -95,20 +96,6 @@ class MessageCenterTargetUserListSerializer(CustomModelSerializer):
|
|||
fields = "__all__"
|
||||
read_only_fields = ["id"]
|
||||
|
||||
def websocket_push(user_id, message):
|
||||
"""
|
||||
主动推送消息
|
||||
"""
|
||||
username = "user_"+str(user_id)
|
||||
print(103,message)
|
||||
channel_layer = get_channel_layer()
|
||||
async_to_sync(channel_layer.group_send)(
|
||||
username,
|
||||
{
|
||||
"type": "push.message",
|
||||
"json": message
|
||||
}
|
||||
)
|
||||
|
||||
class MessageCenterCreateSerializer(CustomModelSerializer):
|
||||
"""
|
||||
|
@ -129,19 +116,21 @@ class MessageCenterCreateSerializer(CustomModelSerializer):
|
|||
users = Users.objects.filter(dept__id__in=target_dept).values_list('id', flat=True)
|
||||
if target_type in [3]: # 系统通知
|
||||
users = Users.objects.values_list('id', flat=True)
|
||||
websocket_push("dvadmin", message={"sender": 'system', "contentType": 'SYSTEM',
|
||||
"content": '您有一条新消息~', "refresh_unread": True})
|
||||
targetuser_data = []
|
||||
for user in users:
|
||||
targetuser_data.append({
|
||||
"messagecenter": data.id,
|
||||
"users": user
|
||||
})
|
||||
if target_type in [1,2]:
|
||||
room_name = f"user_{user}"
|
||||
websocket_push(room_name, message={"sender": 'system', "contentType": 'SYSTEM',
|
||||
"content": '您有一条新消息~', "refresh_unread": True})
|
||||
targetuser_instance = MessageCenterTargetUserSerializer(data=targetuser_data, many=True, request=self.request)
|
||||
targetuser_instance.is_valid(raise_exception=True)
|
||||
targetuser_instance.save()
|
||||
for user in users:
|
||||
unread_count = MessageCenterTargetUser.objects.filter(users__id=user, is_read=False).count()
|
||||
websocket_push(user, message={"sender": 'system', "contentType": 'SYSTEM',
|
||||
"content": '您有一条新消息~', "unread": unread_count})
|
||||
return data
|
||||
|
||||
class Meta:
|
||||
|
@ -182,9 +171,9 @@ class MessageCenterViewSet(CustomModelViewSet):
|
|||
instance = self.get_object()
|
||||
serializer = self.get_serializer(instance)
|
||||
# 主动推送消息
|
||||
unread_count = MessageCenterTargetUser.objects.filter(users__id=user_id, is_read=False).count()
|
||||
websocket_push(user_id, message={"sender": 'system', "contentType": 'TEXT',
|
||||
"content": '您查看了一条消息~', "unread": unread_count})
|
||||
room_name = f"user_{user_id}"
|
||||
websocket_push(room_name, message={"sender": 'system', "contentType": 'TEXT',
|
||||
"content": '您查看了一条消息~', "refresh_unread": True})
|
||||
return DetailResponse(data=serializer.data, msg="获取成功")
|
||||
|
||||
@action(methods=['GET'], detail=False, permission_classes=[IsAuthenticated])
|
||||
|
@ -216,3 +205,10 @@ class MessageCenterViewSet(CustomModelViewSet):
|
|||
serializer = MessageCenterTargetUserListSerializer(queryset.messagecenter, many=False, request=request)
|
||||
data = serializer.data
|
||||
return DetailResponse(data=data, msg="获取成功")
|
||||
|
||||
@action(methods=['GET'], detail=False, permission_classes=[IsAuthenticated])
|
||||
def get_unread_msg(self, request):
|
||||
"""获取未读消息数量"""
|
||||
self_user_id = self.request.user.id
|
||||
count = MessageCenterTargetUser.objects.filter(users__id=self_user_id,is_read=False).count()
|
||||
return DetailResponse(data={"count":count}, msg="获取成功")
|
|
@ -13,6 +13,7 @@ from rest_framework import serializers
|
|||
from rest_framework.views import APIView
|
||||
|
||||
from application import dispatch
|
||||
from application.websocketConfig import websocket_push
|
||||
from dvadmin.system.models import SystemConfig
|
||||
from dvadmin.utils.json_response import DetailResponse, SuccessResponse, ErrorResponse
|
||||
from dvadmin.utils.models import get_all_models_objects
|
||||
|
@ -179,6 +180,8 @@ class SystemConfigViewSet(CustomModelViewSet):
|
|||
serializer = SystemConfigCreateSerializer(instance_obj, data=data)
|
||||
if serializer.is_valid(raise_exception=True):
|
||||
serializer.save()
|
||||
websocket_push("dvadmin", message={"sender": 'system', "contentType": 'SYSTEM',
|
||||
"content": '系统配置有变化~', "systemConfig": True})
|
||||
return DetailResponse(msg="保存成功")
|
||||
|
||||
def get_association_table(self, request):
|
||||
|
|
|
@ -1,134 +0,0 @@
|
|||
import logging
|
||||
import os.path
|
||||
import sys
|
||||
|
||||
from django.db import connection
|
||||
from loguru import logger
|
||||
|
||||
from logging.handlers import RotatingFileHandler
|
||||
|
||||
# 1.🎖️先声明一个类继承logging.Handler(制作一件品如的衣服)
|
||||
|
||||
from application.dispatch import is_tenants_mode
|
||||
|
||||
|
||||
class InterceptTimedRotatingFileHandler(RotatingFileHandler):
|
||||
"""
|
||||
自定义反射时间回滚日志记录器
|
||||
缺少命名空间
|
||||
"""
|
||||
|
||||
def __init__(self, filename, when='d', interval=1, backupCount=5, encoding="utf-8", delay=False, utc=False,
|
||||
maxBytes=1024 * 1024 * 100, atTime=None, logging_levels="all", format=None):
|
||||
super(InterceptTimedRotatingFileHandler, self).__init__(filename)
|
||||
filename = os.path.abspath(filename)
|
||||
# 定义默认格式
|
||||
if not format:
|
||||
format = "<green>{time:YYYY-MM-DD HH:mm:ss.SSS}</green> | <green>{extra[client_addr]:^18}</green> | <level>{level: <8}</level>| <cyan>{message}</cyan>"
|
||||
when = when.lower()
|
||||
# 2.🎖️需要本地用不同的文件名做为不同日志的筛选器
|
||||
logger.configure(
|
||||
handlers=[
|
||||
dict(sink=sys.stderr, format=format),
|
||||
],
|
||||
)
|
||||
self.logger_ = logger.bind(sime=filename, client_addr="-")
|
||||
self.filename = filename
|
||||
key_map = {
|
||||
'h': 'hour',
|
||||
'w': 'week',
|
||||
's': 'second',
|
||||
'm': 'minute',
|
||||
'd': 'day',
|
||||
}
|
||||
# 根据输入文件格式及时间回滚设立文件名称
|
||||
rotation = f"{maxBytes / 1024 / 1024}MB"
|
||||
retention = "%d %ss" % (backupCount, key_map[when])
|
||||
time_format = "{time:%Y-%m-%d_%H-%M-%S}"
|
||||
if when == "s":
|
||||
time_format = "{time:%Y-%m-%d_%H-%M-%S}"
|
||||
elif when == "m":
|
||||
time_format = "{time:%Y-%m-%d_%H-%M}"
|
||||
elif when == "h":
|
||||
time_format = "{time:%Y-%m-%d_%H}"
|
||||
elif when == "d":
|
||||
time_format = "{time:%Y-%m-%d}"
|
||||
elif when == "w":
|
||||
time_format = "{time:%Y-%m-%d}"
|
||||
level_keys = ["info"]
|
||||
# 3.🎖️构建一个筛选器
|
||||
levels = {
|
||||
"debug": lambda x: "DEBUG" == x['level'].name.upper() and x['extra'].get('sime') == filename,
|
||||
"error": lambda x: "ERROR" == x['level'].name.upper() and x['extra'].get('sime') == filename,
|
||||
"info": lambda x: "INFO" == x['level'].name.upper() and x['extra'].get('sime') == filename,
|
||||
"warning": lambda x: "WARNING" == x['level'].name.upper() and x['extra'].get('sime') == filename
|
||||
}
|
||||
# 4. 🎖️根据输出构建筛选器
|
||||
if isinstance(logging_levels, str):
|
||||
if logging_levels.lower() == "all":
|
||||
level_keys = levels.keys()
|
||||
elif logging_levels.lower() in levels:
|
||||
level_keys = [logging_levels]
|
||||
elif isinstance(logging_levels, (list, tuple)):
|
||||
level_keys = logging_levels
|
||||
for k, f in {_: levels[_] for _ in level_keys}.items():
|
||||
|
||||
# 5.🎖️为防止重复添加sink,而重复写入日志,需要判断是否已经装载了对应sink,防止其使用秘技:反复横跳。
|
||||
filename_fmt = filename.replace(".log", "_%s_%s.log" % (time_format, k))
|
||||
# noinspection PyUnresolvedReferences,PyProtectedMember
|
||||
file_key = {_._name: han_id for han_id, _ in self.logger_._core.handlers.items()}
|
||||
filename_fmt_key = "'{}'".format(filename_fmt)
|
||||
if filename_fmt_key in file_key:
|
||||
continue
|
||||
# self.logger_.remove(file_key[filename_fmt_key])
|
||||
self.logger_.add(
|
||||
filename_fmt,
|
||||
format=format,
|
||||
retention=retention,
|
||||
encoding=encoding,
|
||||
level=self.level,
|
||||
rotation=rotation,
|
||||
compression="zip", # 日志归档自行压缩文件
|
||||
delay=delay,
|
||||
enqueue=True,
|
||||
backtrace=True,
|
||||
filter=f
|
||||
)
|
||||
|
||||
def emit(self, record):
|
||||
try:
|
||||
level = self.logger_.level(record.levelname).name
|
||||
except ValueError:
|
||||
level = record.levelno
|
||||
|
||||
frame, depth = logging.currentframe(), 2
|
||||
# 6.🎖️把当前帧的栈深度回到发生异常的堆栈深度,不然就是当前帧发生异常而无法回溯
|
||||
while frame.f_code.co_filename == logging.__file__:
|
||||
frame = frame.f_back
|
||||
depth += 1
|
||||
# 设置自定义属性
|
||||
details = frame.f_locals.get('details', None)
|
||||
msg = self.format(record)
|
||||
bind = {}
|
||||
record_client = None
|
||||
if isinstance(record.args, dict):
|
||||
record_client = record.args.get('client_addr') or record.args.get('client')
|
||||
elif isinstance(record.args, tuple) and len(record.args) > 0:
|
||||
if ":" in str(record.args[0]):
|
||||
record_client = record.args[0]
|
||||
if msg.split("-") and len(msg.split("-")) == 2:
|
||||
msg = f"{msg.split('-')[1].strip(' ')}"
|
||||
elif isinstance(record.args[0], tuple) and len(record.args[0]) == 2:
|
||||
record_client = f"{record.args[0][0]}:{record.args[0][1]}"
|
||||
if msg.split("-") and len(msg.split("-")) == 2:
|
||||
msg = f"{msg.split('-')[1].strip(' ')}"
|
||||
client = record_client or (details and details.get('client'))
|
||||
if client:
|
||||
bind["client_addr"] = client
|
||||
if is_tenants_mode():
|
||||
bind["schema_name"] = connection.tenant.schema_name
|
||||
bind["domain_url"] = getattr(connection.tenant, 'domain_url', None)
|
||||
self.logger_ \
|
||||
.opt(depth=depth, exception=record.exc_info, colors=True, lazy=True) \
|
||||
.bind(**bind) \
|
||||
.log(level, msg)
|
|
@ -47,4 +47,3 @@ uvicorn==0.21.1
|
|||
gunicorn==20.1.0
|
||||
gevent==22.10.2
|
||||
websockets==10.4
|
||||
loguru==0.6.0
|
||||
|
|
|
@ -0,0 +1,18 @@
|
|||
Information about external resources
|
||||
|
||||
The following files are taken from external resources or trees.
|
||||
|
||||
Files: insQ.js
|
||||
insQ.min.js
|
||||
License: MIT
|
||||
Copyright: Zbyszek Tenerowicz
|
||||
Eryk Napierała <eryk.piast@gmail.com>
|
||||
Askar Yusupov <devex.soft@gmail.com>
|
||||
Dan Dascalescu <ddascalescu+github@gmail.com>
|
||||
Source: https://github.com/naugtur/insertionQuery v1.0.3
|
||||
|
||||
Files: immutable.js
|
||||
immutable.min.js
|
||||
License: MIT
|
||||
Copyright: 2014-present, Facebook, Inc
|
||||
Source: https://github.com/immutable-js/immutable-js/releases/tag/v3.8.2
|
File diff suppressed because it is too large
Load Diff
|
@ -0,0 +1,163 @@
|
|||
var insertionQ = (function () {
|
||||
"use strict";
|
||||
|
||||
var sequence = 100,
|
||||
isAnimationSupported = false,
|
||||
animation_string = 'animationName',
|
||||
keyframeprefix = '',
|
||||
domPrefixes = 'Webkit Moz O ms Khtml'.split(' '),
|
||||
pfx = '',
|
||||
elm = document.createElement('div'),
|
||||
options = {
|
||||
strictlyNew: true,
|
||||
timeout: 20
|
||||
};
|
||||
|
||||
if (elm.style.animationName) {
|
||||
isAnimationSupported = true;
|
||||
}
|
||||
|
||||
if (isAnimationSupported === false) {
|
||||
for (var i = 0; i < domPrefixes.length; i++) {
|
||||
if (elm.style[domPrefixes[i] + 'AnimationName'] !== undefined) {
|
||||
pfx = domPrefixes[i];
|
||||
animation_string = pfx + 'AnimationName';
|
||||
keyframeprefix = '-' + pfx.toLowerCase() + '-';
|
||||
isAnimationSupported = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
function listen(selector, callback) {
|
||||
var styleAnimation, animationName = 'insQ_' + (sequence++);
|
||||
|
||||
var eventHandler = function (event) {
|
||||
if (event.animationName === animationName || event[animation_string] === animationName) {
|
||||
if (!isTagged(event.target)) {
|
||||
callback(event.target);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
styleAnimation = document.createElement('style');
|
||||
styleAnimation.innerHTML = '@' + keyframeprefix + 'keyframes ' + animationName + ' { from { outline: 1px solid transparent } to { outline: 0px solid transparent } }' +
|
||||
"\n" + selector + ' { animation-duration: 0.001s; animation-name: ' + animationName + '; ' +
|
||||
keyframeprefix + 'animation-duration: 0.001s; ' + keyframeprefix + 'animation-name: ' + animationName + '; ' +
|
||||
' } ';
|
||||
|
||||
document.head.appendChild(styleAnimation);
|
||||
|
||||
var bindAnimationLater = setTimeout(function () {
|
||||
document.addEventListener('animationstart', eventHandler, false);
|
||||
document.addEventListener('MSAnimationStart', eventHandler, false);
|
||||
document.addEventListener('webkitAnimationStart', eventHandler, false);
|
||||
//event support is not consistent with DOM prefixes
|
||||
}, options.timeout); //starts listening later to skip elements found on startup. this might need tweaking
|
||||
|
||||
return {
|
||||
destroy: function () {
|
||||
clearTimeout(bindAnimationLater);
|
||||
if (styleAnimation) {
|
||||
document.head.removeChild(styleAnimation);
|
||||
styleAnimation = null;
|
||||
}
|
||||
document.removeEventListener('animationstart', eventHandler);
|
||||
document.removeEventListener('MSAnimationStart', eventHandler);
|
||||
document.removeEventListener('webkitAnimationStart', eventHandler);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
function tag(el) {
|
||||
el.QinsQ = true; //bug in V8 causes memory leaks when weird characters are used as field names. I don't want to risk leaking DOM trees so the key is not '-+-' anymore
|
||||
}
|
||||
|
||||
function isTagged(el) {
|
||||
return (options.strictlyNew && (el.QinsQ === true));
|
||||
}
|
||||
|
||||
function topmostUntaggedParent(el) {
|
||||
if (isTagged(el.parentNode)) {
|
||||
return el;
|
||||
} else {
|
||||
return topmostUntaggedParent(el.parentNode);
|
||||
}
|
||||
}
|
||||
|
||||
function tagAll(e) {
|
||||
tag(e);
|
||||
e = e.firstChild;
|
||||
for (; e; e = e.nextSibling) {
|
||||
if (e !== undefined && e.nodeType === 1) {
|
||||
tagAll(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
//aggregates multiple insertion events into a common parent
|
||||
function catchInsertions(selector, callback) {
|
||||
var insertions = [];
|
||||
//throttle summary
|
||||
var sumUp = (function () {
|
||||
var to;
|
||||
return function () {
|
||||
clearTimeout(to);
|
||||
to = setTimeout(function () {
|
||||
insertions.forEach(tagAll);
|
||||
callback(insertions);
|
||||
insertions = [];
|
||||
}, 10);
|
||||
};
|
||||
})();
|
||||
|
||||
return listen(selector, function (el) {
|
||||
if (isTagged(el)) {
|
||||
return;
|
||||
}
|
||||
tag(el);
|
||||
var myparent = topmostUntaggedParent(el);
|
||||
if (insertions.indexOf(myparent) < 0) {
|
||||
insertions.push(myparent);
|
||||
}
|
||||
sumUp();
|
||||
});
|
||||
}
|
||||
|
||||
//insQ function
|
||||
var exports = function (selector) {
|
||||
if (isAnimationSupported && selector.match(/[^{}]/)) {
|
||||
|
||||
if (options.strictlyNew) {
|
||||
tagAll(document.body); //prevents from catching things on show
|
||||
}
|
||||
return {
|
||||
every: function (callback) {
|
||||
return listen(selector, callback);
|
||||
},
|
||||
summary: function (callback) {
|
||||
return catchInsertions(selector, callback);
|
||||
}
|
||||
};
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
//allows overriding defaults
|
||||
exports.config = function (opt) {
|
||||
for (var o in opt) {
|
||||
if (opt.hasOwnProperty(o)) {
|
||||
options[o] = opt[o];
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
return exports;
|
||||
})();
|
||||
|
||||
if (typeof module !== 'undefined' && typeof module.exports !== 'undefined') {
|
||||
module.exports = insertionQ;
|
||||
}
|
|
@ -1,3 +1,9 @@
|
|||
// redoc-init.js
|
||||
// https://github.com/axnsan12/drf-yasg
|
||||
// Copyright 2017 - 2021, Cristian V. <cristi@cvjd.me>
|
||||
// This file is licensed under the BSD 3-Clause License.
|
||||
// License text available at https://opensource.org/licenses/BSD-3-Clause
|
||||
|
||||
"use strict";
|
||||
|
||||
var currentPath = window.location.protocol + "//" + window.location.host + window.location.pathname;
|
||||
|
|
|
@ -0,0 +1,22 @@
|
|||
The MIT License (MIT)
|
||||
|
||||
Copyright (c) 2015, Rebilly, Inc.
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
|
File diff suppressed because one or more lines are too long
|
@ -0,0 +1,23 @@
|
|||
<html>
|
||||
<head>
|
||||
<script type="text/javascript" charset="utf-8">
|
||||
// Map of projects that support handling 404s.
|
||||
var supportedProjects = {
|
||||
'ReDoc': 'https://redocly.github.io/redoc'
|
||||
};
|
||||
|
||||
var project = window.location.pathname.split('/')[1];
|
||||
|
||||
// Always fallback to rebilly.com redirect.
|
||||
var loc = 'https://www.rebilly.com/';
|
||||
|
||||
if (supportedProjects.hasOwnProperty(project)) {
|
||||
if (typeof supportedProjects[project] === 'string') {
|
||||
loc = supportedProjects[project];
|
||||
}
|
||||
}
|
||||
window.location.href = loc;
|
||||
</script>
|
||||
</head>
|
||||
<body></body>
|
||||
</html>
|
|
@ -0,0 +1,22 @@
|
|||
The MIT License (MIT)
|
||||
|
||||
Copyright (c) 2015-present, Rebilly, Inc.
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
|
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
|
@ -0,0 +1,202 @@
|
|||
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright [yyyy] [name of copyright owner]
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
|
@ -0,0 +1,2 @@
|
|||
swagger-ui
|
||||
Copyright 2020-2021 SmartBear Software Inc.
|
|
@ -4,8 +4,6 @@
|
|||
<title>Swagger UI: OAuth2 Redirect</title>
|
||||
</head>
|
||||
<body>
|
||||
</body>
|
||||
</html>
|
||||
<script>
|
||||
'use strict';
|
||||
function run () {
|
||||
|
@ -20,19 +18,20 @@
|
|||
qp = location.search.substring(1);
|
||||
}
|
||||
|
||||
arr = qp.split("&")
|
||||
arr.forEach(function (v,i,_arr) { _arr[i] = '"' + v.replace('=', '":"') + '"';})
|
||||
arr = qp.split("&");
|
||||
arr.forEach(function (v,i,_arr) { _arr[i] = '"' + v.replace('=', '":"') + '"';});
|
||||
qp = qp ? JSON.parse('{' + arr.join() + '}',
|
||||
function (key, value) {
|
||||
return key === "" ? value : decodeURIComponent(value)
|
||||
return key === "" ? value : decodeURIComponent(value);
|
||||
}
|
||||
) : {}
|
||||
) : {};
|
||||
|
||||
isValid = qp.state === sentState
|
||||
isValid = qp.state === sentState;
|
||||
|
||||
if ((
|
||||
oauth2.auth.schema.get("flow") === "accessCode"||
|
||||
oauth2.auth.schema.get("flow") === "authorizationCode"
|
||||
oauth2.auth.schema.get("flow") === "accessCode" ||
|
||||
oauth2.auth.schema.get("flow") === "authorizationCode" ||
|
||||
oauth2.auth.schema.get("flow") === "authorization_code"
|
||||
) && !oauth2.auth.code) {
|
||||
if (!isValid) {
|
||||
oauth2.errCb({
|
||||
|
@ -48,7 +47,7 @@
|
|||
oauth2.auth.code = qp.code;
|
||||
oauth2.callback({auth: oauth2.auth, redirectUrl: redirectUrl});
|
||||
} else {
|
||||
let oauthErrorMsg
|
||||
let oauthErrorMsg;
|
||||
if (qp.error) {
|
||||
oauthErrorMsg = "["+qp.error+"]: " +
|
||||
(qp.error_description ? qp.error_description+ ". " : "no accessCode received from the server. ") +
|
||||
|
@ -72,3 +71,5 @@
|
|||
run();
|
||||
});
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
|
|
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
|
@ -1,3 +1,9 @@
|
|||
// swagger-ui-init.js
|
||||
// https://github.com/axnsan12/drf-yasg
|
||||
// Copyright 2017 - 2021, Cristian V. <cristi@cvjd.me>
|
||||
// This file is licensed under the BSD 3-Clause License.
|
||||
// License text available at https://opensource.org/licenses/BSD-3-Clause
|
||||
|
||||
"use strict";
|
||||
var currentPath = window.location.protocol + "//" + window.location.host + window.location.pathname;
|
||||
var defaultSpecUrl = currentPath + '?format=openapi';
|
||||
|
|
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
|
@ -7,15 +7,15 @@ h1 {
|
|||
}
|
||||
|
||||
pre.highlight code * {
|
||||
white-space: nowrap; // this sets all children inside to nowrap
|
||||
white-space: nowrap; /* this sets all children inside to nowrap */
|
||||
}
|
||||
|
||||
pre.highlight {
|
||||
overflow-x: auto; // this sets the scrolling in x
|
||||
overflow-x: auto; /* this sets the scrolling in x */
|
||||
}
|
||||
|
||||
pre.highlight code {
|
||||
white-space: pre; // forces <code> to respect <pre> formatting
|
||||
white-space: pre; /* forces <code> to respect <pre> formatting */
|
||||
}
|
||||
|
||||
.main-container {
|
||||
|
|
|
@ -131,13 +131,7 @@ $(function () {
|
|||
if (value !== undefined) {
|
||||
params[paramKey] = value
|
||||
}
|
||||
} else if (dataType === 'array' && paramValue) {
|
||||
try {
|
||||
params[paramKey] = JSON.parse(paramValue)
|
||||
} catch (err) {
|
||||
// Ignore malformed JSON
|
||||
}
|
||||
} else if (dataType === 'object' && paramValue) {
|
||||
} else if ((dataType === 'array' && paramValue) || (dataType === 'object' && paramValue)) {
|
||||
try {
|
||||
params[paramKey] = JSON.parse(paramValue)
|
||||
} catch (err) {
|
||||
|
|
|
@ -1,6 +1,6 @@
|
|||
{
|
||||
"name": "django-vue-admin",
|
||||
"version": "2.1.1",
|
||||
"version": "2.1.2",
|
||||
"scripts": {
|
||||
"serve": "vue-cli-service serve --open",
|
||||
"start": "npm run serve",
|
||||
|
@ -86,6 +86,6 @@
|
|||
},
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/d2-projects/d2-admin.git"
|
||||
"url": "https://github.com/liqianglog/django-vue-admin"
|
||||
}
|
||||
}
|
||||
|
|
|
@ -29,8 +29,15 @@ function webSocketOnError (e) {
|
|||
*/
|
||||
function webSocketOnMessage (e) {
|
||||
const data = JSON.parse(e.data)
|
||||
const { unread } = data
|
||||
store.dispatch('d2admin/messagecenter/setUnread', unread || 0)
|
||||
const { refresh_unread, systemConfig } = data
|
||||
if (refresh_unread) {
|
||||
// 更新消息通知条数
|
||||
store.dispatch('d2admin/messagecenter/setUnread')
|
||||
}
|
||||
if (systemConfig) {
|
||||
// 更新系统配置
|
||||
this.$store.dispatch('d2admin/settings/load')
|
||||
}
|
||||
if (data.contentType === 'SYSTEM') {
|
||||
ElementUI.Notification({
|
||||
title: '系统消息',
|
||||
|
|
|
@ -1,3 +1,5 @@
|
|||
import { request } from '@/api/service'
|
||||
import { urlPrefix } from '@/views/system/messageCenter/api'
|
||||
|
||||
export default {
|
||||
namespaced: true,
|
||||
|
@ -18,8 +20,22 @@ export default {
|
|||
* @param {String} param type {String} 类型
|
||||
* @param {Object} payload meta {Object} 附带的信息
|
||||
*/
|
||||
async setUnread ({ state, commit }, number) {
|
||||
commit('set', number)
|
||||
async setUnread ({
|
||||
state,
|
||||
commit
|
||||
}, number) {
|
||||
if (number) {
|
||||
commit('set', number)
|
||||
} else {
|
||||
request({
|
||||
url: '/api/system/message_center/get_unread_msg/',
|
||||
method: 'get',
|
||||
params: {}
|
||||
}).then(res => {
|
||||
const { data } = res
|
||||
commit('set', data.count)
|
||||
})
|
||||
}
|
||||
}
|
||||
},
|
||||
mutations: {
|
||||
|
|
|
@ -84,6 +84,7 @@
|
|||
:key="index"
|
||||
v-else-if="item.form_item_type_label === 'switch'"
|
||||
v-model="form[item.key]"
|
||||
:inactive-value="false"
|
||||
active-color="#13ce66"
|
||||
inactive-color="#ff4949">
|
||||
</el-switch>
|
||||
|
@ -310,7 +311,7 @@ export default {
|
|||
if ([5, 12, 14].indexOf(item.form_item_type) !== -1) {
|
||||
form[key] = []
|
||||
} else {
|
||||
form[key] = undefined
|
||||
form[key] = item.value
|
||||
}
|
||||
}
|
||||
if (item.form_item_type_label === 'array') {
|
||||
|
@ -321,7 +322,7 @@ export default {
|
|||
})
|
||||
}
|
||||
}
|
||||
this.form = JSON.parse(JSON.stringify(form))
|
||||
this.form = Object.assign({}, form)
|
||||
})
|
||||
},
|
||||
// 提交数据
|
||||
|
|
|
@ -56,14 +56,7 @@ export default {
|
|||
return GetObj(query)
|
||||
},
|
||||
addRequest (row) {
|
||||
return AddObj(row).then(res => {
|
||||
const message = {
|
||||
message_id: res.data.id,
|
||||
contentType: 'INFO',
|
||||
content: '您有新的消息,请到消息中心查看~'
|
||||
}
|
||||
this.$websocket.webSocketSend(message)
|
||||
})
|
||||
return AddObj(row)
|
||||
},
|
||||
updateRequest (row) {
|
||||
return UpdateObj(row)
|
||||
|
|
Loading…
Reference in New Issue