I have an echo server running in localhost at port 9999. I am developing a web server using twisted ( I am new to twisted and python in general). The client will stream the data using chunked encoding with HTTP. What I want the server to do is to send this data to port 9999 and get the response from there and write back as http response. But I even can't make the sending part work. This is what i have done till now.
from twisted.web import server, resource from twisted.internet import reactor, endpoints from twisted.internet.protocol import Protocol, Factory class Clientp(Protocol): def __init__(self, req): self.req = req def connectionMade(self): self.transport.writeSequence(self.req.content.read()) def dataReceived(self,data): print ("+ got reply" + str(data)) # I have to send the data via resposne here class Counter(resource.Resource): isLeaf = True numberRequests = 0 def render_POST(self, request): def clientProtocol(): return Clientp(request) endpoint = endpoints.TCP4ClientEndpoint(reactor, "127.0.0.1", 9999) endpoint.connect(Factory.forProtocol(clientProtocol)) return server.NOT_DONE_YET endpoints.serverFromString(reactor, "tcp:8000").listen(server.Site(Counter())) reactor.run()
I can't write the post content (request.content.read()
) to the TCP endpoint. I'm getting TypeError("Data must be bytes")
error. Any thoughts
def connectionMade(self): self.transport.writeSequence(self.req.content.read())
ITransport.writeSequence accepts an iterable of bytes. IRequest.content.read returns a bytes object.
You get the error TypeError("Data must be bytes")
because iterating over bytes in Python 3 results in integers. It is these integers that the implementation is complaining about.
You should just use ITransport.write, instead.