我正在尝试创建类似代理(在PYTHON中)的东西来下载,但出现错误。我想强制用户下载文件,而是在屏幕上打印(二进制代码)。这是我的代码:我正在做的是...从另一台服务器下载文件,同时尝试将此文件发送到客户端。像这样的事情是这样的:REMOTE_SERVER -> MY_SERVER -> CLIENT,而无需将文件保存在我的服务器中。有人可以帮助我做错什么吗?
myfile = session.get(r.headers['location'], stream = True)
print "Content-Type: application/ziprn"
print "Prama: no-cachern"
print "Expires: 0rn"
print "Cache-Control: must-revalidate, post-check=0, pre-check=0rn"
print "Content-Type: application/octet-streamrn"
print "Content-Type: application/downloadrn"
print "Content-Disposition: attachment; filename=ternos.205.ziprn"
print "Content-Transfer-Encoding: binaryrn"
print "Content-Length: 144303765rn"
#print "Accept-Ranges: bytesrn"
print ("rnrn")
#with open('suits.zip', 'wb') as f:
for chunk in myfile.iter_content(chunk_size=1024):
if chunk:
sys.stdout.write(chunk)
sys.stdout.flush()
似乎这与标题无关,因为我已经尝试了数百万个不同的标题..强制下载等... 但没有任何反应..
print
已经在输出中包含换行符。请改用sys.stdout
,并且只写入一个Content-Type
标头。在标题之后,只再写一个rn
组合。
import sys
# ...
sys.stdout.write("Content-Type: application/ziprn")
sys.stdout.write("Prama: no-cachern")
sys.stdout.write("Expires: 0rn")
sys.stdout.write("Cache-Control: must-revalidate, post-check=0, pre-check=0rn")
sys.stdout.write("Content-Type: application/octet-streamrn")
sys.stdout.write("Content-Disposition: attachment; filename=ternos.205.ziprn")
sys.stdout.write("Content-Transfer-Encoding: binaryrn")
sys.stdout.write("Content-Length: 144303765rn")
sys.stdout.write("rn")
大多数CGI实现实际上会将常规n
转换为rn
,因此您可以只打印标题而无需添加分隔符:
print "Content-Type: application/zip"
print "Prama: no-cache"
print "Expires: 0"
print "Cache-Control: must-revalidate, post-check=0, pre-check=0"
print "Content-Type: application/octet-stream"
print "Content-Disposition: attachment; filename=ternos.205.zip"
print "Content-Transfer-Encoding: binary"
print "Content-Length: 144303765"
print
然后流式传输代理请求,我将使用 .raw
文件对象并将其传递给 sys.stdout
shutil.copyfileobj
:
import shutil
shutil.copyfileobj(myfile.raw, sys.stdout)
我怀疑是否需要刷新,而不是如果 Python 在那时退出并在关闭时刷新stdout
。