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

Python中如何为请求响应中返回None的字符串设置默认URL?

解决方案

问题出在你当前的代码逻辑里:当uid为None时,f-string会生成"https://registry.nbnatlas.org/public/show/None"这个非空字符串,而Python中非空字符串的布尔值为True,所以or后面的默认URL永远不会生效。

你可以先单独提取uid,判断它是否有效(不为None且非空),再决定最终的owner_url:

方法一:使用条件判断

d = requests.get(dataset_url)
output = d.json()

# 先获取uid,不存在或为None时得到None
provider_uid = output.get('provider', {}).get('uid')
# 根据uid是否有效选择URL
if provider_uid:
    owner_url = f"https://registry.nbnatlas.org/public/show/{provider_uid}"
else:
    owner_url = "https://registry.nbnatlas.org/datasets"

方法二:更简洁的三元表达式

如果想让代码更紧凑,可以用三元表达式:

d = requests.get(dataset_url)
output = d.json()

provider_uid = output.get('provider', {}).get('uid')
owner_url = f"https://registry.nbnatlas.org/public/show/{provider_uid}" if provider_uid else "https://registry.nbnatlas.org/datasets"

这两种写法都会在provider键不存在,或者uid为None/空字符串时,自动使用默认的https://registry.nbnatlas.org/datasets。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 20:15:42