【问题标题】:I'm getting a bad requests warning when trying to connect to the API I prepared with Django尝试连接到使用 Django 准备的 API 时收到错误请求警告
【发布时间】:2021-10-30 04:51:21
【问题描述】:

我有一个用 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')
]

核心/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) 

这也是我的 serializers.py 代码

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

【问题讨论】:

    标签: python django api rest django-rest-framework


    【解决方案1】:

    400 错误可能表明问题在于您如何从该工具构建请求。

    您发送的电子邮件值不是有效的电子邮件格式,而且您似乎也没有发送用户名,因此我怀疑请求在序列化程序级别验证失败。

    【讨论】:

    • 127.0.0.1:8000/api/token 这是我的邮递员电话,结果如下: { "email": [ "Bualan zorunlu." ], "密码": [ "布艾伦佐润露。" ] }
    • 您发送的电子邮件值不是有效的电子邮件格式,而且您似乎也没有发送用户名,所以我怀疑请求在序列化程序级别验证失败。跨度>
    【解决方案2】:

    根据您的代码 如果“serializer.is_valid()”返回false,类“CustomUserCreate”返回400错误,我认为你没有在邮递员体内发送所需的参数。

    如果发生任何异常,“BlacklistTokenUpdateView”类也会返回 400 错误

    【讨论】:

    • 我应该看看我的序列化程序代码吗?
    • 是的,还要检查 Postman 的 body 参数,这些必须匹配
    • 好的,非常感谢我的兄弟,它可以工作了 :)
    【解决方案3】:

    据我所知,您可以从两个地方收到错误请求:CustomUserCreateBlacklistTokenUpdateView。 为了帮助您调试此问题,您可以添加日志,包括 serializer.errors(在 CustomUserCreate 中)以及在 BlacklistTokenUpdateView 中的 except。一个好的做法是避免捕获通用异常。这样您就可以确切地知道它失败的原因。

    【讨论】:

      猜你喜欢
      • 2021-03-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-04-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-06-22
      相关资源
      最近更新 更多