2

我目前有一个在我的本地机器上运行的 python 脚本,它通过调用我使用远程机器上的 Flask 构建的基本 API 来上传一些文件。该脚本基本上遍历文件路径列表,检查某些条件并在文件符合条件时上传文件。为了清楚起见,这里是脚本的精简版本:

def upload_file(path):

    url = 'http://mydomain.com/upload'
    head,tail = os.path.split(path)
    files = {'files': (tail, open(path, 'rb'))}
    r = requests.post(url,files=files) 
    return r.status_code


def uploadCallback(status):
    if status == 200:
        print "file was successfully uploaded, now do something cool"
    else:
        print "something went wrong"

paths = ['/Users/myFiles/file1.txt', '/Users/myFiles/file2.txt']

meets_criteria = True

for path in paths:
    if meets_criteria: #imagine we check to see if its extension is .txt
        d = threads.deferToThread(upload_file, path)
        d.addCallback(uploadCallback)
    else:
        pass

reactor.run()

问题是该脚本在检测到其他文件时阻止了它们的上传。它们最终都会上传,但我需要异步发送每个文件,但不能同时发送。我研究了 grequests、requests-futures、asyncore、Twisted 等。Twisted 看起来是最好的选择,但需要我学习 Twisted 并重新设计脚本。关于这是否是我应该走的路线的任何提示/意见将不胜感激。提前致谢。

4

0 回答 0