Python 如何关闭对流式广播流url的请求?

Python 如何关闭对流式广播流url的请求?,python,python-2.7,python-requests,Python,Python 2.7,Python Requests,我在几个页面上搜索请求,发现了一个广播流的url。我基本上只想跳过它或执行某种超时,但请求并未结束: u = 'http://streaming.radionomy.com/Cheche-International-Radio' print 'started...', u r = requests.get(u, timeout=1, stream=False) 我以为设置stream=False就可以了,不是吗?我还尝试将标题['Connection']='close'设置为header,但这

我在几个页面上搜索请求,发现了一个广播流的url。我基本上只想跳过它或执行某种超时,但请求并未结束:

u = 'http://streaming.radionomy.com/Cheche-International-Radio'
print 'started...', u
r = requests.get(u, timeout=1, stream=False)
我以为设置stream=False就可以了,不是吗?我还尝试将标题['Connection']='close'设置为header,但这也不起作用。在这两种情况下,请求都不会关闭


谢谢

事实上,代码的行为符合预期,但参数可能并不代表您所期望的<代码>超时是服务器开始发送响应所需的时间限制,但您正在访问的服务器开始响应所需的时间并不长。。。但它发出了无限的回应<代码>流,另一方面,当设置为
(默认设置)时,等待整个内容下载完毕;同样,内容永远不会结束,因此调用将永远不会返回(并且可能会吃掉您的RAM)

我认为您需要的是使用
stream=False
发出请求,查看响应HTTP头,如果内容不是您要查找的内容,则放弃请求。例如,您可以查看
内容类型
;如果您只对
text/html
响应感兴趣,则以下代码将起作用:

u = 'http://streaming.radionomy.com/Cheche-International-Radio'
print 'started...', u
r = requests.get(u, stream=True)
content_type = r.headers['Content-Type']
if content_type.startswith('text/html'):
    content = r.content
    # process the content
else:
    print 'discarded ', u
当然,您可以选择过滤器来过滤具有其他条件的请求。例如,标题为:

{
    'Expires': 'Mon, 26 Jul 1997 05:00:00 GMT',
    'icy-br': '128, 128',
    'Pragma': 'no-cache',
    'icy-name': 'ChecheInternationalRadio',
    'ice-audio-info': 'bitrate=128;samplerate=44100;channels=2',
    'Cache-Control': 'no-cache',
    'icy-genre': 'medellin',
    'Content-Type': 'audio/mpeg',
    'icy-description': 'Esta es una Emisora suena solo Exitos Una selecta programacion musical con los mejores artistas y canciones de todos los tiempos. Transmitiendo desde medellin Colombia.',
    'icy-pub': '1',
    'Accept-Ranges': 'none',
    'icy-url': 'http://cheche-international-radio.playtheradio.com/',
    'Server': 'Icecast 2.3.3-kh8'
}

有些是标准的,有些是特殊的,选择对您更合适的。

我对contextlib有些了解