Ho creato un semplice server http con Twisted, che invia l'intestazione Content-Type: multipart/x-mixed-replace. Lo sto usando per testare un client http che voglio configurare per accettare un flusso a lungo termine.Utilizzando le classi twisted.web di Twisted, come faccio a svuotare i miei buffer in uscita?
Il problema che è sorto è che la mia richiesta del client si blocca fino a quando il self.finish http.Request chiamate(), poi riceve tutti i documenti più parti in una sola volta.
C'è un modo per svuotare manualmente i buffer di uscita verso il client? Suppongo che questo sia il motivo per cui non sto ricevendo i singoli documenti multipart.
#!/usr/bin/env python
import time
from twisted.web import http
from twisted.internet import protocol
class StreamHandler(http.Request):
BOUNDARY = 'BOUNDARY'
def writeBoundary(self):
self.write("--%s\n" % (self.BOUNDARY))
def writeStop(self):
self.write("--%s--\n" % (self.BOUNDARY))
def process(self):
self.setHeader('Connection', 'Keep-Alive')
self.setHeader('Content-Type', "multipart/x-mixed-replace;boundary=%s" % (self.BOUNDARY))
self.writeBoundary()
self.write("Content-Type: text/html\n")
s = "<html>foo</html>\n"
self.write("Content-Length: %s\n\n" % (len(s)))
self.write(s)
self.writeBoundary()
time.sleep(2)
self.write("Content-Type: text/html\n")
s = "<html>bar</html>\n"
self.write("Content-Length: %s\n\n" % (len(s)))
self.write(s)
self.writeBoundary()
time.sleep(2)
self.write("Content-Type: text/html\n")
s = "<html>baz</html>\n"
self.write("Content-Length: %s\n\n" % (len(s)))
self.write(s)
self.writeStop()
self.finish()
class StreamProtocol(http.HTTPChannel):
requestFactory = StreamHandler
class StreamFactory(http.HTTPFactory):
protocol = StreamProtocol
if __name__ == '__main__':
from twisted.internet import reactor
reactor.listenTCP(8800, StreamFactory())
reactor.run()
Ciò consente effettivamente l'esecuzione di qualsiasi altro codice (come selezionato dal reattore) al momento della resa? In tal caso, dovrai stare molto attento che i dati che stai utilizzando non vengano sovrascritti o alterati dall'altro codice. Vedi il commento all'URL sotto il quale non ho visto confutato da nessuna parte: http://twistedmatrix.com/pipermail/twisted-python/2007-February/014869.html – Mick