python - aiohttp 在 Python 对 API 的请求中对 http.client 有不同的响应
问题描述
语境:
这有效:
import http.client
conn = http.client.HTTPSConnection("something-api.com")
payload = 'grant_type=client_credentials&client_id=123-123-123&client_secret=123123&scope=something something'
headers = {
'Content-Type': 'application/x-www-form-urlencoded'
}
conn.request("POST", "/connect/token", payload, headers)
res = conn.getresponse()
data = res.read()
print(data.decode("utf-8"))
这没有。它返回{ 'error':'invalid_client' }
。
async def get_token(self):
params = {
"grant_type": "client_credentials",
"client_id": "123-123-123",
"client_secret": "123123",
"scope": "something something"
}
headers = {
"Content-Type": "application/x-www-form-urlencoded",
}
async with aiohttp.ClientSession() as session:
async with await session.post(
url="https://something-api.com/connect/token",
params=params,
headers=headers) as response:
return await response.json()
async def authorise(self):
response = await self.get_token()
# Returns { 'error':'invalid_client' }
return response
# -- Just so you can see how it's called:
authorise_task: tasks.Task = asyncio.create_task(example.authorise())
access_token = await authorise_task
问题:
我无法理解它们之间有什么区别。任何想法可能会发生什么?
我也试过:
- 也添加标题
ClientSession(headers=headers)
。 - 使用 URL 并删除参数
其他注意事项:
- aiohttp 文档在这里:https ://docs.aiohttp.org/en/stable/client_reference.html
- aiohttp 版本:
3.7.4.post0
解决方案
在文档中:
用于 GET 查询
params –
Mapping, iterable of tuple of key/value pairs or string to be sent as parameters in the query string of the new request. Ignored for subsequent redirected requests (optional)
Allowed values are:
collections.abc.Mapping e.g. dict, aiohttp.MultiDict or aiohttp.MultiDictProxy
collections.abc.Iterable e.g. tuple or list
str with preferably url-encoded content (Warning: content will not be encoded by aiohttp)
用于 POST 正文
data – The data to send in the body of the request. This can be a FormData object or anything that can be passed into FormData, e.g. a dictionary, bytes, or file-like object. (optional)
json – Any json compatible python object (optional). json and data parameters could not be used at the same time.
推荐阅读
- ms-access - 关系消失 - MS Access 2016
- python - 根据其他列的内容创建新列
- r - 无法在传单 R Shiny 中使用 renderText 显示来自 data.frame 的文本
- c# - 无法隐式转换类型'System.Collections.Generic.List
' 至 ' - python - MemoryError,pandas read_csv,32 位,不想使用 chunksize
- batch-file - 复制/合并批处理文件中的文件夹
- django - Selenium - 显示有关浏览器中正在发生的事情的注释
- c# - 如何在我的 Linq 查询的 OrderBy() 中放入 $cond?
- php - 更新当前行的列
- linux - 当我运行特定程序时,我可以将 /etc 目录指向其他地方吗