HTTP长连接---requests的长连接

使用HTTP协议时,为了充分利用资源,经常会用到http的长连接,也就是底层tcp连接的复用。
在requests库中,HTTP的长连接是通过Session会话实现的。

会话对象让你能够跨请求保持某些参数。它也会在同一个 Session 实例发出的所有请求之间保持 cookie, 期间使用 urllib3 的 connection pooling 功能。所以如果你向同一主机发送多个请求,底层的 TCP 连接将会被重用,从而带来显著的性能提升。

HTTP persistent connection, also called HTTP keep-alive, or HTTP connection reuse, is the idea of using a single TCP connection to send and receive multiple HTTP requests/responses, as opposed to opening a new connection for every single request/response pair. The newer HTTP/2 protocol uses the same idea and takes it further to allow multiple concurrent requests/responses to be multiplexed over a single connection.

下面举例说明,如何使用requests的Session:

#!/usr/bin/python
# -*- coding: utf-8 -*-


import requests
import time

url="http://172.20.29.116:5140"

payload=[{'mesg': 'one'},{'mesg':'two'}]

s = requests.Session()
r = s.post(url, data=payload)
print r.headers
print r.status_code
print r.content

while True:
    time.sleep(10)
$ netstat -anp | grep 5140
.....   ....    ... ...5140     ESTABLISHED

使用Session发送HTTP请求后,可以看到,连接依然是ESTABLISHED。
而不使用Session的情况,则是发送HTTP请求后,连接即断开。下次发送请求又要重新建立连接。

注意

要使用长连接,需注意,只有所有的响应体数据被读取完毕连接才会被释放为连接池;所以确保将 stream 设置为 False 或读取 Response 对象的 content 属性。
所谓stream,是指响应体内容工作流,默认情况下,当你进行网络请求后,响应体会立即被下载。可以通过设置stream为False,推迟下载响应体直到访问Response.content。

默认情况下, stream是False。使用长连接时,默认即可。

另外,长连接是需要server端支持的,如果server端不支持(例如django server本身是不支持的,每次接收request,处理完成后,就断开连接),则client设置了也是没有用的。

参考:

http://docs.python-requests.org/zh_CN/latest/user/advanced.html
https://en.wikipedia.org/wiki/HTTP_persistent_connection

你可能感兴趣的:(python,http协议,session,requests)