[英]Parallel file uploading via Browser using Python
以下代码以串行方式将多个文件从浏览器上载到主机。 为了使流程更快,如何并行处理文件,以便将多个流发送到服务器? 如果文件被发送到同一主机,这是否值得追求? 浏览器是否允许多个上传流到同一主机? 如果是这样,这怎么可能呢?
我假设不可能将文件分成几部分并将它们写成并行类似于此示例,因为它们是由浏览器而不是Python客户端提交的。
#!/usr/bin/python
import cgi, os
import shutil
import cgitb; cgitb.enable() # for troubleshooting
form = cgi.FieldStorage()
print """\
Content-Type: text/html\n
<html><body>
"""
if 'file' in form:
filefield = form['file']
if not isinstance(filefield, list):
filefield = [filefield]
for fileitem in filefield:
if fileitem.filename:
fn = os.path.basename(fileitem.filename)
# save file
with open('/var/www/site/files/' + fn, 'wb') as f:
shutil.copyfileobj(fileitem.file, f)
# line breaks are not occuring between interations
print 'File "' + fn + '" was uploaded successfully<br/>'
message = 'All files uploaded'
else:
message = 'No file was uploaded'
print """
<p>%s</p>
</body></html>
""" % (message)
表单提交会生成一个HTTP请求,该请求自然地使用单个TCP连接来传递请求。
要并行上传多个文件,可以并行生成多个请求。 您可能需要在客户端上使用flash或java applet。 检查javascript(AJAX)是否允许并发多个表单提交。
一般来说,提高绩效是一个有趣的主题。 关键是测量以找出瓶颈究竟是什么。
我想象瓶颈是加载上传文件的浏览器还是加载过程中的可用带宽(或两者兼而有之)。
如果瓶颈是从缓冲区保存文件(或将临时文件移动到最终位置),那么将for循环转换为线程可能会有所帮助 - 假设Web服务器具有写入所有这些文件的I / O容量。 但是线程只有在有大量文件要写的情况下才有用,否则工作重复生成线程(或加载队列并启动一组线程)比循环处理一些小文件要慢。
为了好玩,这里有一篇关于python线程和工作队列的文章: http : //www.ibm.com/developerworks/aix/library/au-threadingpython/
通过POST参考Python CGI和文件上传以及多个文件上传:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.