皮林特提升-失踪-从

在这段代码(来自 https://www.django-rest-framework.org/tutorial/3-class-based-views/)上有一条 pylint 消息(w0707) :

class SnippetDetail(APIView):
"""
Retrieve, update or delete a snippet instance.
"""
def get_object(self, pk):
try:
return Snippet.objects.get(pk=pk)
except Snippet.DoesNotExist:
raise Http404

信息是:

Consider explicitly re-raising using the 'from' keyword

我不太明白如何采取行动来纠正这个问题。

55304 次浏览

The link in the comment on your question above outlines the issue and provides a solution, but for clarity of those landing straight on this page like myself, without having to go off to another thread, read and gain context, here is the answer to your specific problem:

TL;DR;

This is simply solved by aliasing the Exception you are 'excepting' and refering to it in your second raise.

Taking your code snippet above, see the bottom two lines, I've added 'under-carets' to denote what I've added.

class SnippetDetail(APIView):
"""
Retrieve, update or delete a snippet instance.
"""
def get_object(self, pk):
try:
return Snippet.objects.get(pk=pk)
except Snippet.DoesNotExist as snip_no_exist:
#                                   ^^^^^^^^^^^^^^^^
raise Http404 from snip_no_exist
#                         ^^^^^^^^^^^^^^^^^^

Note: The alias can be any well formed string.