有没有办法在不下载 Python 中的 url 内容的情况下获得响应 headers?
Is there a way to get response headers without download the url content in Python?
我正在使用 Python 编写一个管理器,该管理器将在特定条件下下载一些文件。问题是要针对响应 headers 执行条件。
下面的例子是我现在所做的一个简化版本。我首先下载该文件,然后测试其名称(包含在 headers 中)是否在先前定义的列表中。
我想知道是否有一种方法可以在不下载内容的情况下获得响应,在我的实际情况下这会花费大量时间。
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
您可以使用 requests.head()
代替 requests.get()
。
我正在使用 Python 编写一个管理器,该管理器将在特定条件下下载一些文件。问题是要针对响应 headers 执行条件。
下面的例子是我现在所做的一个简化版本。我首先下载该文件,然后测试其名称(包含在 headers 中)是否在先前定义的列表中。
我想知道是否有一种方法可以在不下载内容的情况下获得响应,在我的实际情况下这会花费大量时间。
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
您可以使用 requests.head()
代替 requests.get()
。