我正在开发一个 REST API,它从一些无法修补或其他任何东西的真正脑死亡的软件中获取 POST 请求。 POST 用于更新数据库中已存在的模型对象。
具体来说,我正在发布具有相关字段(SlugRelatedField,因为 POSTer 知道“name”属性但不知道“pk”)的对象的数据。但是,如果 POSTer 发送的数据中“名称”在 SlugRelatedField 上没有返回任何内容(例如相关对象不存在),我需要返回 404。我已经使用调试器完成了这个任务,但似乎 DRF 使用了一些 Django 信号魔法来实现 DRF 的方式™,即返回 400 BAD REQUEST。我不知道如何修改这个 -only当它是上述条件并且不是真正的 400 值得 POST 时 - 变成 404。
顺便一提,pre_save()
在我看来,在执行失败的测试期间不会执行。
这是序列化器:
class CharacterizationSerializer(serializers.ModelSerializer):
"""
Work-in-progress for django-rest-framework use. This handles (de)serialization
of data into a Characterization object and vice versa.
See: http://www.django-rest-framework.org/tutorial/1-serialization
"""
creator = serializers.Field(source='owner.user.username')
sample = serializers.SlugRelatedField(slug_field='name',
required=True,
many=False,
read_only=False)
class Meta:
model = Characterization
# leaving 'request' out because it's been decided to deprecate it. (...maybe?)
fields = ('sample', 'date', 'creator', 'comments', 'star_volume', 'solvent_volume',
'solution_center', 'solution_var', 'solution_minimum', 'solution_min_stddev',
'solution_test_len',)
这是视图pre_save
没有在给定的测试中运行(但在其他一些测试中运行):
class CharacterizationList(generics.ListCreateAPIView):
queryset = Characterization.objects.all()
serializer_class = CharacterizationSerializer
permission_classes = (AnonPostAllowed,) # @todo XXX hack for braindead POSTer
def pre_save(self, obj):
# user isn't sent as part of the serialized representation,
# but is instead a property of the incoming request.
if not self.request.user.is_authenticated():
obj.owner = get_dummy_proxyuser() # this is done for CharacterizationList so unauthed users can POST. @todo XXX hack
else:
obj.owner = ProxyUser.objects.get(pk=self.request.user.pk)
# here, we're fed a string sample name, but we need to look up
# the actual sample model.
# @TODO: Are we failing properly if it doesn't exist? Should
# throw 404, not 400 or 5xx.
# except, this code doesn't seem to be run directly when debugging.
# a 400 is thrown; DRF must be bombing out before pre_save?
obj.sample = Sample.objects.get(name=self.request.DATA['sample'])
为了更好地衡量,这是失败的测试:
def test_bad_post_single_missing_sample(self):
url = reverse(self._POST_ONE_VIEW_NAME)
my_sample_postdict = self.dummy_plqy_postdict.copy()
my_sample_postdict["sample"] = "I_DONT_EXIST_LUL"
response = self.rest_client.post(url, my_sample_postdict)
self.assertTrue(response.status_code == 404,
"Expected 404 status code, got %d (%s). Content: %s" % (response.status_code, response.reason_phrase, response.content))
如果我在self.rest_client.post()
调用时,此时响应中已包含 400。