在AWS Lambda中替代requests模块post方法的Python库推荐(Python3.9+)
适配Python 3.9+的requests替代库推荐(适用于AWS Lambda)
以下几个库完全满足你的需求,API风格贴近requests,且支持Python 3.9及以上版本:
1. urllib3
作为requests的底层依赖库,urllib3本身就是成熟的HTTP客户端,AWS Lambda的Python运行时通常自带该库,无需额外打包部署。它的API虽比requests稍繁琐,但能实现完全一致的POST功能:
import urllib3 import json http = urllib3.PoolManager() # 发送form-data格式请求 response = http.request( 'POST', 'https://example.com/api', fields={'key1': 'value1', 'key2': 'value2'}, headers={'Content-Type': 'application/x-www-form-urlencoded'} ) # 发送JSON格式请求 response = http.request( 'POST', 'https://example.com/api', body=json.dumps({'key': 'value'}), headers={'Content-Type': 'application/json'} )
2. httpx
现代HTTP客户端,API设计几乎和requests一致,支持同步/异步请求,完全兼容Python 3.9+,是requests的无缝替代方案。若需额外部署,打包体积也很小,适配Lambda环境:
import httpx # 发送form-data请求 response = httpx.post( 'https://example.com/api', data={'key1': 'value1', 'key2': 'value2'}, headers={'X-Custom-Header': 'value'} ) # 发送JSON请求 response = httpx.post( 'https://example.com/api', json={'key': 'value'}, headers={'X-Custom-Header': 'value'} )
3. http.client(Python标准库)
无需安装任何第三方依赖,直接使用Python内置模块,适合追求最小部署包体积的场景:
import http.client import json conn = http.client.HTTPSConnection('example.com') # 发送JSON请求 headers = {'Content-Type': 'application/json'} payload = json.dumps({'key': 'value'}) conn.request('POST', '/api', payload, headers) response = conn.getresponse() # 发送form-data请求 headers = {'Content-Type': 'application/x-www-form-urlencoded'} payload = 'key1=value1&key2=value2' conn.request('POST', '/api', payload, headers) response = conn.getresponse()
内容的提问来源于stack exchange,提问作者Aarya
相关产品推荐
相关产品推荐

