在python中将.gz文件发送到套接字

时间:2012-09-12 08:32:07

标签: python http sockets binary

我有一个文件,我使用gzip模块压缩,接下来要做的就是将该文件发送到连接到Web浏览器的套接字。我知道我必须将Http响应内容类型更改为application / gzip,但是如何实际发送gzip的二进制文件以便浏览器正确下载?

这是我到目前为止所得到的

f_out = gzip.open('downloads.gz', 'wb')
f_in = open('file.txt', 'rb')
f_out.writelines(f_in)
f_in.close()
f_out.close()
#This all works
.....
def make_http_response(self, content, html_type='text/html'):
        response_headers = {
            'Content-Type': html_type+'; encoding=utf8',
            'Content-Length': len(content),
            'Connection': 'close',
        }
        response_headers_string = ''.join('%s: %s\n' % (k, v) for k, v in   response_headers.iteritems())
        response_proto = 'HTTP/1.1'
        if(self.error):
            response_status = '404'
            response_status_text = 'Not Found' 
        else:
            response_status = '200'
            response_status_text = 'OK '
        response = '%s %s %s' %(response_proto, response_status, response_status_text)
        response = response + response_headers_string + '\n' + str(content)
        return response   

我为html_type字段传递'application / gz'

问题是我传递的内容我有一个download.gz文件,我刚刚在同一目录中创建了如何将二进制文件发送到make http响应函数? 感谢

1 个答案:

答案 0 :(得分:1)

只需将文件的二进制原始数据放在邮件正文中,无需任何修改。

相关问题