Generate headers in Twisted client
i'm using the Twisted web "HTTPClient" protocol to dialogue with a http server (using twisted app as a client), the problem is that most of my request do not accept my header. Is there some sort of way (maybe using certain libraries) to generate header?? I'll post 开发者_开发技巧some code so you can have a look
class Local(HTTPClient):
def generateHeaders(self, type=None):
self.sendHeader('User-Agent', 'Twisted Web Client')
if type:
self.sendHeader('Content-Type', 'x-www-form-urlencoded')
self.sendHeader('Accept', '*/*')
self.sendHeader('Host', 'localhost')
self.endHeaders()
def connectionMade(self):
## GENERATE ID
self.userid= self.generateID()
self.sendCommand('POST', '/chat/action=join&user=pirosb3')
self.generateHeaders(type=True)
def dataReceived(self, data):
print data
As you can see, i created a method that generates header for me, but not very efficient i must say, i always get error responses.
Anyone know a solution?
Thanks
I would definitely recommend you to use Twisted's Agent
class along with the Header
class in the twisted.web.http_headers
module.
There is a nice guide available here.
If you need a real life example of a Twisted HTTP client which adds some headers to the request and can read the ones of the answer, here it is:
from pprint import pformat
from twisted.internet import reactor
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
class BeginningPrinter(Protocol):
def __init__(self, finished):
self.finished = finished
self.remaining = 1024 * 10
def dataReceived(self, bytes):
if self.remaining:
display = bytes[:self.remaining]
print 'Some data received:'
print display
self.remaining -= len(display)
def connectionLost(self, reason):
print 'Finished receiving body:', reason.getErrorMessage()
self.finished.callback(None)
agent = Agent(reactor)
d = agent.request(
'GET',
'http://example.com/',
Headers({'User-Agent': ['Twisted Web Client Example']}),
None)
def cbRequest(response):
print 'Response version:', response.version
print 'Response code:', response.code
print 'Response phrase:', response.phrase
print 'Response headers:'
print pformat(list(response.headers.getAllRawHeaders()))
finished = Deferred()
response.deliverBody(BeginningPrinter(finished))
return finished
d.addCallback(cbRequest)
def cbShutdown(ignored):
reactor.stop()
d.addBoth(cbShutdown)
reactor.run()
精彩评论