Home | 简体中文 | 繁体中文 | 杂文 | Github | 知乎专栏 | 51CTO学院 | CSDN程序员研修院 | OSChina 博客 | 腾讯云社区 | 阿里云栖社区 | Facebook | Linkedin | Youtube | 打赏(Donations) | About
知乎专栏多维度架构

2.25. httpx

2.25.1. 安装 https

	
python3 -m pip install httpx

# HTTP/2 支持,我们需要额外安装一个库

python3 -m pip install httpx[http2]
	
	
		

2.25.2. 操作演示

		
import httpx
r = httpx.get('https://www.example.org/')
r.text
r.content
r.json()
r.status_code		
		
		

2.25.3. Restful CRUD 操作

		
r = httpx.get('https://netkiller.cn/get')
r = httpx.post('https://netkiller.cn/post', data={'key': 'value'})
r = httpx.put('https://netkiller.cn/put', data={'key': 'value'})
r = httpx.delete('https://netkiller.cn/delete')
r = httpx.head('https://netkiller.cn/head')
r = httpx.options('https://netkiller.cn/options')
		
		

2.25.4. HTTP 2

		
import httpx
client = httpx.Client(http2=True, verify=False)
headers = {
    'Host': 'netkiller.com',
    'upgrade-insecure-requests': '1',
    'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.121 Safari/537.36',
    'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',
    'sec-fetch-site': 'none',
    'sec-fetch-mode': 'navigate',
    'sec-fetch-dest': 'document',
    'accept-language': 'zh-CN,zh;q=0.9'
}

response = client.get('https://www.netkiller.cn/linux/', headers=headers)
print(response.text)
		
		

2.25.5. 异步请求

		
async with httpx.AsyncClient() as client:
    resp = await client.get('https://www.netkiller.cn/index.html')
    assert resp.status_code == 200
    html = resp.text
		
		

asyncio

		
import httpx
import asyncio

async def main():
    async with httpx.AsyncClient() as client:
        resp = await client.get("https://www.netkiller.cn")
        result = resp.text
        print(result)

asyncio.run(main())		
		
		

2.25.6. 日志输出

		
import logging.config
import httpx

LOGGING_CONFIG = {
    "version": 1,
    "handlers": {
        "default": {
            "class": "logging.StreamHandler",
            "formatter": "http",
            "stream": "ext://sys.stderr"
        }
    },
    "formatters": {
        "http": {
            "format": "%(levelname)s [%(asctime)s] %(name)s - %(message)s",
            "datefmt": "%Y-%m-%d %H:%M:%S",
        }
    },
    'loggers': {
        'httpx': {
            'handlers': ['default'],
            'level': 'DEBUG',
        },
        'httpcore': {
            'handlers': ['default'],
            'level': 'DEBUG',
        },
    }
}

logging.config.dictConfig(LOGGING_CONFIG)
httpx.get('https://www.example.com')