def fetch_content(request: werkzeug.Request, response: werkzeug.Response) -> None: url = request.args["url"] proxy_query_header = make_request_headers(request.headers) try: proxy_response = requests.get(url, headers=proxy_query_header, timeout=TIMEOUT) except requests.exceptions.SSLError: # Invalid SSL Certificate response.status = 526 except requests.exceptions.ConnectionError: response.status = 523 except requests.exceptions.Timeout: response.status = 524 except requests.exceptions.TooManyRedirects: response.status = 520 else: response.body = proxy_response.content if proxy_response.status_code == 500: response.status = 520 else: copy_proxy_headers(proxy_response, response) response.headers["Access-Control-Allow-Origin"] = get_access_url( request.headers)
def _application(self, environ, start_response): request = Request(environ) self.logger.info(request.full_path) status_code = 200 headers = {'Content-Type': 'application/json'} content = '' if request.path == '/': # 接管主页,因为所有请求需要token,主页转发不能正常工作 headers = {'Content-Type': 'text/html'} content = '<h1><a href="https://github.com/xiyaoWong/iotbot-http-transfer">iotbot http tranfer</a><h1>' elif request.path.strip('/') == 'favicon.ico': status_code = 301 del headers['Content-Type'] headers['location'] = 'https://cdn.jsdelivr.net/gh/xiyaowong/FileHost/transfer.png' elif request.path.strip('/') == 'genToken': # 处理token生成请求 key = request.args.get('key') if key == self.key: token = self._genarate_token('ok, it\' funny.') content = json.dumps({'token': token}) else: content = '{"Ret":1111, "Msg":"key错误"}' else: # 处理其他请求 # 鉴权 token = request.args.get('token') or request.headers.get('Authorization') if not self._check_token(token): # 大胆,狗贼 content = '{"Ret":2222, "Msg":"无效的token"}' else: try: resp = requests.request( request.method, '{}{}?{}'.format( 'http://{}:{}'.format(self.iotbot_host, self.iotbot_port), request.path, request.query_string.decode()), headers=request.headers, data=request.data, timeout=self.timeout ) except requests.Timeout as e: self.logger.warning(e) content = '{"Ret":3333, "Msg":"请求响应超时"}' except requests.ConnectionError as e: self.logger.exception(e) content = '{"Ret":4444, "Msg":"连接错误"}' except Exception as e: self.logger.exception(e) content = '{"Ret":5555, "Msg":"请求响应失败"}' else: content = resp.content status_code = resp.status_code headers = resp.headers response = Response(content) response.status = HTTP_STATUS_CODES[status_code] response.status_code = status_code for header_name, header_value in headers.items(): response.headers[header_name] = header_value return response(environ, start_response)