Search code examples
pythontwistedtwisted.web

twisted , return custom message to client after receiving request from client


I have Written a simple code of http server and http client, i am able to successfully send messages to server in form of xml from client. here's my code.

client.py

from StringIO import StringIO
from twisted.internet import reactor
from twisted.web.client import Agent
from twisted.web.http_headers import Headers

from twisted.web.client import FileBodyProducer
from xml_dict import bm_xml

xml_str = bm_xml()
agent = Agent(reactor)
body = FileBodyProducer(StringIO(xml_str))

d = agent.request(
   'GET',
   'http://localhost:8080/',
    Headers({'User-Agent': ['Replication'],
            'Content-Type': ['text/x-greeting']}),
    body)

def cbResponse(response):
    print response.version
d.addCallback(cbResponse)

def cbShutdown(ignored):
   reactor.stop()
d.addBoth(cbShutdown)

reactor.run()

server.py

from twisted.web import server, resource
from twisted.internet import reactor

def parse_xml(xml_str):
  print xml_str
  response = "xml_to_client"
  return response



class Simple(resource.Resource):
     isLeaf = True
     def render_GET(self, request):
        xml_request_str = request.content.read()
        response = parse_xml(xml_request_str)
        print response

 site = server.Site(Simple())
 reactor.listenTCP(8080, site) 
 reactor.run()

what i am trying to do here is from client i am sending an xml string to server, xml is generated from bm_xml module which is another file. this xml is successfully read to server, now once once server receives the xml, i need to parse this xml and return another xml string. i have the code to parse xml and construct another xml so that client receives this xml from server, but i do not know how to send the message to client from server. where all the changes would the required , in server or client ? i am assuming cbresponse is the one where changes has to be done in client , but i have no idea where the change should be done in server side. In server response variable is the one which i need to send to client.


Solution

  • You code appears to already do what you are asking. Simple.render_GET returns response. response is what is sent to the client. Perhaps you're unsure how to get the response after it has been sent to the client? If so, the answer may be readBody (more docs).