Twisted中单个请求的多个响应

时间:2012-08-07 14:36:46

标签: json twisted urllib2 multiple-results

我希望能够在发送一个请求后从服务器接收多个响应。这是全部扭曲的。  服务器:

class HandleReq(resource.Resource):
    def __init__(self):
        resource.Resource.__init__(self)

    def render_GET(self, request):
        """
          Here I basically connect to another server and get multiple
          responses"""
         d = defer.Deferred()
         interface = RemoteService(request, i_deferred)
         self._connect_to_RemoteService(bf_command, interface)
         self.handleCallbacks(i_deferred, request)
         return server.NOT_DONE_YET

    def render_POST(self, request):
        '''to make sure both GET/POST are handled'''
        return self.render_GET(request)

    def handleCallbacks(self, d, req):
        msg = d.addCallback(self.getEvent)
        d.addCallback(self.postResponse(req, msg))
        return None

    def getEvent(self, msg):
        return msg

    def postResponse(self, request, response):
        def post(event):
            request.setHeader('Content-Type', 'application/json')
            request.write(response)
            request.finish()
            self.postResponse(request, response)
            return server.NOT_DONE_YET
      return post

客户:

from urllib2 import URLError, HTTPError
api_req = 'http://localhost:8000/req' + '?' + urllib.urlencode({"request": request})
req = urllib2.Request(api_req)
try:
    response = urllib2.urlopen(api_req)

except HTTPError, e:
            print 'Problem with the request'
            print 'Error code: ', e.code
except URLError, e:
            print 'Reason: ', e.reason
else:
     j_response = json.loads(response.read())

基本上我想要的是服务器不要关闭连接(request.finish()),而是继续发送响应;并且客户端应该能够接收这些消息。

1 个答案:

答案 0 :(得分:3)

HTTP不能以这种方式工作。 HTTP请求只有一个响应。 Twisted Web不允许您发送多个响应,因为这将违反HTTP规范,并且没有HTTP客户端能够弄清楚发生了什么。

可能有另一种方法可以实现您的基本目标,但无论如何,它都不会涉及向单个HTTP请求发送多个HTTP响应。