我正在尝试创建类似代理(在PYTHON中)下载并且我收到错误。我想强制用户下载文件,而是在屏幕上打印(二进制代码)。这是我的代码: 我正在做的是......从另一台服务器下载文件,同时尝试将此文件发送给客户端。 所以是这样的:REMOTE_SERVER - > MY_SERVER - > CLIENT,无需将文件保存在我的服务器中。有人能帮助我做错了吗?
myfile = session.get(r.headers['location'], stream = True)
print "Content-Type: application/zip\r\n"
print "Prama: no-cache\r\n"
print "Expires: 0\r\n"
print "Cache-Control: must-revalidate, post-check=0, pre-check=0\r\n"
print "Content-Type: application/octet-stream\r\n"
print "Content-Type: application/download\r\n"
print "Content-Disposition: attachment; filename=ternos.205.zip\r\n"
print "Content-Transfer-Encoding: binary\r\n"
print "Content-Length: 144303765\r\n"
#print "Accept-Ranges: bytes\r\n"
print ("\r\n\r\n")
#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()
似乎与标题无关,因为我已尝试过数百万个不同的标题..强制下载等等......但没有任何反应......
答案 0 :(得分:2)
print
已经在输出中包含换行符。请改用sys.stdout
,并仅写入一个 Content-Type
标头。在标题之后,只写一个更多\r\n
组合。
import sys
# ...
sys.stdout.write("Content-Type: application/zip\r\n")
sys.stdout.write("Prama: no-cache\r\n")
sys.stdout.write("Expires: 0\r\n")
sys.stdout.write("Cache-Control: must-revalidate, post-check=0, pre-check=0\r\n")
sys.stdout.write("Content-Type: application/octet-stream\r\n")
sys.stdout.write("Content-Disposition: attachment; filename=ternos.205.zip\r\n")
sys.stdout.write("Content-Transfer-Encoding: binary\r\n")
sys.stdout.write("Content-Length: 144303765\r\n")
sys.stdout.write("\r\n")
大多数CGI实现实际上会为您定期\n
转换为\r\n
,因此您可以只打印标题而无需添加分隔符:< / p>
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
传递给import shutil
shutil.copyfileobj(myfile.raw, sys.stdout)
:
stdout
我怀疑是否需要刷新,如果Python退出该点并且在关闭时刷新{{1}}。