python - 使用 Postman 进行 Django Rest Framework token 身份验证

标签 python django django-rest-framework postman

我正在尝试使用 Postman 来测试我的 DRF 端点,但我总是收到 Authentication credentials were not provided. 错误。端点工作正常,但我还没有找到如何从 Postman 发送请求。

我能够为用户获取 token :

enter image description here

但是当我尝试使用 token 发送请求时,我总是得到错误:

enter image description here

我将授权类型设置为Inherit auth from parent

这是 View 的代码:

class AlbumViewSet(viewsets.ModelViewSet):
    permission_classes = (permissions.IsAuthenticated,)
    queryset = proxies.AlbumProxy.objects.all()
    serializer_class = serializers.AlbumSerializer
    filter_backends = (DjangoFilterBackend, SearchFilter, OrderingFilter,)
    search_fields = ('name', 'description', 'company__name')
    filter_fields = ('code', 'company')

    def get_permissions(self):
        if self.action == 'retrieve':
            return []

        return super(AlbumViewSet, self).get_permissions()

    def retrieve(self, request, pk):
        password = request.query_params.get('password', None)

        try:
            instance = proxies.AlbumProxy.objects.get(pk=pk)
        except:
            return Response({'success': False, 'code': 1})

        if instance.access_code != password and password != settings.MASTER_KEY:
            return Response({'success': False, 'code': 2})

        instance_to_return = serializers.AlbumSerializer(instance=instance, context={'request': request}).data
        instance_to_return.pop('access_code')
        instance_to_return['success'] = True

        return Response(instance_to_return)

这是我的 REST_FRAMEWORK 来自 settings 的常量:

REST_FRAMEWORK = {
    'DEFAULT_PERMISSION_CLASSES': ('rest_framework.permissions.IsAuthenticated',),
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework.authentication.TokenAuthentication',
        'rest_framework.authentication.SessionAuthentication',
    ),
    'DEFAULT_FILTER_BACKENDS': ('django_filters.rest_framework.DjangoFilterBackend',),
    'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.LimitOffsetPagination',
    'PAGE_SIZE': 20,
    'DEFAULT_METADATA_CLASS': 'rest_framework.metadata.SimpleMetadata'
}

最佳答案

就您使用 Apache 而言,您需要:

WSGIPassAuthorization On

将它添加到您的 httpd.conf

更多详情 there .

关于python - 使用 Postman 进行 Django Rest Framework token 身份验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53829225/

相关文章:

python - 部署了 rest-framework 的 django 时出错

python - Django 基于类的 View 中的密码格式无效或未知的哈希算法

python - 如何在 HttpResponse 中编写 Django 模板标签 {% %}

python - 使用 Python 转发邮件并添加新内容

django - 无法解析 django 中的提醒

django - 如何使用 Django admin 使用 Celery 创建自定义任务

python - 将 GET 参数转换为 Django REST Framework 中 Request 对象上的 POST 数据

python - 属性访问在 print 语句中有效,但在 while 循环中引发有关 NoneType 的 AttributeError

python - 如何重用 hashlib.md5 的实例

Python oauth2 - 发出请求