0

我正在尝试创建类似代理(在 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()

似乎标题无关紧要,因为我已经尝试了数百万个不同的标题..强制下载等...但没有任何反应..

4

1 回答 1

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因此您可以只打印标题而不添加分隔符:

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.stdoutwith shutil.copyfileobj

import shutil

shutil.copyfileobj(myfile.raw, sys.stdout)

我怀疑是否需要刷新,而不是如果 Python 在那时退出并stdout在关闭时刷新。

于 2013-09-21T12:49:03.047 回答