我需要为我的Python项目添加一个函数来检查注释的毒性。cURL的例子是:
curl -H "Content-Type: application/json" --data \
'{comment: {text: "what kind of idiot name is foo?"},
languages: ["en"],
requestedAttributes: {TOXICITY:{}} }' \
https://commentanalyzer.googleapis.com/v1alpha1/comments:analyze?key=YOUR_KEY_HERE
现在,还有一个Python代码示例。但这是不好的,因为它是同步的。我需要它是异步的,我需要使用aiohttp。这是我翻译cURL请求的尝试:
import aiohttp, asyncio
async def main():
async with aiohttp.ClientSession(headers={"CONTENT-TYPE": "application/json"}) as session:
async with session.get("https://commentanalyzer.googleapis.com/v1alpha1/comments:analyze?key"
"=",
json={"comment": {"text": "what kind of idiot name is foo?"},
"languages": ["en"],
"requestedAttributes": {"TOXICITY": {}}},
) as resp:
print(resp)
asyncio.run(main())
(我隐藏了我的API密钥)不幸的是,这不起作用,这会产生:
<ClientResponse(https://commentanalyzer.googleapis.com/v1alpha1/comments:analyze?key=) [400 Bad Request]>
<CIMultiDictProxy('Content-Type': 'text/html; charset=UTF-8', 'Referrer-Policy': 'no-referrer', 'Content-Length': '1555', 'Date': 'Thu, 22 Sep 2022 09:37:52 GMT')>
我该怎么解决这个问题?我已经看过aiohttp文档,尝试过很多事情,和kwargs一起玩过,但我还是得到了同样的东西。请帮帮忙
编辑:
所以,在邮递员玩了几下之后,我成功地发送了一个请求。有几个错误。首先,它必须是一个邮政请求。其次,如果没有这两个标题,它就无法工作:
Host: commentanalyzer.googleapis.com
Content-Length: 160
内容长度自动计算。问题是,当我试图在Fedora上的Pycharm中这样做时,它是不起作用的。它挂着。设置超时3秒后,它将引发该错误。
发布于 2022-10-08 10:17:13
在对邮递员和我的机器人做了很多修改之后,我找到了正确的论点:
async def analyzeText(text: str, threshold=0.90, bot=None):
analyze_request = {
"comment": {"text": text.replace("'", "").replace('"', '')},
"requestedAttributes": {
"SEVERE_TOXICITY": {},
"IDENTITY_ATTACK": {},
"THREAT": {},
"INSULT": {},
"INFLAMMATORY": {},
},
}
try:
async with bot.session.post(
f"https://commentanalyzer.googleapis.com/v1alpha1/comments:analyze?key"
f"={PERSPECTIVE_API_KEY}",
json=analyze_request,
headers={
"Content-Type": "application/json",
"Content-Length": str(len(str(analyze_request))),
"Host": "commentanalyzer.googleapis.com",
},
timeout=3,
) as resp:
pass
except aiohttp.web.HTTPException as e:
pass
return resp
https://stackoverflow.com/questions/73812875
复制相似问题