简体   繁体   English

在 Locust 上测试 DRF 端点时获取“未提供身份验证凭据”

[英]Getting "Authentication Credentials Were not Provided" when testing DRF endpoint on Locust

I am trying to load test an endpoint that allows users to create posts using locust, it is worth mentioning that users need to be authenticated before they can access this endpoint.我正在尝试对允许用户使用 locust 创建帖子的端点进行负载测试,值得一提的是,用户在访问此端点之前需要经过身份验证。

Problem: When I hit the endpoint using locust, I keep getting the error saying "Authentication provided were not provided" even though I have done so and I have also configured my endpoint to accept token (I am using the default DRF token feature).问题:当我使用蝗虫访问端点时,我不断收到错误消息“未提供提供的身份验证”,尽管我已经这样做了,而且我还配置了我的端点以接受令牌(我使用的是默认的 DRF 令牌功能)。 Any idea what I am doing wrong?知道我做错了什么吗? any help will be appreciated.任何帮助将不胜感激。 Below is my code:下面是我的代码:

Locust file蝗虫档案

class ListPostUser(HttpUser):
    wait_time = between(1, 5)

    @task(3)
    def create_post(self):
        data = {
            "title": "This is another random title", 
            "body": "This is the body of a randomly titled post"
        }
        headers = {
            "Authorization": "Token 508e650b0ca1613818939089190a1661a75865b1"
        }
        response = self.client.post("blog/create", json=data, headers=headers)

        print(response)
        print(response.json())

    @task
    def comment_detail(self):
        self.client.get("blog/comment/1")

    @task(2)
    def post_detail(self):
        self.client.get("blog/post/1")


    def on_start(self):
        self.client.post("login/", json={"username": "username", "password": "mypassword"})

views file查看文件

class CreatePostAPI(APIView):
    permission_classes = (IsAuthenticated, )
    
    def post(self, request):
        serializer = CreatePostSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save(user=self.request.user)
            return Response(serializer.data, status=status.HTTP_200_OK)

I should also note that the endpoint works fine on POSTMAN, I only get the error when I am load testing with locust我还应该注意端点在 POSTMAN 上工作正常,我只在使用 Locust 进行负载测试时才收到错误

Not sure if this will help you find the real issue, but you can investigate the exact payload sent by examining response.request , like this:不确定这是否会帮助您找到真正的问题,但您可以通过检查response.request来调查发送的确切负载,如下所示:

print(response.request.headers) print(response.request.data) print(response.request.headers) print(response.request.data)

I finally found a solution to the issue, All I needed to do was add TokenAuthentication to the list of default authentication classes in settings.py file我终于找到了解决问题的方法,我需要做的就是将TokenAuthentication添加到 settings.py 文件中的默认身份验证类列表中

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': 
    [
        'rest_framework.authentication.TokenAuthentication',
        ...
    ],
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM