python - DRF 序列化器通过 REST API 与第三方应用程序进行操作

标签 python django django-rest-framework serialization

一图胜千言,就这样吧。因此,我尝试通过 REST CRUD API 操作第三方应用程序。

现在,我想使用 Django Rest API 路由器以及它将给我的应用程序带来的所有好处。要使用路由器,我必须使用 ViewSets。我只使用简单的 python 类而不是模型,因为我不必存储任何数据(也许根本不需要?)。

问题是,如何创建序列化器来转换来自第三方服务的复杂 json 数据,转换它并将其发送到 Fronted。但是,当我更改前端应用程序上的数据以传播更改并更新第三方应用程序时。

enter image description here

到目前为止我有这个:

url.py

router.register(r'applications', ApplicationViewSet, base_name='application')

模型.py

class Application(object):

    def __init__(self, name, color):
        self.name = name
        self.color = color

序列化器.py

class ApplicationSerializer(serializers.Serializer):
    name = serializers.CharField(max_length=256)
    #color = ??? How to transform and serialize dict value to field ?

View .py

class ApplicationViewSet(ViewSet):

    def create(self, request):
        # I guess that this logic should be handled by serializes as well?. 
        name = request.data.get('name')
        color = request.data.get('color')
        result = third_party_service.create_application(request, name)
        app = Application(**result)
        if color:
            app.color = color
            third_party_service.update_application(request, app)
        return Response(app)

    def list(self, request):
        queryset = third_party_service.get_applications(request)
        serializer = ApplicationSerializer(queryset, many=True)
        return Response(serializer.data)

    def retrieve(self, request, pk=None):
        app = third_party_service.get_application(request, pk)
        serializer = ApplicationSerializer(instance=app)
        return Response(serializer.data)

来自第三方应用程序的 JSON:

{
  "name": "Application",
  "attributeCollection": {
    "attributeArray": [
      {
        "name": "color",
        "value": [
          "red",
          "green"
        ]
      },
      {
        "name": "text",
        "value": [
          "bold"
        ]
      }
    ]
  }
}

发送到前端的 JSON:

{
  "name": "Application",
  "color": ["red", "green"]
}

我并不是 DRF 的高级用户,所以也许我使用它的方式是错误的。任何有关如何实现这一目标的建议都会非常有帮助!

最佳答案

您可以使用serializer-method-field从字典中获取值。

下面是根据您提供的示例获取颜色的代码。

class ApplicationSerializer(serializers.Serializer):
    name = serializers.CharField(max_length=256)
    color = = serializers.SerializerMethodField()

    def get_color(self, obj):
        attribute_array = obj['attributeCollection']['attributeArray']
        color_attr = [attr for attr in attribute_array if attr['name'] == 'color']
        if color_attr:
            return color_attr[0]['value']

        return []

您还可以使用generator-expression从数组中查找 color_attribute。

color_attr = next((attr for attr in attribute_array if attr["name"] == "color"), None)
return color_attr['value] if color_attr else []

关于python - DRF 序列化器通过 REST API 与第三方应用程序进行操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59490952/

相关文章:

python - 如何不在 Python、Django 中两次生成相同的动态图像?

python - 按名称将函数的文档字符串复制到另一个函数

Django ManyToMany 来自 CreateView 中的字符串

python - 部署了 rest-framework 的 django 时出错

django - 我真的需要 Django Rest Framework 来使用 Django 开发 Restful api 吗?

django - 缺少 1 个必需的位置参数 : 'request' django restframework

python - 没有 `await` 任何东西的协程与函数有什么不同吗?

Python程序只获取列表中没有重复项的唯一项

python - django form.模板中的错误

python - Django:Python 全局变量重叠,即使是单独运行