Home | 简体中文 | 繁体中文 | 杂文 | Github | 知乎专栏 | Facebook | Linkedin | Youtube | 打赏(Donations) | About
知乎专栏

2.8. httpx

2.8.1. 安装 https

	
python3 -m pip install httpx

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

python3 -m pip install httpx[http2]
	
	
		

2.8.2. 操作演示

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

2.8.3. 上传文件

		
import httpx

auth = httpx.BasicAuth(username="neo", password="admin")
client = httpx.Client(auth=auth, base_url="http://api.netkiller.cn:8080",timeout=60)

files = {'file': open('../datasets/tongue/val/images/black tongue coating_1.jpg', 'rb')}
response = client.post('/tongue/diagnosis', files=files)
print(response.status_code, response.json())		
		
		

2.8.4. 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.8.5. 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.8.6. BasicAuth

		
import httpx

auth = httpx.BasicAuth(username="admin", password="admin")
client = httpx.Client(auth=auth, base_url="http://api.aigcsst.cn:8080")
response = client.get("/")
print(response.status_code, response.json())		
		
		

2.8.7. 异步请求

		
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.8.8. 日志输出

		
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')