尝试连接到我用 Django 准备的 API 时收到错误请求警告
I'm getting a bad requests warning when trying to connect to the API I prepared with Django
我有一个用 django 准备的用户 API。但是,当我出于测试目的向 Postman 应用程序发出 API 请求时,我收到 400 Bad Request 警告,这可能是什么原因?如果还有其他需要的代码,我可以把我所有的代码写成如下。
这是views.py代码
from rest_framework_simplejwt.views import TokenObtainPairView
from rest_framework import status
from rest_framework.response import Response
from rest_framework.views import APIView
from .serializers import CustomUserSerializer
from rest_framework_simplejwt.tokens import RefreshToken
from rest_framework.permissions import AllowAny
class CustomUserCreate(APIView):
permission_classes = [AllowAny]
def post(self, request, format='json'):
serializer = CustomUserSerializer(data=request.data)
if serializer.is_valid():
user = serializer.save()
if user:
json = serializer.data
return Response(json, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
class BlacklistTokenUpdateView(APIView):
permission_classes = [AllowAny]
authentication_classes = ()
def post(self, request):
try:
refresh_token = request.data["refresh_token"]
token = RefreshToken(refresh_token)
token.blacklist()
return Response(status=status.HTTP_205_RESET_CONTENT)
except Exception as e:
return Response(status=status.HTTP_400_BAD_REQUEST)
这是我的网址
api/urls.py
from django.urls import path
from .views import CustomUserCreate, BlacklistTokenUpdateView
app_name = 'users'
urlpatterns = [
path('create/', CustomUserCreate.as_view(), name="create_user"),
path('logout/blacklist/', BlacklistTokenUpdateView.as_view(),
name='blacklist')
]
core/urls.py
from django.contrib import admin
from django.urls import path, include
from django.conf.urls.static import static
from django.conf import settings
from rest_framework_simplejwt.views import (
TokenObtainPairView,
TokenRefreshView,
)
urlpatterns = [
path('admin/', admin.site.urls),
path("api/post/", include("post.api.urls", namespace="post")),
path("api/post/audio/", include("post_audio.api.urls", namespace="postaudio")),
path('api/comment/', include('comment.api.urls', namespace='comment')),
path("api/categories/", include("post.api.urls", namespace="categories")),
path("api/author/", include("author.api.urls", namespace="author")),
path("api/favourites/", include("favourite.api.urls", namespace="favourite")),
path('api/token/', TokenObtainPairView.as_view(), name='token_obtain_pair'),
path('api/token/refresh/', TokenRefreshView.as_view(), name='token_refresh'),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
And Also this is my serializers.py code
from rest_framework import serializers
from users.models import NewUser
class CustomUserSerializer(serializers.ModelSerializer):
email = serializers.EmailField(required=True)
user_name = serializers.CharField(required=True)
password = serializers.CharField(min_length=8, write_only=True)
class Meta:
model = NewUser
fields = ('email', 'user_name', 'password')
extra_kwargs = {'password': {'write_only': True}}
def create(self, validated_data):
password = validated_data.pop('password', None)
# as long as the fields are the same, we can just use this
instance = self.Meta.model(**validated_data)
if password is not None:
instance.set_password(password)
instance.save()
return instance
据我所知,您可以从两个地方收到错误请求:CustomUserCreate
和 BlacklistTokenUpdateView
。
为了帮助您调试它,您可以添加日志,包括 serializer.errors
(在 CustomUserCreate
中)和 BlacklistTokenUpdateView
中的除外。一个好的做法是避免捕获一般异常。这样你就会知道失败的确切原因。
400 错误可能表明问题在于您如何从该工具构建请求。
您发送的电子邮件值不是有效的电子邮件格式,而且您似乎也没有发送 user_name,所以我怀疑请求在序列化程序级别验证失败。
根据你的代码
class 如果“serializer.is_valid()” returns 为假,“CustomUserCreate”将返回 400 错误,我认为您没有在 Postman 体内发送所需的参数。
在 class “BlacklistTokenUpdateView” 的情况下 returns 如果发生任何异常,也会出现 400 错误
我有一个用 django 准备的用户 API。但是,当我出于测试目的向 Postman 应用程序发出 API 请求时,我收到 400 Bad Request 警告,这可能是什么原因?如果还有其他需要的代码,我可以把我所有的代码写成如下。
这是views.py代码
from rest_framework_simplejwt.views import TokenObtainPairView
from rest_framework import status
from rest_framework.response import Response
from rest_framework.views import APIView
from .serializers import CustomUserSerializer
from rest_framework_simplejwt.tokens import RefreshToken
from rest_framework.permissions import AllowAny
class CustomUserCreate(APIView):
permission_classes = [AllowAny]
def post(self, request, format='json'):
serializer = CustomUserSerializer(data=request.data)
if serializer.is_valid():
user = serializer.save()
if user:
json = serializer.data
return Response(json, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
class BlacklistTokenUpdateView(APIView):
permission_classes = [AllowAny]
authentication_classes = ()
def post(self, request):
try:
refresh_token = request.data["refresh_token"]
token = RefreshToken(refresh_token)
token.blacklist()
return Response(status=status.HTTP_205_RESET_CONTENT)
except Exception as e:
return Response(status=status.HTTP_400_BAD_REQUEST)
这是我的网址
api/urls.py
from django.urls import path
from .views import CustomUserCreate, BlacklistTokenUpdateView
app_name = 'users'
urlpatterns = [
path('create/', CustomUserCreate.as_view(), name="create_user"),
path('logout/blacklist/', BlacklistTokenUpdateView.as_view(),
name='blacklist')
]
core/urls.py
from django.contrib import admin
from django.urls import path, include
from django.conf.urls.static import static
from django.conf import settings
from rest_framework_simplejwt.views import (
TokenObtainPairView,
TokenRefreshView,
)
urlpatterns = [
path('admin/', admin.site.urls),
path("api/post/", include("post.api.urls", namespace="post")),
path("api/post/audio/", include("post_audio.api.urls", namespace="postaudio")),
path('api/comment/', include('comment.api.urls', namespace='comment')),
path("api/categories/", include("post.api.urls", namespace="categories")),
path("api/author/", include("author.api.urls", namespace="author")),
path("api/favourites/", include("favourite.api.urls", namespace="favourite")),
path('api/token/', TokenObtainPairView.as_view(), name='token_obtain_pair'),
path('api/token/refresh/', TokenRefreshView.as_view(), name='token_refresh'),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
And Also this is my serializers.py code
from rest_framework import serializers
from users.models import NewUser
class CustomUserSerializer(serializers.ModelSerializer):
email = serializers.EmailField(required=True)
user_name = serializers.CharField(required=True)
password = serializers.CharField(min_length=8, write_only=True)
class Meta:
model = NewUser
fields = ('email', 'user_name', 'password')
extra_kwargs = {'password': {'write_only': True}}
def create(self, validated_data):
password = validated_data.pop('password', None)
# as long as the fields are the same, we can just use this
instance = self.Meta.model(**validated_data)
if password is not None:
instance.set_password(password)
instance.save()
return instance
据我所知,您可以从两个地方收到错误请求:CustomUserCreate
和 BlacklistTokenUpdateView
。
为了帮助您调试它,您可以添加日志,包括 serializer.errors
(在 CustomUserCreate
中)和 BlacklistTokenUpdateView
中的除外。一个好的做法是避免捕获一般异常。这样你就会知道失败的确切原因。
400 错误可能表明问题在于您如何从该工具构建请求。
您发送的电子邮件值不是有效的电子邮件格式,而且您似乎也没有发送 user_name,所以我怀疑请求在序列化程序级别验证失败。
根据你的代码 class 如果“serializer.is_valid()” returns 为假,“CustomUserCreate”将返回 400 错误,我认为您没有在 Postman 体内发送所需的参数。
在 class “BlacklistTokenUpdateView” 的情况下 returns 如果发生任何异常,也会出现 400 错误