python HTTP library~Requests

python HTTP library~Requests,第1张

官网:Requests
接口:Main Interface

Requests 是一个第三方的http包。请求参数不需要手动拼接。

安装依赖
pip install requests
发送请求

Requests 支持的请求方式POSTGETOPTIONSDELETEPUTHEADPATCH
示例

import requests

	r = requests.get('https://api.github.com/events',params={'key1': 'value1', 'key2': 'value2'})
	r = requests.post('https://httpbin.org/post', data={'key': 'value'})
	r = requests.put('https://httpbin.org/put', data={'key': 'value'})
	r = requests.delete('https://httpbin.org/delete')
	r = requests.head('https://httpbin.org/get')
	r = requests.options('https://httpbin.org/get')
	

当字典中某个key的值为None,则该key将不会被添加到url的querey string中

import requests

    payload = {'key1': 'value1', 'key2': ['value2','value3'],'key3': None}
    response = requests.get('https://httpbin.org/get', params=payload)
    print(response.url)

输出结果   https://httpbin.org/get?key1=value1&key2=value2&key2=value3
响应结果

Requests 会自动解码服务器返回的响应内容。响应内容的编码依赖headers中的设置。
Requests 会自动对gzipdeflate 类型的响应结果解码,而br类型解码则需要安装Brotli包(brotli 或 brotlicffi)

response.text

response.content

response.json()
json解码失败将抛出异常

response.raw
使用此方式需要在初始化reqeust时将stream置为`True`
with open(filename, 'wb') as fd:
    for chunk in r.iter_content(chunk_size=128):
        fd.write(chunk)
自定义header
headers = {'user-agent': 'my-app/0.0.1'}
reqeust.get('https://api.github.com/events',params={'key1': 'value1', 'key2': 'value2'},headers=headers)

发送json 数据
requests.post('https://api.github.com/some/endpoint',json={'some': 'data'}
上传文件
url = 'https://httpbin.org/post'
files = {'file': ('report.xls', open('report.xls', 'rb'), 'application/vnd.ms-excel', {'Expires': '0'})}

r = requests.post(url, files=files)
r.text

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/723756.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-04-26
下一篇 2022-04-26

发表评论

登录后才能评论

评论列表(0条)

保存