如何通过Django Rest框架公开Django-Constance设置?

vu8f3i0k  于 2023-02-17  发布在  Go
关注(0)|答案(3)|浏览(126)

我正在构建一个项目,其中我需要有一些自定义设置,可由某些用户编辑,这些用户没有访问django管理面板的权限,他们通过一个Angular 前端访问应用程序。
我安装django-constance是为了让这些自定义设置可以编辑,因为它是我在Django packages site上找到的最推荐的包。我现在的问题是我不知道如何在我的API rest上提供这些设置。
我从一些自定义视图开始:

class ConstanceSettingSerializer(serializers.Serializer):

name = serializers.CharField()
value = serializers.Field()
defult_value = serializers.Field()
modified = serializers.BooleanField(read_only=True)

from constance import settings as constance_settings

class ConstanceView(APIView):

def get(self, request):

    settings = constance_settings.CONFIG.items()

    return Response(settings, status=status.HTTP_200_OK)

但是现在我不知道如何将这些设置正确地传递给我的序列化器。我尝试了以下方法,但没有成功:

settings_serializer = ConstanceSettingSerializer(settings)
 return Response(settings_serializer.data, status=status.HTTP_200_OK)

我只得到错误。
你知道怎么做吗?
谢谢!

bksxznpy

bksxznpy1#

给你演示一下

from .utils import get_settings
from constance import config
from rest_framework.viewsets import ViewSet

class SettingViewSet(ViewSet):
    permission_classes = (IsAuthenticated,)

    def setting(self, request, allow_settings):
        if request.method == 'GET':
            # list all setting items
            return Response(data=get_settings(allow_settings))
        else:
            # change all allow setting items in allow_settings
            for key in request.data:
                if key in allow_settings and key in getattr(settings, 'CONSTANCE_CONFIG', {}):
                    value = request.data[key]
                    setattr(config, key, '' if value is None else value)
            return Response(data=get_settings(allow_settings))

    def create(self, request):
        """
        <p>update with POST:<code>{'Key': new_value}</code>
        """
        allow_settings = [key for key, options in getattr(settings, 'CONSTANCE_CONFIG', {}).items()]
        return self.setting(request, allow_settings)

    def list(self, request):
        """
        get all setting item
        """
        allow_settings = [key for key, options in getattr(settings, 'CONSTANCE_CONFIG', {}).items()]
        return self.setting(request, allow_settings)

在www.example.com中utils.py:

def get_settings(allow_settings):
    setting_list = []
    for key, options in getattr(settings, 'CONSTANCE_CONFIG', {}).items():
        if key in allow_settings:
            default, help_text = options[0], options[1]
            data = {'key': key,
                    'default': default,
                    'help_text': help_text,
                    'value': getattr(config, key)}
            setting_list.append(data)
    return setting_list

在www.example.com中urls.py:

router.register(r'setting', SettingViewSet, base_name='setting')

询问get http://x.x.x.x/setting/可以得到:

[
    {
        "key": "staff_prefix",
        "default": "",
        "help_text": "工号固定代码",
        "value": ""
    },
    {
        "key": "staff_suffix",
        "default": 3,
        "help_text": "工号尾缀",
        "value": "3"
    }
]

使用数据{'staff_prefix': 'demo'}发布http://x.x.x.x/setting/,您可以更新staff_prefix中的值。

o7jaxewo

o7jaxewo2#

你的序列化器需要知道返回什么。所以对于每个字段,你可以做如下的事情:

class ConstanceSettingSerializer(serializers.Serializer):

    setting_name = serializers.SerializerMethodField()

    def get_setting_name(self):
        settings = constance_settings.CONFIG.items()
        # Retrieve your setting's value here and return
        return setting_value

如果你想通过PUT/POST/PATCH来改变设置,你需要在你的序列化器中重写create/update,并实现自己保存值的逻辑。
另一种方法是检查设置的存储是如何实现的。我没有使用常量设置,所以我不能说。但是如果它使用DB来存储设置,你可以为它们使用的模型实现模型序列化器。

yks3o0rb

yks3o0rb3#

如果您使用数据库后端,也可以使用序列化程序执行相同的操作:
serializer.py:

from constance.backends.database.models import Constance
from constance import config
from django.conf import settings
from rest_framework import serializers

class ConfigSerializer(serializers.ModelSerializer):
    default = serializers.SerializerMethodField()
    help_text = serializers.SerializerMethodField()
    value = serializers.SerializerMethodField()

    class Meta:
        model = Constance
        fields = ('key', 'default', 'help_text', 'value')

    def get_default(self, obj):
        default, _ = settings.CONSTANCE_CONFIG.get(obj.key)
        return default

    def get_help_text(self, obj):
        _, help_text = settings.CONSTANCE_CONFIG.get(obj.key)
        return help_text

    def get_value(self, obj):
        return getattr(config, obj.key, None)

views.py:

from rest_framework.viewsets import ReadOnlyModelViewSet
from rest_framework.permissions import IsAuthenticated
from constance.backends.database.models import Constance

from myproject.apps.common.api.v1.serializers import ConfigSerializer

class ConfigAPIView(ReadOnlyModelViewSet):
    serializer_class = ConfigSerializer
    permission_classes = [IsAuthenticated]
    queryset = Constance

urls.py:

from django.urls import path

from myproject.apps.common.api.v1.views import ConfigAPIView

urlpatterns = [
    path(
        "config/",
        ConfigAPIView.as_view({"get": "list"}),
        name="config-list",
    ),
]

相关问题