python - Django 意外的 405 响应

标签 python django django-rest-framework http-status-code-405

  1. 问题

    我的 django 应用程序经常响应 405 Method Now Allowed 即使 它是在开发环境上工作的API。但如果我重新启动 开发服务器(python manage.py runserver)它可以工作。

  2. 环境

    • macOS Mojave 10.14
    • Python 3.6.4(通过 Pipenv 隔离环境)
    • Django 2.1.4
    • djangorestframework 3.8.2
  3. API代码

    settings/urls.py(根 URL 文件)

    from django.urls import path, include
    
    import my_account.urls
    
    urlpatterns = [
        path('account/', include(my_account.urls, namespace='account_v1')),
    ]
    

    my_account/urls.py

    from django.urls import path
    
    from .apps import MyAccountConfig
    from .views import TokenView
    
    app_name = MyAccountConfig.name
    
    urlpatterns = [
        path('token/', TokenView.as_view()),
    ]
    

    my_account/views.py

    from rest_framework.views import APIView
    
    class TokenView(APIView):
        def post(self, request):
            # Some Business-Logic Code
            pass
    
  4. 日志

    发生 405 时记录

    System check identified no issues (0 silenced).
    December 07, 2018 - 11:22:54
    Django version 2.1.4, using settings 'my_server.settings.staging'
    Starting development server at http://0.0.0.0:8000/
    Quit the server with CONTROL-C.
    .env Applied
    [07/Dec/2018 11:24:30] "OPTIONS /account/token/ HTTP/1.1" 200 0
    [07/Dec/2018 11:24:30] "{"email":"email@hidden.com","password":"hidden_password"}POST /account/token/ HTTP/1.1" 405 66
    

    工作时记录

    System check identified no issues (0 silenced).
    December 07, 2018 - 11:48:01
    Django version 2.1.4, using settings 'my_server.settings.staging'
    Starting development server at http://0.0.0.0:8000/
    Quit the server with CONTROL-C.
    .env Applied
    [07/Dec/2018 11:48:08] "OPTIONS /account/token/ HTTP/1.1" 200 0
    [07/Dec/2018 11:48:09] "POST /account/token/ HTTP/1.1" 200 517
    

    在chrome网络选项卡中,200和405的请求没有区别。

最佳答案

过去两个月我也遇到了同样的错误,最终我解决了。 错误: 当用户 token 过期时,我们将收到带有未经授权消息的 401 状态代码,当发生这种情况时,下一个 API 也会被中断,它会返回 405 Method Not Allowed 作为错误。
解决方案 : Django 版本 2.1 中存在错误问题,您必须将 Django 版本升级到 2.2。

检查此错误后,它将不会引发。

关于python - Django 意外的 405 响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53662558/

相关文章:

javascript - 如何将 HTML 表单文本字段的值获取到 Django View 中?

python - DRF get_permissions 似乎无法正常工作

python - future 警告 : Method . ptp

python - 我怎样才能减少查询的数量?

python - 如何使用redis for python在Redis中搜索值

python - Django - 属性错误 : 'NoneType' object has no attribute 'method'

Django:更改序列化器中字段的表示

python - 这段代码真的是私有(private)的吗? (Python)

python - 矩阵乘法 Python 与 Swift 中的不同输出

django - 消息 - 找不到已安装的 python-django 或 python3-django 版本