python - Swagger 不使用 Django BaseSerializer 对象

标签 python django rest django-rest-framework swagger

我正在使用 django-rest-swagger 来记录和测试 API,到目前为止它运行良好,但出现了以下错误:

/docs/api-docs/app 的属性错误 “PeriodSerializer”对象没有属性“get_fields”

'PeriodSerializer'继承自serializers.BaseSerializer:

class PeriodSerializer(serializers.BaseSerializer):

    def to_representation(self, instance):
        return {
            'lower': instance.lower,
            'upper': instance.upper
        }

    def to_internal_value(self, data):
        data = json.loads(data)

        date_lower = self.date_from_str(data["lower"])
        date_upper = self.date_from_str(data["upper"])

        # some code omitted for brevity

        return DateTimeTZRange(lower=date_lower, upper=date_upper)


    @staticmethod
    def date_from_str(datestr):
        # code omitted for brevity

代码本身工作正常,只是 django-rest-swagger 似乎有问题。我正在使用:

  • python 3.4.0
  • Django 1.8.2
  • DRF 3.1.3
  • django-rest-swagger 0.3.2

如有任何帮助,我们将不胜感激。

最佳答案

Django Rest Framework 的 BaseSerializer 没有 get_fields 函数。您可以在 source 中看到这一点.

简短回答:使用Serializer,而不是BaseSerializer。您的代码将以同样的方式工作,您不必为此担心。如果出于某种原因你需要同时使用 BaseSerializerdjango-rest-swagger,你必须自己实现 get_fields

如果您在更高级别的序列化程序(如 Serializer)中查看 get_fields 的实现,您会看到 get_fields 的定义如下:

def get_fields(self):
    """
    Returns a dictionary of {field_name: field_instance}.
    """
    # Every new serializer is created with a clone of the field instances.
    # This allows users to dynamically modify the fields on a serializer
    # instance without affecting every other serializer class.
    return copy.deepcopy(self._declared_fields)

使用 BaseSerializer,您也无法访问 self._declared_fields。您可以在上面的链接源中看到它是如何工作的,但它的要点是它返回 Field 类型的属性字典。

Any instances of Field included as attributes on either the class or on any of its superclasses will be include in the _declared_fields dictionary.

我希望这有助于回答您的问题!

关于python - Swagger 不使用 Django BaseSerializer 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30880375/

相关文章:

python - Python 请求在这里做错了什么,还是我的 POST 请求缺少某些东西?

jquery - 将 django HttpResponse 作为文件返回,而不是 $.ajax() post 中的普通响应正文

python - 如何使用 Celery 延迟任务?

jquery - 数据表未在 django-datatable-view 中填充数据

rest - 使用 MarkLogic REST API 将文件系统设置为模块数据库

python - 如何使用 matplotlib 缩放轴标签?

python - 打开文件 tokenizer.dat 时出现 FREELING 错误

python - 正则表达式匹配一些子字符串,同时忽略看似相同的子字符串?

rest - "WebSocket"和 "REST API"之间有何不同

带有 rxjs 的 Angular HttpClient