将HTTP头部(字符串)转换为Python字典

10 投票
7 回答
15090 浏览
提问于 2025-04-15 19:19

有没有一个标准的函数可以把HTTP头信息转换成Python字典?还有一个可以把字典转换回去的函数吗?

当然,这些函数需要支持头信息的折叠功能。

7 个回答

2

实现这个的最佳方法是使用一个HTTP请求转换器,比如这个:

你可以把请求复制为CURL格式,然后这个转换器会把它翻译成Python请求。

https://curl.trillworks.com/

顺便说一下,如果你不信这个链接,可以在谷歌上搜索“curl转换器”,它可能会出现在前几条结果中。 https://github.com/NickCarneiro/curlconverter

这里输入图片描述

如何将请求复制为CURL格式

这里输入图片描述

4

如果你找不到任何库来解决这个问题,这里有一个简单的、未经测试的解决方案:

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
5

与其自己动手用套接字等技术去构建,不如直接使用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-ranges', '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-modified', 'Mon, 15 Feb 2010 07:30:46 GMT'), ('etag', '"105800d-4194-47f9e9871d580"'), ('date', 'Mon, 15 Feb 2010 21:34:18 GMT'), ('content-type', 'text/html')]

而且它还有方法可以用来发送一个字典作为请求的一部分。

撰写回答