Существует ли стандартная функция, которая преобразует http заголовки в словарь Python, и один для преобразования назад?
Они должны были бы поддерживать сворачивание заголовка, конечно.
Вместо того, чтобы создавать свои собственные сокеты и т. Д., Я бы использовал httplib Таким образом можно было бы получить данные с http-сервера и проанализировать заголовки в словаре например
import httplib
conn = httplib.HTTPConnection("www.python.org")
conn.request("GET", "/index.html")
r1 = conn.getresponse()
dict = r1.getheaders()
print(dict)
дает
[('content-length', '16788'), ('accept-range', 'bytes '), (' server ',' Apache / 2.2.9 (Debian) DAV / 2 SVN / 1.5.1 mod_ssl / 2.2.9 OpenSSL / 0.9.8g mod_wsgi / 2.5 Python / 2.5.2 '), (' last- изменено ',' Пн, 15 февраля 2010 г. 07:30:46 GMT '), (' etag ',' "105800d-4194-47f9e9871d580" '), (' date ',' Пн, 15 февраля 2010 г. 21:34:18 GMT '), (' content-type ',' text / html ')]
и методы put для отправки словаря как части запроса.
Я не совсем уверен, но это похоже на то, что вы ищете
Надеюсь, это поможет
Если вы не найдете ни одной библиотеки, решающей эту проблему, вот наивное, непроверенное решение:
def fold(header):
line = "%s: %s" % (header[0], header[1])
if len(line) < 998:
return line
else: #fold
lines = [line]
while len(lines[-1]) > 998:
split_this = lines[-1]
#find last space in longest chunk admissible
split_here = split_this[:998].rfind(" ")
del lines[-1]
lines = lines + [split_this[:split_here]),
split_this[split_here:])] #this may still be too long
#hence the while on lines[-1]
return "\n".join(lines)
def dict2header(data):
return "\n".join((fold(header) for header in data.items()))
def header2dict(data):
data = data.replace("\n ", " ").splitlines()
headers = {}
for line in data:
split_here = line.find(":")
headers[line[:split_here]] = line[split_here:]
return headers