gpt4 book ai didi

python - 扭曲的链接回调在一起不传递数据

转载 作者:太空宇宙 更新时间:2023-11-03 19:15:10 25 4
gpt4 key购买 nike

我将多个延迟链接在一起,因为在开始下一个函数之前我需要一个函数的结果。但是,代码在第一次成功回调后中断。

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 中的延迟递归循环对于其正常运行是必要的,但它不会将任何结果传递给 future 的回调,这就是为什么 addBarcodeChain 在尝试使用结果内容时失败。

如何调整 cbRequestSaveContents 将响应对象转发给 future 的回调?

最佳答案

我明白了。正如我怀疑的那样,相关位是保存内容类。

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 方法,响应将传递给 future 的回调。

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 的问题。

关于python - 扭曲的链接回调在一起不传递数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11564620/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com