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

解决TouchDesigner中AttributeError: 'URLError'无'read'属性问题

修复TouchDesigner中天气API调用的SSL及错误处理问题

问题根源

  1. SSL证书验证失败:macOS环境下TouchDesigner自带的Python框架未正确配置SSL根证书,导致无法验证HTTPS接口的证书有效性。
  2. 错误处理逻辑错误:URLError对象不存在read()和code属性,原代码错误调用这两个方法,触发AttributeError。

修复后的完整代码

import json
import urllib.request
import urllib.error
import sys
import ssl

BaseURL = 'https://weather.visualcrossing.com/VisualCrossingWebServices/rest/services/timeline/'

ApiKey='你的API密钥'
UnitGroup='us'
Location='Washington,DC'
StartDate = ''
EndDate=''
ContentType="json"
Include="current"

# 构建API请求URL
ApiQuery=BaseURL + Location
if len(StartDate):
    ApiQuery+="/"+StartDate
    if len(EndDate):
        ApiQuery+="/"+EndDate

ApiQuery+="?"
if len(UnitGroup):
    ApiQuery+="&unitGroup="+UnitGroup
if len(ContentType):
    ApiQuery+="&contentType="+ContentType
if len(Include):
    ApiQuery+="&include="+Include
ApiQuery+="&key="+ApiKey

print(' - 正在调用的URL: ', ApiQuery)
print()

# 创建跳过SSL验证的上下文(仅临时解决,生产环境建议配置正确证书)
ssl_context = ssl.create_default_context()
ssl_context.check_hostname = False
ssl_context.verify_mode = ssl.CERT_NONE

try: 
    # 使用自定义SSL上下文发起请求
    data = urllib.request.urlopen(ApiQuery, context=ssl_context)
except urllib.error.HTTPError as e:
    # HTTPError有read()和code属性,正常处理
    ErrorInfo = e.read().decode() 
    print('错误代码: ', e.code, ErrorInfo)
    sys.exit()
except urllib.error.URLError as e:
    # URLError通过reason获取错误详情
    print('连接错误: ', str(e.reason))
    sys.exit()
    
weatherData = json.loads(data.read().decode('utf-8'))

op('request_output').text = json.dumps(weatherData)

debug(ApiQuery)

关键改动说明

  • SSL问题修复:通过ssl.create_default_context()创建自定义上下文,关闭证书验证和主机名检查,绕过macOS下的证书缺失问题。注意:这是临时解决方案,生产环境建议手动配置TouchDesigner Python的根证书。
  • 错误处理修复:
    • 保留HTTPError的原有处理逻辑(该类确实包含read()和code属性)
    • 修改URLError的处理逻辑,使用e.reason获取错误详情,避免调用不存在的方法
  • 移除了未使用的codecs模块,精简代码

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.05 14:15:55