| 知乎专栏 |
python3 -m pip install httpx # HTTP/2 支持,我们需要额外安装一个库 python3 -m pip install httpx[http2]
import httpx
r = httpx.get('https://www.example.org/')
r.text
r.content
r.json()
r.status_code
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())
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')
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)
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())
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())
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')