python-requests:获取响应内容的头部而不全部消耗

标签 python http unicode python-requests

使用 python-requests 和 python-magic,我想测试 web 资源的 mime 类型而不获取其所有内容(特别是如果该资源恰好是 ogg 文件或 PDF 文件)。根据结果​​,我可能会决定全部获取。但是,在测试 mime 类型后调用 text 方法只会返回尚未使用的内容。如何在不使用响应内容的情况下测试 mime 类型?

下面是我当前的代码。

import requests
import magic


r = requests.get("http://www.december.com/html/demo/hello.html", prefetch=False)
mime = magic.from_buffer(r.iter_content(256).next(), mime=True)

if mime == "text/html":
    print(r.text)  # I'd like r.text to give me the entire response content

谢谢!

最佳答案

如果 'content-type' 足够,您可以发出 HTTP 'Head' 请求而不是 'Get',只接收 HTTP header 。

import requests

url = 'http://www.december.com/html/demo/hello.html'
response = requests.head(url)
print response.headers['content-type']

关于python-requests:获取响应内容的头部而不全部消耗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13197854/

相关文章:

javascript - Firefox 中保存的密码发送空字段

json - Angular 如何检查 HttpRequest 对象以为 header 设置正确的内容类型?

HTTP 应用程序通过 PPTP 连接挂起

python-3.x - 在 Python3 中读取 UTF-8 编码文件和文本文件

python - re.findall 行为怪异

Python:两个变量什么时候指向内存中的同一个对象?

windows - Windows 中的 i18n shell

java - Java中的unicode换行符(\u000d)

python - cvxpy :'sum_entries' 未定义

python - Vim 使用 python 递归定义突出显示