2012-07-19 59 views
1

我一起鏈接幾個延遲,因爲我需要從一個函數的結果,然後我開始下一個。但是,代碼在第一次成功回調後中斷。扭曲的鏈接回調在一起不傳遞數據

class SaveContents(Protocol): 
    def __init__(self, finished, filesize, filename): 
     self.finished = finished 
     self.remaining = filesize 
     self.outfile = open(filename, 'wb') 

    def dataReceived(self, bytes): 
     if self.remaining: 
      display = bytes[:self.remaining] 
      self.outfile.write(display) 
      self.remaining -= len(display) 
     else: 
      self.outfile.close() 

    def connectionLost(self, reason): 
     print 'Finished receiving body:', reason.getErrorMessage() 
     self.outfile.close() 
     self.finished.callback(None) 

def cbRequest(response): 
    print 'Response version:', response.version 
    print 'Response code:', response.code 
    print 'Response phrase:', response.phrase 
    print 'Response headers:' 
    print 'Response length:', response.length 
    print pformat(list(response.headers.getAllRawHeaders())) 
    finished = Deferred() 
    response.deliverBody(SaveContents(finished, response.length, 'test2.pdf')) 
    return finished 

def cbShutdown(ignored): 
    reactor.stop() 

def addBarcodeChain(result, infile, outfile, analyze, duplex): 
    print "starting Chain with results {0}".format(result) 
    d = addBarcode(infile, outfile, lastStatement=result.headers.getHeader('lastStatement'), analyze=analyze, duplex=duplex) 
    return d 

def addBarcode(infile, outfile, **kwargs): 
    """Send the pdf file to the remote server for processing, then save the results.""" 
    agent = Agent(reactor) 
    f = open('70935.pdf', 'rb') 
    body = FileBodyProducer(f) 
    fstr = 'filename={0}'.format(infile) 
    stmnt = 'lastStatement={0}'.format(kwargs['lastStatement']) 
    duplex = 'duplex={0}'.format(int(kwargs['duplex'])) 
    analyze = 'analyze={0}'.format(int(kwargs['analyze'])) 
    options = '&'.join([fstr, stmnt, duplex, analyze]) 
    d = agent.request(
     'POST', 
     'http://127.0.0.1:7777?{0}'.format(options), 
     Headers({'User-Agent': ['Twisted Web Client Example'], 
       'Content-Type': ['multipart/form-data; boundary=1024'.format()]}), 
     body) 
    return d 

#=============================================== 
# Main methods 
#=============================================== 
def main(infiles, output_path, output_filename, analyze, duplex, debug): 
    logger.info("Start of processing {0}".format(infiles)) 
    if debug: 
     logger.setLevel(logging.DEBUG) 

    lastStatement = 0 
    work = [] 
    for globFile in infiles: 
     for f in glob(globFile): 
      outname = '{0}/{1}{2}.pdf'.format(output_path, os.path.splitext(os.path.basename(f))[0], output_filename) 
      work.append((f, outname)) 

    d = addBarcode(work[0][0], work[0][1], lastStatement=lastStatement, analyze=analyze, duplex=duplex) 
    d.addCallback(cbRequest) 
    d.addErrback(cbShutdown) 
    for f, outname in work[1:]: 
     d.addCallback(addBarcodeChain, f, outname, analyze=analyze, duplex=duplex) 
     d.addCallback(cbRequest) 
     d.addErrback(cbShutdown) 

    d.addCallback(cbShutdown) 
    d.addErrback(cbShutdown) 

    reactor.run() 

儘可能靠近我可以計算,在cbRequest遞延遞歸循環需要它才能正常工作,但是當它試圖將不會傳遞給未來回調的結果,這就是爲什麼addBarcodeChain失敗使用結果內容。

我該如何調整cbRequestSaveContents以將響應對象傳遞給將來的回調?

+0

它如何「打破」?提供完整的細節。 – Marcin 2012-07-19 15:54:32

+0

@ addBarcodeChain被調用時@Marcin的結果是None。 – 2012-07-19 16:03:18

+0

請描述你的輸入。 http://sscce.org/ – Marcin 2012-07-19 16:08:37

回答

1

我想通了。正如我懷疑的那樣,相關位是保存內容類。

class SaveContents(Protocol): 
    def __init__(self, finished, filesize, filename): 
     self.finished = finished 
     self.remaining = filesize 
     self.outfile = open(filename, 'wb') 

    def dataReceived(self, bytes): 
     if self.remaining: 
      display = bytes[:self.remaining] 
      self.outfile.write(display) 
      self.remaining -= len(display) 
     else: 
      self.outfile.close() 

    def connectionLost(self, reason): 
     print 'Finished receiving body:', reason.getErrorMessage() 
     self.outfile.close() 
     self.finished.callback(None) 

值得注意的是,當連接關閉時,connectionLost方法被調用。當發生這種情況時,它應該通過設置self.finished.callback(None)來「清除」遞歸回調循環。

通過將其更改爲self.finished.callback(self.response)並將響應傳遞給init方法,將響應傳遞給將來的回調。

class SaveContents(Protocol): 
    def __init__(self, finished, response, filesize, filename): 
     self.finished = finished 
     self.remaining = filesize 
     self.response = response 
     self.outfile = open(filename, 'wb') 

    def dataReceived(self, bytes): 
     if self.remaining: 
      display = bytes[:self.remaining] 
      self.outfile.write(display) 
      self.remaining -= len(display) 
     else: 
      self.outfile.close() 

    def connectionLost(self, reason): 
     print 'Finished receiving body:', reason.getErrorMessage() 
     self.outfile.close() 
     self.finished.callback(self.response) 

這解決了以後回調從他們的前輩得到None的問題。