有没有办法在不下载Python中的url内容的情况下获取响应头?

sro*_*uex 1 python response request http-headers python-requests

我正在使用Python编写一个管理器,它会在某些条件下下载一些文件.问题是要对响应头执行条件.

以下示例是我现在正在做的简化版本.我首先下载该文件,然后测试其包含在标题中的名称是否在先前定义的列表中.

我想知道是否有办法在不下载内容的情况下获得响应,这在我的实际案例中需要花费大量时间.

import requests

# The line below download the file, but I'd like not to do it.
req = requests.get('http://some_url.com/some_file')

# Get the name of the file to test if it's the right file.
r = re.search(r'filename="(.*)";', req.headers['Content-Disposition'])

filename = None

# If the filename is present in the headers...
if r.groups():
    filename = r.groups()[0]

# If the filename is in an authorized list...
if filename in [...]:
   # Process req.content
Run Code Online (Sandbox Code Playgroud)

edd*_*iem 9

你可以用requests.head()而不是requests.get().

  • 注意:这将发送一个“HEAD”请求,该请求**应该**与“GET”请求相同,只是不返回正文。但这取决于服务器是否正确处理它;它*可以*为“HEAD”请求返回不同的标头。此外,如果您决定使用“GET”请求下载实际内容,这会产生*两个* HTTP 请求(但这不应该成为一个缺点)。 (3认同)