Django Rest Framework:多次调用“get_serializer_class”,请求方法的值错误

2024-01-09

Using a ModelViewSet,这正常吗?get_serializer_class在访问可浏览的 API 时,是否会针对单个请求多次调用?并且该值self.method.request每次通话之间的变化?

我已经创建了一个小测试项目来展示行为 https://github.com/decibyte/drf-method-example. In project/example/views.py https://github.com/decibyte/drf-method-example/blob/master/project/example/views.py有一个ThingViewSet与定制get_serializer_class,打印当前的请求方法。

如果您启动服务器并导航到http://127.0.0.1:8000/things/1/ http://127.0.0.1:8000/things/1/,输出将类似于:

./manage.py runserver
Performing system checks...

System check identified no issues (0 silenced).
May 19, 2015 - 08:51:34
Django version 1.8.1, using settings 'project.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.
Method is: GET
Method is: PUT
Method is: PATCH
Method is: PUT
[19/May/2015 08:51:40]"GET /things/1/ HTTP/1.1" 200 11679

清楚地,get_serializer_class被调用 4 次,具有不同的值(GET, PUT, PATCH, PUT),虽然只有一个GET请求被执行。

奇怪的是,如果您以 JSON 形式请求,则不会发生这种情况:

./manage.py runserver
Performing system checks...

System check identified no issues (0 silenced).
May 19, 2015 - 10:25:57
Django version 1.8.1, using settings 'project.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.
Method is: GET
[19/May/2015 10:26:22]"GET /things/?format=json HTTP/1.1" 200 49

问题是最后一次调用的请求方法get_serializer_class可浏览的 API 是PUT(这显然是错误的GET请求),然后我们最终为请求使用了错误的序列化器,因为不同的请求方法返回不同的序列化器,这是我们在现实生活项目中所做的(例如,用于读取和写入操作)。

任何人都可以阐明正在发生的事情吗?为什么是get_serializer_class多次调用可浏览 API,但方法值错误?


你所看到的原因get_serializer_class被多次调用是因为您正在使用可浏览的 API。如果您在不使用可浏览的 API 的情况下进行测试,例如通过强制 JSON 渲染器(?format=json or an Acceptheader),你只会看到它被称为一个。

可浏览的 API 生成基于序列化器显示的表单,因此get_serializer_class对每个表单和可能的请求类型调用一次。

因此,当第一个请求时,GET对于用于处理响应数据(在本例中为特定对象)的原始序列化程序有意义,接下来的三个是可浏览 API 的自定义。这些调用按以下顺序发生:get_serializer你所看到的

  1. 原始 PUT 表单(用于输入任何请求正文)。 https://github.com/tomchristie/django-rest-framework/blob/e33fed70d65303627ea4ee8292dd28a6a1f9f617/rest_framework/renderers.py#L638
  2. 原始 PATCH 形式。 https://github.com/tomchristie/django-rest-framework/blob/e33fed70d65303627ea4ee8292dd28a6a1f9f617/rest_framework/renderers.py#L640
  3. 完整的 PUT 表单(默认包含实例数据)。 https://github.com/tomchristie/django-rest-framework/blob/e33fed70d65303627ea4ee8292dd28a6a1f9f617/rest_framework/renderers.py#L633

The method正在改变the override_method有功能 https://github.com/tomchristie/django-rest-framework/blob/e33fed70d65303627ea4ee8292dd28a6a1f9f617/rest_framework/request.py#L33-L60它模拟被重写的请求方法,这通常发生在POST请求需要不同的方法。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Django Rest Framework:多次调用“get_serializer_class”,请求方法的值错误 的相关文章

随机推荐