问题描述
我做了一个最小的例子,完全重复了我的代码的行为。我从firefox和chrome发送请求。我注意到,在chrome发出请求后,firefox不再收到答案。经过一些研究,我意识到服务器响应localhost:8000 / favicon.ico路径请求时出现错误。一次收到错误404后,chrome在来自服务器的每个响应之后都会创建到该服务器的另一个连接,但不发送数据,这会导致recv函数锁定。
File "/usr/lib/python3.7/socket.py",line 589,in readinto
return self._sock.recv_into(b)
我发现可以为处理程序类设置连接超时,它在StreamRequestHandler:r中已考虑在内:
if self.timeout is not None:
self.connection.settimeout(self.timeout)
但是我很尴尬的是在文档中没有关于此的信息 https://docs.python.org/3/library/socketserver.html#socketserver.BaseRequestHandler.handle
import logging
import json
import http.server
from http import HTTPStatus
from typing import Optional
from urllib.parse import urlparse,parse_qs
import socketserver
from threading import Thread
import traceback
from functools import wraps
import sys,os
project_dir = os.path.abspath(os.curdir)
sys.path.append(project_dir)
logging.getLogger().setLevel("DEBUG")
class RESTHandler(http.server.BaseHTTPRequestHandler):
"""
Rest router for api methods
"""
def __init__(self,*args,**kwargs):
logging.info(f"Creating RESTHandler obj. Args: {args},kwargs: {kwargs}")
super().__init__(*args,**kwargs)
def end_headers(self) -> None:
self.send_header('Access-Control-Allow-Origin','*')
http.server.BaseHTTPRequestHandler.end_headers(self)
# noinspection PyPep8Naming
def do_GET(self):
logging.info(self.path)
url = urlparse(self.path)
if "favicon.ico" in url.path:
self.send_error(HTTPStatus.NOT_FOUND,message='UnkNown api path.')
return
self.send_response(HTTPStatus.OK)
self.send_header('Content-Type','application/json')
self.end_headers()
self.wfile.write(json.dumps({"resp":"I am OK","int": 5},ensure_ascii=False).encode('utf-8'))
class ApiService():
DEFAULT_API_PORT = 8000
DEFAULT_API_HOST = ''
def __init__(self,ui_service = None,host: Optional[str] = None,port: Optional[int] = None):
self.ui_service = ui_service
self.host = host or self.DEFAULT_API_HOST
self.port = port or self.DEFAULT_API_PORT
def _run(self):
while True:
try:
with socketserver.Tcpserver((self.host,self.port),RESTHandler,bind_and_activate=False) as httpd:
logging.info("Starting server....")
httpd.allow_reuse_address = True
httpd.server_bind()
httpd.server_activate()
logging.info(f"Serving API at {self.host}:{self.port}")
httpd.serve_forever()
break
except Exception as e:
tb_list = traceback.format_exception( type(e),e,tb=e.__traceback__)
tb_list = [ s.replace("\n","") for s in tb_list ]
tb_str = "; ".join(tb_list)
logging.error(f"Unexpected exception while http-server was working: {tb_str}")
def run(self,in_thread=True):
if in_thread:
t = Thread(target=self._run)
t.start()
else:
self._run()
if __name__ == '__main__':
ApiService().run(in_thread=False)
解决方法
我猜想,Chrome浏览器会使用预打开套接字的网络浏览器,在我看来,TCPServer会无限期等待。但是我仍然很有趣,为什么只有在404之后,使用请求处理程序超时的合法性又如何呢?