def request(self, method, url, name=None, **kwargs): """ Constructs and sends a :py:class:`requests.Request`. 构造并发送一个:py:class: ' requests.Request ' Returns :py:class:`requests.Response` object. :param method: method for the new :class:`Request` object. :param url: URL for the new :class:`Request` object. :param name: (optional) Placeholder, make compatible with Locust's HttpSession :param params: (optional) Dictionary or bytes to be sent in the query string for the :class:`Request`. :param data: (optional) Dictionary or bytes to send in the body of the :class:`Request`. :param headers: (optional) Dictionary of HTTP Headers to send with the :class:`Request`. :param cookies: (optional) Dict or CookieJar object to send with the :class:`Request`. :param files: (optional)上传文件 Dictionary of ``'filename': file-like-objects`` for multipart encoding upload. :param auth: (optional)认证元组或可调用,以启用基本/摘要/自定义HTTP认证 Auth tuple or callable to enable Basic/Digest/Custom HTTP Auth. :param timeout: (optional) How long to wait for the server to send data before giving up, as a float, or \ a (`connect timeout, read timeout <user/advanced.html#timeouts>`_) tuple. :type timeout: float or tuple :param allow_redirects: (optional)允许重定向 Set to True by default. :type allow_redirects: bool :param proxies: (optional)代理 Dictionary mapping protocol to the URL of the proxy. :param stream: (optional)是否立即下载响应内容。默认为' '假' ' whether to immediately download the response content. Defaults to ``False``. :param verify: (optional)如果' ' True ' ',将验证SSL证书。还可以提供CA_BUNDLE路径。 if ``True``, the SSL cert will be verified. A CA_BUNDLE path can also be provided. :param cert: (optional)ssl客户端证书文件(.pem)的路径。If元组,('cert', 'key')对 if String, path to ssl client cert file (.pem). If Tuple, ('cert', 'key') pair. """ self.init_meta_data() # record test name self.meta_data["name"] = name # record original request info记录原始请求信息 self.meta_data["data"][0]["request"]["method"] = method self.meta_data["data"][0]["request"]["url"] = url kwargs.setdefault("timeout", 120) self.meta_data["data"][0]["request"].update(kwargs) start_timestamp = time.time() response = self._send_request_safe_mode(method, url, **kwargs) response_time_ms = round((time.time() - start_timestamp) * 1000, 2) # get the length of the content, but if the argument stream is set to True, we take # 获取内容的长度,但如果参数流被设置为True,则获取 # the size from the content-length header, in order to not trigger fetching of the body # 从内容长度标题中获取的大小,以便不触发对主体的获取 if kwargs.get("stream", False): content_size = int( dict(response.headers).get("content-length") or 0) else: content_size = len(response.content or "") # record the consumed time记录消耗的时间 self.meta_data["stat"] = { "response_time_ms": response_time_ms, "elapsed_ms": response.elapsed.microseconds / 1000.0, "content_size": content_size } # record request and response histories, include 30X redirection # 记录请求和响应历史,包括30次重定向 response_list = response.history + [response] self.meta_data["data"] = [ get_req_resp_record(resp_obj) for resp_obj in response_list ] try: response.raise_for_status() except RequestException as e: logger.log_error(u"{exception}".format(exception=str(e))) else: logger.log_info( """status_code: {}, response_time(ms): {} ms, response_length: {} bytes\n""" .format(response.status_code, response_time_ms, content_size)) return response
def request(self, method, url, name=None, **kwargs): """ Constructs and sends a :py:class:`requests.Request`. Returns :py:class:`requests.Response` object. :param method: method for the new :class:`Request` object. :param url: URL for the new :class:`Request` object. :param name: (optional) Placeholder, make compatible with Locust's HttpSession :param params: (optional) Dictionary or bytes to be sent in the query string for the :class:`Request`. :param data: (optional) Dictionary or bytes to send in the body of the :class:`Request`. :param headers: (optional) Dictionary of HTTP Headers to send with the :class:`Request`. :param cookies: (optional) Dict or CookieJar object to send with the :class:`Request`. :param files: (optional) Dictionary of ``'filename': file-like-objects`` for multipart encoding upload. :param auth: (optional) Auth tuple or callable to enable Basic/Digest/Custom HTTP Auth. :param timeout: (optional) How long to wait for the server to send data before giving up, as a float, or \ a (`connect timeout, read timeout <user/advanced.html#timeouts>`_) tuple. :type timeout: float or tuple :param allow_redirects: (optional) Set to True by default. :type allow_redirects: bool :param proxies: (optional) Dictionary mapping protocol to the URL of the proxy. :param stream: (optional) whether to immediately download the response content. Defaults to ``False``. :param verify: (optional) if ``True``, the SSL cert will be verified. A CA_BUNDLE path can also be provided. :param cert: (optional) if String, path to ssl client cert file (.pem). If Tuple, ('cert', 'key') pair. """ self.init_meta_data() # record test name self.meta_data["name"] = name # record original request info self.meta_data["data"][0]["request"]["method"] = method self.meta_data["data"][0]["request"]["url"] = url kwargs.setdefault("timeout", 120) self.meta_data["data"][0]["request"].update(kwargs) start_timestamp = time.time() response = self._send_request_safe_mode(method, url, **kwargs) response_time_ms = round((time.time() - start_timestamp) * 1000, 2) # get the length of the content, but if the argument stream is set to True, we take # the size from the content-length header, in order to not trigger fetching of the body if kwargs.get("stream", False): content_size = int( dict(response.headers).get("content-length") or 0) else: content_size = len(response.content or "") # record the consumed time self.meta_data["stat"] = { "response_time_ms": response_time_ms, "elapsed_ms": response.elapsed.microseconds / 1000.0, "content_size": content_size } # record request and response histories, include 30X redirection response_list = response.history + [response] self.meta_data["data"] = [ get_req_resp_record(resp_obj) for resp_obj in response_list ] try: response.raise_for_status() except RequestException as ex: logger.error(f"{str(ex)}") else: logger.info(f"status_code: {response.status_code}, " f"response_time(ms): {response_time_ms} ms, " f"response_length: {content_size} bytes\n") return response