Python 如何在生成asyncore.dispatcher对象时跳过坏主机?

Python 如何在生成asyncore.dispatcher对象时跳过坏主机?,python,asyncore,Python,Asyncore,出现了一个错误: import asyncore class HTTPClient(asyncore.dispatcher): def __init__(self, host, path): asyncore.dispatcher.__init__(self) self.create_socket() self.connect( (host, 80) ) self.buffer = bytes('GET %s HTTP/

出现了一个错误:

import asyncore

class HTTPClient(asyncore.dispatcher):

    def __init__(self, host, path):
        asyncore.dispatcher.__init__(self)
        self.create_socket()
        self.connect( (host, 80) )
        self.buffer = bytes('GET %s HTTP/1.0\r\nHost: %s\r\n\r\n' %
                            (path, host), 'ascii')

    def handle_connect(self):
        pass

    def handle_close(self):
        self.close()

    def handle_read(self):
        print(self.recv(8192))

    def writable(self):
        return (len(self.buffer) > 0)

    def handle_write(self):
        sent = self.send(self.buffer)
        self.buffer = self.buffer[sent:]


client = HTTPClient('www.bocaonews.com.br', '/')
asyncore.loop()
回溯(最近一次呼叫最后一次):
文件“”,第1行,在
文件“***.py”,第15行,在_init中__
自连接((主机,80))
文件“***\lib\asyncore.py”,第339行,在connect中
err=self.socket.connect\u ex(地址)
socket.gaierror:[Errno 11004]getaddrinfo失败
HTTP客户端是官方文档的示例。由于无法访问主机www.bocaownews.com.br,因此引发了错误


所以我的问题是,如何修改代码,让客户端在主机坏时自动关闭连接?我可以在生成调度程序之前检查主机。但是它的效率较低。

asyncore在简化错误处理方面没有提供太多功能。大部分情况下,这让你对此负责。因此,解决方案是在应用程序代码中添加错误处理:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "***.py", line 15, in __init__
    self.connect( (host, 80) )
  File "***\lib\asyncore.py", line 339, in connect
    err = self.socket.connect_ex(address)
socket.gaierror: [Errno 11004] getaddrinfo failed
为了让您的生活更轻松,您可能不想在
HTTPClient.\uuuu init\uuuu
内部调用
connect

另外,为了进行比较,这里有一个基于Twisted的HTTP/1.1客户端:

try:
    client = HTTPClient('www.bocaonews.com.br', '/')
except socket.error as e:
    print 'Could not contact www.bocaonews.com.br:', e
else:
    asyncore.loop()
from twisted.internet import reactor
from twisted.web.client import Agent

a = Agent(reactor)
getting = a.request(b"GET", b"http://www.bocaonews.com.br/")
def got(response):
    ...
def failed(reason):
    print 'Request failed:', reason.getErrorMessage()
getting.addCallbacks(got, failed)
reactor.run()