2015-09-18 62 views
2

我有一个文件,我正在阅读它,如下所示。 [忽略所有的连接相关参数]无法发送文件内容以及python中的http标头

somefile=open(/path/to/some/file,'rb') 
READ_somefile=somefile.read() 
somefile.close() 
client_connection.send((str.encode('HTTP/1.1 200 OK\nContent-Type: image/png\n\n'))) 
client_connection.send((READ_somefile)) 

我能够正确显示我的Html网页,当我用上面的代码。 但我想只使用一个发送而不是两个,这就产生了问题。 我尝试使用以下内容

client_connection.send((str.encode('HTTP/1.1 200 OK\nContent-Type: image/png\n\n',READ_somefile))) 

我得到下面的错误。

client_connection.send((str.encode('HTTP/1.1 200 OK\nContent-Type: image/png\n\n',READ_somefile))) 
TypeError: encode() argument 1 must be str, not bytes 

然后我试着用这个。

client_connection.send((str.encode('HTTP/1.1 200 OK\nContent-Type: image/png\n\n',str(READ_somefile)))) 

我收到以下错误消息。

client_connection.send((str.encode('HTTP/1.1 200 OK\nContent-Type: image/png\n\n',str(READ_somefile)))) 
LookupError: unknown encoding: b'/*! 

您能否让我知道我应该在这里使用什么样的编码来发送标题和内容?

请注意,我不能使用任何外部模块。

+0

我猜你”重新尝试使用纯Python发送一个网页?你没有像烧瓶一样使用Web框架?乐于帮助,只是寻找更多的信息。干杯! –

+0

嗨是的,我使用Python创建一个简单的Web服务器,然后发送一个网页。没有使用外部模块或框架。 –

+0

一切工作正常,但我无法找出正确的编码和解码。 –

回答

0

签名是socket.send(bytes[, flags]) - 所以

  1. 你想传递一个字节的字符串
  2. 你想要把它作为一个参数

什么你是

  1. 标题'HTTP/1.1 200 OK\nContent-Type: image/png\n\n'它当前是一个Unicode字符串,所以需要编码为字节str荷兰国际集团
  2. 主体(图像的二进制数据),这已经是一个字节的字符串,所以不需要进行编码

显而易见的解决办法是:

with open(/path/to/some/file,'rb') as somefile: 
    body = somefile.read() 
header = 'HTTP/1.1 200 OK\nContent-Type: image/png\n\n'.encode() 
payload = header + body 
client_connection.send(payload) 
+0

嗨,非常感谢。那么假设给定任何文件是安全的,无论是文本还是图像首先需要转换为二进制文件然后发送它? –

相关问题