2

我遇到了这个奇怪的错误,我的代码昨天运行良好(通过自动化测试)但今天就坏了。基本上,感觉好像@api_view 装饰器坏了,无法申请一个方法。情况如下:

我有一个名为“advance_orders”的方法,它的包装如下:

@api_view(http_method_names=['POST'], hack=True)
@permission_classes((IsAuthenticated,))
@check_wallet_token
@disallow_disabled_users
def advance_orders(request):
    # code that is irrelevant for this issue

注意: hack=True 是我在第一次发现错误后为调试目的而添加的一个小功能。

这些方法在这里@check_wallet_token@disallow_disabled_users无关紧要,我 99.99% 确定它们不是错误的来源(因为它们昨天工作罚款和在/在其他类似包装的方法中)

到函数的 url 映射是: re_path(r'^vendor/orders/advance/$', vendor.advance_orders, name='advance_order'),

现在,在某个测试中,我有:

client = RequestsClient()
# absolute_url == http://testserver/wallet/vendor/orders/advance/
# there are some helper methods which generate it...
# the headers are irrelevant honestly
r = client.post(absolute_url, headers=self.headers, data={"order_id": "asdf"})
print(r.text)
self.assertEqual(r.status_code, 400)
self.assertEqual(json.loads(r.text), {"display_message": "Missing order_id (int)."})

测试失败并在打印我发现的响应文本时: {"detail":"Method \"POST\" not allowed."}

这没有任何意义!除非我做错了什么,我很确定我不是。

++++++++++++++++++++++++++++++++++++++++++++++++++++++ +++++++++++++++++++++++++

现在是我收集更多证据的时候了。我进入安装在我的虚拟环境中的 DRF 的源代码并修改两种方法以打印出额外的调试信息。

在views.py中我改变views.APIView.dispatch()如下:

def dispatch(self, request, *args, **kwargs):
        """
        `.dispatch()` is pretty much the same as Django's regular dispatch,
        but with extra hooks for startup, finalize, and exception handling.
        """
        self.args = args
        self.kwargs = kwargs
        request = self.initialize_request(request, *args, **kwargs)
        self.request = request
        self.headers = self.default_response_headers  # deprecate?

        hack = False
        if request.META['PATH_INFO'] == '/wallet/vendor/orders/advance/':
            print("[HACK - views.py] Method identified as advance_order")
            hack = True

        try:
            self.initial(request, *args, **kwargs)

            # Get the appropriate handler method
            if request.method.lower() in self.http_method_names:
                handler = getattr(self, request.method.lower(),
                                  self.http_method_not_allowed)
            else:
                print("[HACK - views.py] list of http_method_names associated with the function: {}".format(self.http_method_names))
                handler = self.http_method_not_allowed

            response = handler(request, *args, **kwargs)

        except Exception as exc:
            response = self.handle_exception(exc)
# and so on as usual...

我修改的另一种方法是decorators.api_view()

def api_view(http_method_names=None, exclude_from_schema=False, hack=False):
    """
    Decorator that converts a function-based view into an APIView subclass.
    Takes a list of allowed methods for the view as an argument.
    """
    http_method_names = ['GET'] if (http_method_names is None) else http_method_names

    if hack:
        print("[HACK - decorators.py] Provided http_method_names: {}".format(http_method_names))
# and so on as usual...

./manage.py test Wallet.tests.test_api_vendors.API_VendorTestCase --failfast 现在我使用并打印我们的结果来运行我的测试:

[HACK - decorators.py] Provided http_method_names: ['POST']
System check identified no issues (0 silenced).
[HACK - views.py] Method identified as advance_order
[HACK - views.py] list of http_method_names associated with the function: ['get', 'options']
{"detail":"Method \"POST\" not allowed."}
F
======================================================================
FAIL: test_advance_order (Wallet.tests.test_api_vendors.API_VendorTestCase)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/mnt/CommonShare/Code/DVM/APOGEE/Wallet/tests/test_api_vendors.py", line 231, in test_advance_order
    self.assertEqual(r.status_code, 400)
AssertionError: 405 != 400

----------------------------------------------------------------------
Ran 1 test in 0.377s

FAILED (failures=1)
Destroying test database for alias 'default'...

这让我非常困惑,因为这意味着装饰器认识到我想要允许“POST”方法,但是当我的视图“advance_order”被执行时,“POST”不包含在允许的方法列表中。

所以我的问题是:是我的错误吗?如果是这样,怎么做?否则,我能做些什么来解决这样的问题?(删除 __pycache__ 文件不起作用)。

PS为这个非常冗长的问题道歉,我只想非常清楚我的问题。

4

0 回答 0