def inner(request, *args, **kwargs): try: return view(request, *args, **kwargs) except utils.InvalidArgError as e: logging.error(u'请求参数错误:' + unicode(e).decode("unicode-escape")) return HttpResponse(utils.Response(code=-3, msg='请求参数错误:%s' % e).to_json(), content_type='application/json') except Exception as e: logging.error('未知错误:\n' + traceback.format_exc()) return HttpResponse(utils.Response(code=-1, msg='未知错误:%s' % e).to_json(), content_type="application/json")
def _request(self, url_path, query_params, json, expected_codes, json_response): # Construct the URL using url_path, query_params and the api key url = url_path if FLAGS.api_key: if query_params: url = '%s?key=%s&%s' % (url_path, FLAGS.api_key, query_params) else: url = '%s?key=%s' % (url_path, FLAGS.api_key) elif query_params: url = '%s?%s' % (url_path, query_params) # Prepare Headers headers = {'Content-Type': 'application/json'} if FLAGS.auth_token: headers['Authorization'] = 'Bearer ' + FLAGS.auth_token self._conn.request('POST', url, json, headers) response = utils.Response(self._conn.getresponse()) if not response.status_code in expected_codes: print(utils.red( "Invalid status code {}:\n\turl={},\n\trequest_header={},\n\trequest_body={},\n\tresponse={}\n\n").format( response.status_code, url, headers, json, response)) self._unexpected_errors += 1 if json_response and not ( response.status_code != 200 and response.content_type == "text/plain") \ and not response.is_json(): print(utils.red( "response is not json {}:\n\turl={},\n\trequest_header={},\n\trequest_body={},\n\tresponse={}\n\n").format( response.content_type, url, headers, json, response)) self._unexpected_errors += 1 self._total_requests += 1
def _get_status(self): self._status_conn.request('GET', '/ready') status = utils.Response(self._status_conn.getresponse()) if status.status_code != 200: sys.exit(utils.red( 'ESPv2 crash')) return status.text.strip()
def _handle_client(self, client, keep_log): self.request = self._get_request(client) self.response = utils.Response() if not self.request.http_request: client.close() return if keep_log: utils.log( f"{':'.join([str(el) for el in client.getpeername()])} - {self.request.raw_content}" ) # If the path exists, we send the corresponding file # If not, we send the 404 page unknown_path = True for paths, webpage in self.paths[self.request.method]: pathnames = list(map(lambda el: f"/{el}", paths)) if self.request.path in pathnames: self.response.body = webpage() unknown_path = False break if unknown_path: self.response.status_code = 404 self.response.body = utils.sample_404() # Send everthing client.send(self.response.create()) client.close() self.request = None self.response = None