2015-09-18 109 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

嗨,非常感謝。那麼假設給定任何文件是安全的,無論是文本還是圖像首先需要轉換爲二進制文件然後發送它? –

相關問題