驷四 2023-04-13 10:57 采纳率: 0%
浏览 15

压测 性能测试 locust fasthttp上传文件post

locust fasthttp不可以发送上传文件的请求吗
locust,想用fasthttp,我直接class WebLoadtest(FastHttpUser),并且使用了FastHttpSession的request请求,

    def request(
        self,
        method: str,
        path: str,
        name: str = None,
        data: str = None,
        catch_response: bool = False,
        stream: bool = False,
        headers: dict = None,
        auth=None,
        json: dict = None,
        allow_redirects=True,
        context: dict = {},
        **kwargs,
    ):
        """
        Send and HTTP request
        Returns :py:class:`locust.contrib.fasthttp.FastResponse` object.

        :param method: method for the new :class:`Request` object.
        :param path: Path that will be concatenated with the base host URL that has been specified.
            Can also be a full URL, in which case the full URL will be requested, and the base host
            is ignored.
        :param name: (optional) An argument that can be specified to use as label in Locust's
            statistics instead of the URL path. This can be used to group different URL's
            that are requested into a single entry in Locust's statistics.
        :param catch_response: (optional) Boolean argument that, if set, can be used to make a request
            return a context manager to work as argument to a with statement. This will allow the
            request to be marked as a fail based on the content of the response, even if the response
            code is ok (2xx). The opposite also works, one can use catch_response to catch a request
            and then mark it as successful even if the response code was not (i.e 500 or 404).
        :param data: (optional) String/bytes to send in the body of the request.
        :param json: (optional) Dictionary to send in the body of the request.
            Automatically sets Content-Type and Accept headers to "application/json".
            Only used if data is not set.
        :param headers: (optional) Dictionary of HTTP Headers to send with the request.
        :param auth: (optional) Auth (username, password) tuple to enable Basic HTTP Auth.
        :param stream: (optional) If set to true the response body will not be consumed immediately
            and can instead be consumed by accessing the stream attribute on the Response object.
            Another side effect of setting stream to True is that the time for downloading the response
            content will not be accounted for in the request time that is reported by Locust.
        """
        # prepend url with hostname unless it's already an absolute URL


但是,它好像不支持form-data?

 def _make_request(self, url, method='GET', headers=None, payload=None):
        req_headers = self.default_headers.copy()
        if headers:
            req_headers.update(headers)
        if payload:
            # Adjust headers depending on payload content
            content_type = req_headers.get('content-type', None)
            if not content_type and isinstance(payload, dict):
                req_headers['content-type'] = "application/x-www-form-urlencoded; charset=utf-8"
                payload = urlencode(payload)
            elif not content_type and isinstance(payload, text_type):
                req_headers['content-type'] = 'text/plain; charset=utf-8'
            elif not content_type:
                req_headers['content-type'] = 'application/octet-stream'
            elif content_type.startswith("multipart/form-data"):
                # See restkit for some example implementation
                # TODO: Implement it
                raise NotImplementedError
        return self.request_type(url, method=method, headers=req_headers, payload=payload)

问题,我如何进行非纯文本文件,例如图片、mp3发送的post请求呢 如果我想使用fasthttp进行测试(不使用用httpuser),也许我需要用geventhttp重新构造吗

  • 写回答

1条回答 默认 最新

  • CSDN-Ada助手 CSDN-AI 官方账号 2023-04-18 20:28
    关注
    不知道你这个问题是否已经解决, 如果还没有解决的话:
    • 以下回答来自chatgpt: 对于FastHttpSession不支持form-data格式的问题,我们可以使用MultipartFormDataWriter来构造form-data格式的请求,支持发送非纯文本文件。具体步骤如下: 1. 首先导入相关的包: ```python from io import BytesIO from fasthttp.multipart import MultipartFormDataWriter ``` 2. 构造MultipartFormDataWriter对象: ```python content_type, body = write_form_data() mpw = MultipartFormDataWriter(boundary=b'--------------------------abc123') mpw.add_header('Content-Type', content_type) mpw.append('body', body, { 'Content-Type': 'application/octet-stream', 'filename': 'your_filename' }) ``` 其中,write_form_data() 是一个自定义的函数,用于返回Content-Type和请求体(body),其构造方式和普通form-data类似,只不过需要包含非纯文本文件。例如: ```python def write_form_data(): filename = 'your_file_path' with open(filename, 'rb') as f: body = BytesIO(f.read()) content_type = 'multipart/form-data; boundary=--------------------------abc123\r\n' return content_type, body ``` 3. 将构造好的表单数据加入到请求中: ```python req = http.Request('POST', url) mpw.add_headers(req.headers) mpw.add_session(self.session) ``` 其中,http是FastHttpSession的一个实例,可更改为任意FastHttpSession实例。 至于第二个问题,如果想使用fasthttp进行测试(不使用HttpUser),是不需要使用geventhttp重新构造请求的。FastHttpSession和geventhttp虽然使用方式不同,但都可用于发送HTTP请求。而使用HttpUser则是一种更高级的快速测试工具,需要根据具体情况进行选择。

    如果你已经解决了该问题, 非常希望你能够分享一下解决方案, 写成博客, 将相关链接放在评论区, 以帮助更多的人 ^-^
    评论

报告相同问题?

问题事件

  • 创建了问题 4月13日

悬赏问题

  • ¥20 模型在y分布之外的数据上预测能力不好如何解决
  • ¥15 processing提取音乐节奏
  • ¥15 gg加速器加速游戏时,提示不是x86架构
  • ¥15 python按要求编写程序
  • ¥15 Python输入字符串转化为列表排序具体见图,严格按照输入
  • ¥20 XP系统在重新启动后进不去桌面,一直黑屏。
  • ¥15 opencv图像处理,需要四个处理结果图
  • ¥15 无线移动边缘计算系统中的系统模型
  • ¥15 深度学习中的画图问题
  • ¥15 java报错:使用mybatis plus查询一个只返回一条数据的sql,却报错返回了1000多条