Best Python code snippet using locust
client.py
Source:client.py  
...84        # set up pre_request hook for attaching meta data to the request object85        self.meta_data["method"] = method86        kwargs.setdefault("timeout", 120)87        self.meta_data["request_time"] = time.time()88        response = self._send_request_safe_mode(method, url, **kwargs)89        # record the consumed time90        self.meta_data["response_time_ms"] = round((time.time() - self.meta_data["request_time"]) * 1000, 2)91        self.meta_data["elapsed_ms"] = response.elapsed.microseconds / 1000.092        self.meta_data["url"] = (response.history and response.history[0] or response)\93            .request.url94        self.meta_data["request_headers"] = response.request.headers95        self.meta_data["request_body"] = response.request.body96        self.meta_data["status_code"] = response.status_code97        self.meta_data["response_headers"] = response.headers98        try:99            self.meta_data["response_body"] = response.json()100        except ValueError:101            self.meta_data["response_body"] = response.content102        msg = "response details:\n"103        msg += "> status_code: {}\n".format(self.meta_data["status_code"])104        msg += "> headers: {}\n".format(self.meta_data["response_headers"])105        msg += "> body: {}".format(self.meta_data["response_body"])106        logger.log_debug(msg)107        # get the length of the content, but if the argument stream is set to True, we take108        # the size from the content-length header, in order to not trigger fetching of the body109        if kwargs.get("stream", False):110            self.meta_data["content_size"] = int(self.meta_data["response_headers"].get("content-length") or 0)111        else:112            self.meta_data["content_size"] = len(response.content or "")113        try:114            response.raise_for_status()115        except RequestException as e:116            logger.log_error(u"{exception}".format(exception=str(e)))117        else:118            logger.log_info(119                """status_code: {}, response_time(ms): {} ms, response_length: {} bytes""".format(120                    self.meta_data["status_code"],121                    self.meta_data["response_time_ms"],122                    self.meta_data["content_size"]123                )124            )125        return response126    def _send_request_safe_mode(self, method, url, **kwargs):127        """128        Send a HTTP request, and catch any exception that might occur due to connection problems.129        Safe mode has been removed from requests 1.x.130        """131        print('HttpSession==>_send_request_safe_mode')132        try:133            msg = "processed request:\n"134            msg += "> {method} {url}\n".format(method=method, url=url)135            msg += "> kwargs: {kwargs}".format(kwargs=kwargs)136            logger.log_debug(msg)137            return requests.Session.request(self, method, url, **kwargs)138        except (MissingSchema, InvalidSchema, InvalidURL):139            raise140        except RequestException as ex:..._httpreq.py
Source:_httpreq.py  
...63                traceback.print_exc()64                raise65            return json.loads(resultObj)66    67    def _send_request_safe_mode(self, method, url, **kwargs):68        """69        Send an HTTP request, and catch any exception that might occur due to connection problems.70        """71        try:72            return HttpReq.s.request(method, url, **kwargs)73        except (MissingSchema, InvalidSchema, InvalidURL):74            raise75        except RequestException as e:76            r = ReqResponse()77            r.error = e78            r.status_code = 0  # with this status_code, content returns None79            r.request = Request(method, url).prepare()80            return r81    def request(self, method, url, **kwargs):82        """83        éç¨è¯·æ±æ¹æ³84        :param method: get/post/put/delete85        :param url: æ¥å£è¯·æ±å°å86        :param kwargs:87        :return:88        """89        resp = self._send_request_safe_mode(method, url, **kwargs)90        return resp...Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
