Python封装汇率API调用函数返回None,直接调用正常,求助排查
问题:封装汇率API函数返回None,但直接调用API正常?
你遇到的问题很典型——函数里的URL没有正确使用传入的参数,而是把参数名当成了固定字符串传给API了!
先看你封装的函数里的URL:
url = 'https://api.exchangerate.host/convert?from=source&to=target'
这里的source和target是字符串字面量,不是你传入的函数参数。也就是说,你每次调用函数时,实际请求的是from=source&to=target,而不是你传入的"EUR"和"USD"。这时候API无法识别无效的货币代码,返回的数据里要么没有result字段,要么result的值就是None,所以你最终返回的xchng自然是None。
而你直接调用API时,URL里写的是真实的货币代码from=USD&to=EUR,所以能正常获取到汇率。
修正后的函数代码
你需要用字符串格式化把参数代入URL,推荐使用f-string(Python 3.6+支持),写法更清晰直观:
import requests # 别忘了导入requests库哦 def getCurrentExchange(source, target): """The function takes the source - source and target currency - target and extract the rate as of now""" url = f'https://api.exchangerate.host/convert?from={source}&to={target}' response = requests.get(url) data = response.json() # 增加校验,避免API返回错误时出现KeyError if data.get('success') and 'result' in data: return data['result'] else: print(f"API请求失败:{data.get('error', '未知错误')}") return None print(getCurrentExchange("EUR", "USD"))
额外小建议
- 务必确保导入
requests库,不然函数会直接抛出导入错误(你直接调用API时应该已经导入了,但封装函数时容易遗漏)。 - 增加对API返回结果的校验,比如检查
success字段是否为True,能避免因API返回错误数据导致程序崩溃,同时也方便排查问题。
内容的提问来源于stack exchange,提问作者eponkratova
相关产品推荐
相关产品推荐

