Django Rest框架中的输入消毒

2024-06-06 20:23:02 发布

您现在位置:Python中文网/ 问答频道 /正文

如果我发一些像

{
    "description": "Hello World <script>alert('hacked');</script>"
}

对于我的django rest框架视图,我想去掉脚本标记。在

  1. 有没有一种方便的方法可以做到这一点,即不需要覆盖所有内容并添加strip_tags?在
  2. 还要做什么来清理输入?在
  3. 我是真的读过头了drf文档中的那一部分,还是没有涵盖?在

Tags: django方法标记脚本框架视图rest内容
2条回答

您可以重写视图的perform_create方法,并使用一些正则表达式执行类似的操作

import re
class MyView(generics.CreateAPIView):
      ......
      ......
      def perform_create(self, serializer):
            replacement=re.sub('</*script>','',serializer.validated_data.get('description'))
            serializer.save(description=replacement)

这是假设您正在使用CreateAPIView或它的一个mixin。 或者您可以创建一个custom序列化程序字段

^{pr2}$

以及

class MySerializer(serializer.ModelSerializer):
      description=MyCustomField()
      class Meta:
           model= MyModel

忽略这里的答案,它们太可怕了。在

使用bleach。你不会得到所有的边缘案件。这就是使用库的情况。根据定义,您的客户机控制着客户端。在

相关问题 更多 >