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

基于Frankfurter的货币转换App持续返回None值问题求助

解决Frankfurter货币转换应用输出显示None的问题

核心问题1:格式化函数未实现导致返回None

currency.py中的format_conversion_result函数仅用pass占位,没有返回任何有效内容,无论转换接口返回的汇率是否正常,调用该函数都会返回None,这是页面显示None的直接原因。

修复代码(currency.py):

def format_conversion_result(result, amount):
    # 接收汇率和金额参数,返回格式化后的转换结果
    return f"{amount} = {result * amount:.2f}"

同时修改app.py中的调用逻辑,传入金额参数:

if result is not None:
    st.write(format_conversion_result(result, amount))
else:
    st.write("Conversion result not available or there was an error.")

核心问题2:日期判断逻辑错误

Streamlit的date_input组件默认会返回当前日期,不会为空值,原代码中if date:的判断永远为True,导致程序只会调用历史转换接口,无法触发最新汇率查询。

修复app.py中的判断逻辑,新增选项让用户主动选择是否使用历史汇率:

# 新增复选框让用户选择是否使用历史汇率
use_historical = st.checkbox("使用历史汇率(需选择日期)")

if st.button("Convert"):
    if use_historical and date:
        result = get_historical_conversion(date, from_currency, to_currency)
    else:
        result = get_latest_conversion(from_currency, to_currency)
    
    # 调试用:打印转换结果确认接口返回值
    print(f"接口返回汇率:{result}")
    
    if result is not None:
        st.write(format_conversion_result(result, amount))
    else:
        st.write("Conversion result not available or there was an error.")

次要问题:避免currencies_list导入冲突

app.py中同时从api和currency导入currencies_list,会导致变量被覆盖。建议统一使用api.py中从接口拉取的实时货币列表,调整app.py的导入语句:

import streamlit as st
from api import get_latest_conversion, get_historical_conversion, currencies_list
from currency import format_conversion_result

并删除currency.py中的硬编码currencies_list。

额外调试建议

  • 检查历史转换接口的响应:Frankfurter API对历史日期有范围限制,若请求日期早于API支持的起始日期,会返回错误。可在get_historical_conversion中增加状态码日志:
    print(f"API响应状态码:{response.status_code}")
    
  • 确认货币代码格式:API要求货币代码为大写,确保下拉框中的代码与API返回的格式一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 14:25:28