Files
boss_dp/server/api/settings.py
2026-02-26 01:27:35 +08:00

43 lines
1.5 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# -*- coding: utf-8 -*-
"""
系统配置 API需要登录
- GET /api/settings -> 查询所有配置
- POST /api/settings -> 批量更新配置(传入 key-value 对象)
- GET /api/settings/{key} -> 查询单个配置
"""
from rest_framework import status
from rest_framework.decorators import api_view
from server.core.response import api_success, api_error
from server.models import SystemConfig
from server.serializers import SystemConfigSerializer
@api_view(["GET", "POST"])
def settings_list(request):
if request.method == "GET":
qs = SystemConfig.objects.all().order_by("key")
return api_success(SystemConfigSerializer(qs, many=True).data)
# POST: 批量更新,请求体格式 {"key1": "value1", "key2": "value2", ...}
if not isinstance(request.data, dict):
return api_error(status.HTTP_400_BAD_REQUEST, "请传入 key-value 对象")
results = []
for key, value in request.data.items():
obj, created = SystemConfig.objects.update_or_create(
key=key,
defaults={"value": str(value)},
)
results.append(SystemConfigSerializer(obj).data)
return api_success(results)
@api_view(["GET"])
def settings_detail(request, key):
try:
obj = SystemConfig.objects.get(key=key)
except SystemConfig.DoesNotExist:
return api_error(status.HTTP_404_NOT_FOUND, f"配置项 '{key}' 不存在")
return api_success(SystemConfigSerializer(obj).data)