问题

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


macOS Mojave 10.14
Python 3.6.4(通过Pipenv隔离的环境)
Django 2.1.4
djangorestframework 3.8.2

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

记录

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 protected]","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之间没有区别。

最佳答案

HTTP_405_METHOD_NOT_ALLOWED


状态码405表示您正在使用不允许的方法进行请求。
根据您的代码,您正在定义令牌API,以通过post方法进行访问。

看一下这个日志:

[07/Dec/2018 11:48:09] "POST /account/token/ HTTP/1.1" 200 517


在这种情况下,您发送的是明确的POST请求,这是可以的。但请查看提供的日志以了解失败的案例:

[07/Dec/2018 11:24:30] "{"email":"[email protected]","password":"hidden_password"}POST /v1/account/token/ HTTP/1.1" 405 66


1-由于用户界面中的某种原因,您正在使用方法{"email":"[email protected]","password":"hidden_password"}POST !!!!发送请求。

2-,并且您正在向/v1/account/token/ API端点发送请求,该请求根本没有在您的url中注册(根据您提供给我们的信息)

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

10-12 16:54