Python Restful CRUD 操作

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')	
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

netkiller-

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值