Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/362.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用Python Twisted使用Flask API进行异步文件上载?_Python_Asynchronous_Twisted_Python Requests_Grequests - Fatal编程技术网

使用Python Twisted使用Flask API进行异步文件上载?

使用Python Twisted使用Flask API进行异步文件上载?,python,asynchronous,twisted,python-requests,grequests,Python,Asynchronous,Twisted,Python Requests,Grequests,我目前有一个在本地机器上运行的python脚本,它通过调用我在远程机器上使用Flask构建的基本API上传一些文件。脚本基本上通过文件路径列表进行迭代,检查一些条件,并在满足条件时上载文件。为清晰起见,以下是脚本的精简版本: def upload_file(path): url = 'http://mydomain.com/upload' head,tail = os.path.split(path) files = {'files': (tail, open(path

我目前有一个在本地机器上运行的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并重新设计脚本。如果您对我是否应该走这条路线有任何建议/意见,我将不胜感激。提前谢谢。

除了“是的,您应该使用Twisted”之外,我不知道该给您什么答案。这真的很模糊。你试过用Twisted写吗?您遇到了什么问题?@Glyph我已将代码编辑为更像扭曲的实现。我还没有实现它,因为真正的代码需要一些重大的返工。只是想看看我是否走对了路。这个“示例代码”是否符合我描述的场景?好的,我继续测试了上面的代码,它确实可以按照我的需要工作。感谢您确认我的直觉,twisted是正确的解决方案。感谢您尝试。祝你好运如果您正在使用的twisted的唯一功能是deferToThread,那么您可以使用
多处理.ThreadPool
作为备选功能,例如:
用于mp.ThreadPool(20)中的状态。imap_无序(上载文件,路径):打印(“成功”如果状态==200,否则“错误”)
一次上载20个文件(同时)。