python http客户端卡在100上继续
我有一个简单的python http服务器,它使用100 continue实现PUT:python http客户端卡在100上继续,python,python-3.x,http,Python,Python 3.x,Http,我有一个简单的python http服务器,它使用100 continue实现PUT: class TestHandler(SimpleHTTPRequestHandler): def do_PUT(self): length = int(self.headers.get('Content-Length')) self.send_response_only(100) self.end_headers() data = sel
class TestHandler(SimpleHTTPRequestHandler):
def do_PUT(self):
length = int(self.headers.get('Content-Length'))
self.send_response_only(100)
self.end_headers()
data = self.rfile.read(length)
res = manipulate(data)
new_length = len(res)
self.send_response(200)
self.send_header("Content-Length", new_length)
self.end_headers()
self.wfile.write(res)
server = HTTPServer(("localhost", 8080), TestHandler)
server.serve_forever()
我尝试使用此客户端连接到服务器:
def send_put(data):
c = HTTPConnection('localhost', 8080)
c.request('PUT', 'http://localhost:8080/', headers={'Content-Length': len(data), 'Expect': '100-continue'})
r = c.getresponse()
if 100 != r.status:
return
c.request('PUT', 'http://localhost:8080/', body=data)
r = c.getresponse()
print(r.read())
但是代码总是卡在第一个“getresponse”上,即使我可以在wireshark上看到100 continue响应,我在这里做错了什么?python http是否支持100继续
编辑:在查看了一些python http代码之后,我发现了getresponse被卡住的原因;python的http只是忽略100 continue并等待下一个永远不会出现的响应(来自python3.4/http/client.py):
我也遇到了这个问题;这是一个好主意。我提出了以下相当粗俗的“让它运行”变通方法,在我的情况下(仅限Python 3.5,HTTPS)似乎是可行的: 我是这样使用它的:
conn = ContinueHTTPSConnection(host)
conn.request(...)
resp = conn.getresponse()
if resp.status == http.client.CONTINUE:
resp.read()
conn.send(body)
resp = conn.getresponse()
# do something with resp if you want...
警告:超级黑客。可能到处都是虫子。使用风险自负。您是否尝试发送
wget localhost:8080
。还可以尝试使用sudo
运行python代码。。我运行了您的代码并获得了AttributeError:TestHandler实例没有属性'send\u response\u only'
。另外,AFAIK python请求不支持100 continuedid您是否使用python3运行它?python 3.2中添加了send_response_only以支持100 continue。
class ContinueHTTPResponse(http.client.HTTPResponse):
def _read_status(self, *args, **kwargs):
version, status, reason = super()._read_status(*args, **kwargs)
if status == 100:
status = 199
return version, status, reason
def begin(self, *args, **kwargs):
super().begin(*args, **kwargs)
if self.status == 199:
self.status = 100
def _check_close(self, *args, **kwargs):
return super()._check_close(*args, **kwargs) and self.status != 100
class ContinueHTTPSConnection(http.client.HTTPSConnection):
response_class = ContinueHTTPResponse
def getresponse(self, *args, **kwargs):
logging.debug('running getresponse')
response = super().getresponse(*args, **kwargs)
if response.status == 100:
setattr(self, '_HTTPConnection__state', http.client._CS_REQ_SENT)
setattr(self, '_HTTPConnection__response', None)
return response
conn = ContinueHTTPSConnection(host)
conn.request(...)
resp = conn.getresponse()
if resp.status == http.client.CONTINUE:
resp.read()
conn.send(body)
resp = conn.getresponse()
# do something with resp if you want...