【问题标题】:Proper POST file upload (load testing with Locust)正确的 POST 文件上传(使用 Locust 进行负载测试)
【发布时间】:2016-07-09 20:51:58
【问题描述】:

我正在尝试对基于 Django 的网站进行负载测试。

我使用 Locust 0.7.3 和 python 2.7.10

我在这里做 POST - 填写表格并附加一些文件:

class WebsiteTasks(TaskSet):
    def on_start(self):
        self.client.get("/")

    @task
    def submit(self):
        response = self.client.get("/submit/")
        csrftoken = response.cookies['csrftoken']
        attach = open('file.pdf', 'rb')

        r = self.client.post("/submit/", {
           'csrfmiddlewaretoken': csrftoken,
           'password': smart_str(u'wkefjgui'),
           'payload': smart_str(u'kjsdgfljdsh'),
           'docfile': attach,
           'commit': smart_str(u'Вкрапить / Embed'),
        })

似乎一切正常,但在服务器的上传文件夹中没有文件!

我做错了什么?

【问题讨论】:

    标签: python django locust


    【解决方案1】:

    好吧,我找到了解决方案,我希望它对某人有用:

    这里描述了 Django 如何处理文件: How to send a "multipart/form-data" with requests in python?

    配方是在 post 函数中定义“文件”参数:

        r = self.client.post("/submit/", data={
            'csrfmiddlewaretoken': csrftoken,
            'password': smart_str(u'wkefjgui'),
            'payload': smart_str(u'kjsdgfljdsh'),
            'commit': smart_str(u'Вкрапить / Embed'),
             }, files={'docfile': attach})
    

    【讨论】:

      【解决方案2】:

      处理多部分文件

       def _get_image_part(self, file_path, file_content_type='image/jpeg'):
              import os
              file_name = os.path.basename(file_path)
              file_content = open(file_path, 'rb')
              return file_name, file_content, file_content_type
      

      多部分测试用例

      
      class OpenDeviceFrontApi(TaskSet):
      
          @task(2)
          def rec_log_upload(self):
              payload = {
                  "device_key": device_key
              }
              files = {
                  "scene_img": self._get_image_part("data/face/rec1.jpg"),
                  "face_img": self._get_image_part("data/face/rec2.jpg")
              }
              r = self.client.post("/log/rec_log_upload", data=payload, files=files, verify=False)
              assert r.status_code == 200
              rData = json.loads(r.text, encoding="utf-8")
      
      
      【解决方案3】:

      如何通过 Django 服务器在 Locust 中测试文件上传:

      def post_img(self):
          files = {'media': open('img.png', 'rb')}
          response=self.client.post("/upload",files=files)
          print('Response is -: ',response)
      

      【讨论】:

      • 欢迎来到 StackOverflow。虽然此代码可能会解决问题,但包括解释如何以及为什么解决问题将真正有助于提高您的帖子质量,并可能导致更多的赞成票。请记住,您正在为将来的读者回答问题,而不仅仅是现在提问的人。请编辑您的答案以添加解释并说明适用的限制和假设。看看这里→How do I write a good answer?
      猜你喜欢
      • 1970-01-01
      • 2020-01-02
      • 1970-01-01
      • 2019-12-26
      • 2021-07-29
      • 1970-01-01
      • 2017-04-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多