You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将毒性检测cURL转为aiohttp异步请求并解决报错问题?

解决Google评论分析API异步调用问题

先修正400 Bad Request错误

确保请求严格符合Google API的规范,以下是正确的aiohttp异步请求模板:

import aiohttp
import asyncio

async def analyze_toxicity(comment_text, api_key):
    url = f"https://commentanalyzer.googleapis.com/v1alpha1/comments:analyze?key={api_key}"
    headers = {"Content-Type": "application/json"}
    payload = {
        "comment": {"text": comment_text},
        "requestedAttributes": {"TOXICITY": {}}
    }
    
    # 显式设置超时,避免请求挂起
    timeout = aiohttp.ClientTimeout(total=10)
    
    async with aiohttp.ClientSession(timeout=timeout) as session:
        try:
            async with session.post(url, json=payload, headers=headers) as response:
                if response.status == 400:
                    # 打印错误详情便于排查
                    error_detail = await response.json()
                    print(f"400错误详情: {error_detail}")
                    return None
                response.raise_for_status()
                return await response.json()
        except aiohttp.ClientError as e:
            print(f"请求出错: {str(e)}")
            return None

# 调用示例
async def main():
    result = await analyze_toxicity("测试评论内容", "你的有效API密钥")
    print(result)

if __name__ == "__main__":
    asyncio.run(main())

排查Fedora下PyCharm请求挂起超时问题

  • 系统网络限制排查:

    • 若开启全局代理,需在aiohttp中配置代理信息:
      connector = aiohttp.TCPConnector(proxy="http://你的代理地址:端口")
      async with aiohttp.ClientSession(connector=connector, timeout=timeout) as session:
          # 后续请求逻辑
      
    • 临时关闭SELinux测试:执行sudo setenforce 0,若恢复正常则需添加规则放行HTTPS请求
    • 放行防火墙出站HTTPS流量:执行sudo firewall-cmd --add-service=https --permanent && sudo firewall-cmd --reload
  • PyCharm配置检查:

    • 打开File > Settings > Appearance & Behavior > System Settings > HTTP Proxy,选择No proxy或正确配置代理参数
    • 在系统终端直接运行代码,排除PyCharm虚拟环境的网络权限问题
  • 超时逻辑强化:

    • 必须显式设置ClientTimeout,示例中设置10秒总超时,可根据网络情况调整时长

额外排查点

  • 确认API密钥未过期、未被限制调用次数或权限
  • 检查请求体字段是否完整,Google API要求comment.text和requestedAttributes为必填项
  • 确保请求方法为POST,且Content-Type严格设置为application/json,禁止使用form-data等其他格式

内容的提问来源于stack exchange,提问作者Larry Teischwilly

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 12:55:25