简体   繁体   English

Twisted中单个请求的多个响应

[英]Multiple response for a single request in Twisted

I wanted to be able to receive multiple response from a server after sending one single request. 我想在发送一个请求后能够从服务器接收多个响应。 This is implemented all in twisted. 这是全部扭曲的。 The Server: 服务器:

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

And the Client: 而客户:

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())

Basically what I want is that the server not to close the connection (request.finish()), but instead to continue sending responses; 基本上我想要的是服务器不要关闭连接(request.finish()),而是继续发送响应; and the client should be able to receive those messages. 并且客户端应该能够接收这些消息。

HTTP does not work this way. HTTP无法以这种方式工作。 An HTTP request has exactly one response. HTTP请求只有一个响应。 Twisted Web will not let you send more than one response, because that would be against the HTTP specification and no HTTP clients would be able to figure out what was going on. Twisted Web不允许您发送多个响应,因为这将违反HTTP规范,并且没有HTTP客户端能够弄清楚发生了什么。

There may be another way to accomplish your underlying goals, but whatever it is, it won't involve sending more than one HTTP response to a single HTTP request. 可能有另一种方法来实现您的基本目标,但不管它是什么,它都不会涉及向单个HTTP请求发送多个HTTP响应。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM