下面是 根据官方例子改变的 发送http请求的 代码~~
from twisted.internet.defer import Deferred
from twisted.internet.protocol import Protocol
from twisted.web.client import Agent
from twisted.web.http_headers import Headers
from zope.interface import implements
from twisted.internet.defer import succeed
from twisted.web.iweb import IBodyProducer
from twisted.internet.protocol import ClientCreator
class StringProducer(object):
implements(IBodyProducer)
def __init__(self, body):
self.body = body
self.length = len(body)
def startProducing(self, consumer):
consumer.write(self.body)
return succeed(None)
def pauseProducing(self):
pass
def stopProducing(self):
pass
class BeginningPrinter(Protocol):
def __init__(self, finished, results):
self.finished = finished
self.remaining = 1024 * 100
self.results = results
def dataReceived(self, bytes):
if self.remaining:
display = bytes[:self.remaining]
self.results.append(display)
self.remaining -= len(display)
def connectionLost(self, reason):
self.finished.callback(None)
def connectionFailed(self, reason):
print 'Connection failed. Reason:', reason
import simplejson as json
import operator ,uuid,logging
from xml.dom.minidom import parseString
def refresh_url(addresses,command):
from twisted.internet import reactor
errors = []
results = []
def cbRequest(response,address):
finished = Deferred()
response.deliverBody(BeginningPrinter(finished,results))
return finished
def cbShutdown(ignored):
if len(counter)+len(errors) == len(addresses):
reactor.stop()
def cbError(err,address):
errors.append({address:err.getErrorMessage()})
agent = Agent(reactor, connectTimeout=4)
for address in addresses:
client = agent.request(
'POST',
'http://%s:%d' % (address.strip(),21108),
Headers(),
StringProducer(command))
client.addCallback(cbRequest,address).addErrback(cbError,address)
client.addBoth(cbShutdown)
reactor.run()
return results,errors