python 我在Django 2.1版本的Django Rest Framework中创建了一个基本身份验证,但它显示'.authenticate()must be overrided'错误

lpwwtiir  于 2023-10-14  发布在  Python
关注(0)|答案(3)|浏览(81)

设置.py

REST_FRAMEWORK = { 'DEFAULT_PERFORMANCE_CLASSES':('rest_framework.authentication. BasicAuthentication',),'DEFAULT_PERMISSION_CLASSES':('rest_framework.permissions. IsAuthenticated',)}

models.py

from django.db import models
class Emp(models.Model):
    eid = models.IntegerField()
    ename = models.CharField(max_length=30)
    sal = models.IntegerField()
    def __str__(self):
        return self.ename

admin.py

from django.contrib import admin
from .models import Emp
class AdminEmp(admin.ModelAdmin):
    list_display = ['eid','ename','sal']
admin.site.register(Emp,AdminEmp)

serializers.py

from .models import Emp
from rest_framework import serializers
class EmpSerializer(serializers.ModelSerializer):
    class Meta:
        model = Emp
        fields = ('eid','ename','sal')

views.py

from .serializers import EmpSerializer
from .models import Emp
from rest_framework import viewsets
from rest_framework.authentication import BaseAuthentication
from rest_framework.permissions import IsAuthenticated
class EmpViewSet2(viewsets.ModelViewSet):
    authentication_classes = (BaseAuthentication,)
    permission_classes = (IsAuthenticated,)
    queryset = Emp.objects.all()
    serializer_class = EmpSerializer

应用级别urls.py

from django.conf.urls import url,include
from .views import EmpViewSet2
from rest_framework.routers import DefaultRouter
router = DefaultRouter()
router.register('emp_viewset',EmpViewSet2,base_name='emp_viewset2')
urlpatterns = [
url(r'',include(router.urls)) ]

项目级urls.py

from django.contrib import admin
from django.urls import path,include
urlpatterns = [
    path('admin/', admin.site.urls),
    path('api/', include('Basic_Authentication_App.urls'))
]

密码和密码窗口x1c 0d1x
Django Rest Framework窗口 * 但是当我点击这个链接“emp_viewset”:“http://127.0.0.1:3499/api/emp_viewset/“*

它显示如下:**必须覆盖/API/emp_viewset/.authenticate()中的NotImplementedError。

deikduxw

deikduxw1#

您需要编写自己的身份验证后端。你可以从官方的django文档中看到一个例子,它详细解释了如何实现(即重写)authenticate函数。
当然,如果您想提供自己的权限,可以实现自定义身份验证后端。

5uzkadbs

5uzkadbs2#

从views.py删除以下代码:-

authentication_classes = (BaseAuthentication,)
permission_classes = (IsAuthenticated,)

一切都会正常的。如果您想更改权限,只需在www.example.com中添加views.py
permission_classes = []
不需要添加
认证类
所以
权限类
views.py将覆盖settings.py中给出的权限。
谢谢.

fkaflof6

fkaflof63#

authentication_classes =(BaseAuthentication,)permission_classes =(IsAuthenticated,)您使用的是BaseAuthentication而不是BasicAuthentication,这就是出现“NotImplementedError at /API/emp_viewset/ .authenticate()must be overrided”错误的原因

相关问题