Python Restful CRUD 操作
2.25.1. 安装 httpx
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')