前言
HTTP请求是指客户端向服务器发送请求的消息格式。它包括:请求行(HTTP方法、请求URL、HTTP协议版本号)、请求头部、请求数据三个部分。客户端向服务器发送HTTP请求后,服务器会依据请求消息的内容进行相应的处理并回送HTTP响应消息给客户端。
协程是一种轻量级的线程,与线程不同的是,协程由程序进行调度,并且在执行中可以被挂起和恢复。这种机制可以充分利用 CPU 时间,提高程序的运行效率,特别是在 I/O 操作密集型的程序中表现更加明显。通过将程序的流程切换到协程中,可以避免线程上下文切换的开销,从而提高程序的响应速度。
一、httpx
1.httpx是什么
HTTPX 是适用于 Python 3 的全功能型 HTTP 客户端库。它包括一个集成的 命令行客户端,同时支持 HTTP/1.1 和 HTTP/2,并提供同步 和异步 API。
httpx 是一个几乎继承了所有 requests 的特性并且支持 “异步” http 请求的开源库。
httpx的源码网址:https://github.com/encode/httpx
httpx的文档网址:https://www.python-httpx.org/
2.安卓包
pip install httpx
pip install httpx[http2]
注意:HTTPX 需要 Python 3.7+
3.同步http请求
import asyncio
import httpx
import threading
import time
def sync_main(url, sign):
response = httpx.get(url).status_code
print(f'sync_main: {
threading.current_thread()}: {
sign}: {
response}')
sync_start = time.time()
[sync_main(url='http://www.baidu.com', sign=i) for i in range(200)]
sync_end = time.time()
print(sync_end - sync_start)
可以看到在 sync_main 中则实现了同步 http 访问百度 200 次
4.异步http请求
import asyncio
import httpx
import threading
import time
client = httpx.AsyncClient()
async def async_main(url, sign):
response = await client.get(url)
status_code = response.status_code
print(f'async_main: {
threading.current_thread()}: {
sign}:{
status_code}')
loop = asyncio.get_event_loop()
tasks = [async_main(url='http://www.baidu.com', sign=i) for i in range(200)]
async_start = time.time()
loop.run_until_complete(asyncio.wait(tasks))
async_end = time.time()
loop.close()
print(async_end - async_start)
可以看到顺序虽然是乱的,但是主线程并没有切换 (协程本质还是单线程 )。