2011-03-21 44 views
2

我正在研究一個庫,它涉及到urllib2.Request實例的預處理(使用urllib2.BaseHandler.xxx_request回調)。某些預處理器需要檢查提供的urllib2.Request實例中包含的頭文件。Python urllib2.Request.get_header文檔?

我注意到官方的Python文檔只列出了添加標題和檢查標題是否存在的方法。有一個未公開的urllib2.Request.get_header方法,雖然它似乎有一些怪癖。例如,它改變多字頭的情況下:

from urllib2 import Request 
req = Request('http://www.example.com') 
req.add_header('Content-Type', 'application/x-www-form-urlencoded') 

req.get_header('Content-Type') # Produces nothing 
req.get_header('Content-type') # Produces 'application/x-www-form-urlencoded' 

是get_header正式支持和/或任何相關文檔?如果沒有,是否有從urllib2.Request實例讀取標題值的最佳做法?

回答

4

我確定get_header已經官方支持,但我在文檔中找不到它。

至於你的「get_header返回無」的問題,看着源urllib2.py,該add_header方法節省了頭鍵值對,這就是爲什麼get_header('Content-type')工程和其他變體沒有收到主叫key.capitalize()

class Request: 
    def add_header(self, key, val): 
     self.headers[key.capitalize()] = val 

>>> 'content-type'.capitalize() 
'Content-type' 
+0

啊,謝謝。奇怪的是,大小寫不區分大小寫,因此大小寫被修改。 – 2011-03-22 04:59:59

+1

同意,我期望看到key.lower()或正常化爲'內容類型'(以匹配HTTP RFC),但key.capitalize()有點令人驚訝。 – samplebias 2011-03-22 16:25:50