style: ruff format 全仓库

行宽 180 下把历史遗留的折行表达式合并,无语义改动。

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
2026-08-05 04:45:26 -06:00
parent db104ac091
commit 3a9ab83ba5
56 changed files with 455 additions and 769 deletions

View File

@@ -1,6 +1,7 @@
"""
WebSocket consumers for configuration updates
"""
import json
import logging
@@ -18,31 +19,25 @@ class ConfigConsumer(AsyncWebsocketConsumer):
async def connect(self):
"""处理 WebSocket 连接"""
self.user = self.scope["user"]
# 只允许认证用户连接
if not self.user.is_authenticated:
await self.close()
return
# 使用全局配置组名,所有用户都能接收配置更新
self.group_name = "config_updates"
# 加入配置更新组
await self.channel_layer.group_add(
self.group_name,
self.channel_name
)
await self.channel_layer.group_add(self.group_name, self.channel_name)
await self.accept()
logger.info(f"Config WebSocket connected: user_id={self.user.id}, channel={self.channel_name}")
async def disconnect(self, close_code):
"""处理 WebSocket 断开连接"""
if hasattr(self, 'group_name'):
await self.channel_layer.group_discard(
self.group_name,
self.channel_name
)
if hasattr(self, "group_name"):
await self.channel_layer.group_discard(self.group_name, self.channel_name)
logger.info(f"Config WebSocket disconnected: user_id={self.user.id}, close_code={close_code}")
async def receive(self, text_data):
@@ -53,13 +48,10 @@ class ConfigConsumer(AsyncWebsocketConsumer):
try:
data = json.loads(text_data)
message_type = data.get("type")
if message_type == "ping":
# 响应心跳包
await self.send(text_data=json.dumps({
"type": "pong",
"timestamp": data.get("timestamp")
}))
await self.send(text_data=json.dumps({"type": "pong", "timestamp": data.get("timestamp")}))
elif message_type == "config_update":
# 处理配置更新请求
key = data.get("key")
@@ -69,17 +61,7 @@ class ConfigConsumer(AsyncWebsocketConsumer):
# 这里可以添加权限检查,只有管理员才能发送配置更新
if self.user.is_superuser:
# 广播配置更新给所有连接的客户端
await self.channel_layer.group_send(
self.group_name,
{
"type": "config_update",
"data": {
"type": "config_update",
"key": key,
"value": value
}
}
)
await self.channel_layer.group_send(self.group_name, {"type": "config_update", "data": {"type": "config_update", "key": key, "value": value}})
except json.JSONDecodeError:
logger.error(f"Invalid JSON received from user {self.user.id}")
except Exception as e:

View File

@@ -44,7 +44,7 @@ class JudgeServerHeartbeatSerializer(serializers.Serializer):
cpu_core = serializers.IntegerField(min_value=1)
memory = serializers.FloatField(min_value=0, max_value=100)
cpu = serializers.FloatField(min_value=0, max_value=100)
action = serializers.ChoiceField(choices=("heartbeat", ))
action = serializers.ChoiceField(choices=("heartbeat",))
service_url = serializers.CharField(max_length=256)

View File

@@ -153,9 +153,7 @@ class JudgeServerAPI(APIView):
@super_admin_required
def put(self, request):
is_disabled = request.data.get("is_disabled", False)
JudgeServer.objects.filter(id=request.data["id"]).update(
is_disabled=is_disabled
)
JudgeServer.objects.filter(id=request.data["id"]).update(is_disabled=is_disabled)
if not is_disabled:
process_pending_task()
return self.success()
@@ -166,10 +164,7 @@ class JudgeServerHeartbeatAPI(CSRFExemptAPIView):
def post(self, request):
data = request.data
client_token = request.META.get("HTTP_X_JUDGE_SERVER_TOKEN")
if (
hashlib.sha256(SysOptions.judge_server_token.encode("utf-8")).hexdigest()
!= client_token
):
if hashlib.sha256(SysOptions.judge_server_token.encode("utf-8")).hexdigest() != client_token:
return self.error("Invalid token")
try:
@@ -263,8 +258,7 @@ class ReleaseNotesAPI(APIView):
def get(self, request):
try:
resp = requests.get(
"https://raw.githubusercontent.com/QingdaoU/OnlineJudge/master/docs/data.json?_="
+ str(time.time()),
"https://raw.githubusercontent.com/QingdaoU/OnlineJudge/master/docs/data.json?_=" + str(time.time()),
timeout=3,
)
releases = resp.json()
@@ -289,9 +283,7 @@ class DashboardInfoAPI(AsyncAPIView):
User.objects.acount(),
Submission.objects.filter(create_time__gte=today_start).acount(),
Contest.objects.exclude(end_time__lt=timezone.now()).acount(),
JudgeServer.objects.filter(
last_heartbeat__gte=timezone.now() - timedelta(seconds=6)
).acount(),
JudgeServer.objects.filter(last_heartbeat__gte=timezone.now() - timedelta(seconds=6)).acount(),
)
return self.success(
{
@@ -312,20 +304,14 @@ class RandomUsernameAPI(AsyncAPIView):
classroom = request.GET.get("classroom", "")
if not classroom:
return self.error("需要班级号")
usernames = [
u async for u in User.objects.filter(username__istartswith=classroom)
.values_list("username", flat=True)
.order_by("?")[:10]
]
usernames = [u async for u in User.objects.filter(username__istartswith=classroom).values_list("username", flat=True).order_by("?")[:10]]
return self.success(usernames)
class HitokotoAPI(AsyncAPIView):
async def get(self, request):
try:
categories = JsonDataLoader.load_data(
settings.HITOKOTO_DIR, "categories.json"
)
categories = JsonDataLoader.load_data(settings.HITOKOTO_DIR, "categories.json")
path = random.choice(categories).get("path")
sentences = JsonDataLoader.load_data(settings.HITOKOTO_DIR, path)
sentence = random.choice(sentences)
@@ -341,7 +327,6 @@ class ClassUsernamesAPI(AsyncAPIView):
return self.error("需要班级号")
prefix = f"ks{classroom}"
names = [
user.username[len(prefix):] if user.username.startswith(prefix) else user.username
async for user in User.objects.filter(class_name=classroom).order_by("-create_time")
user.username[len(prefix) :] if user.username.startswith(prefix) else user.username async for user in User.objects.filter(class_name=classroom).order_by("-create_time")
]
return self.success(names)