Azure函数中Pandas获取XE汇率重复取值问题求助
解决Azure函数中Pandas读取XE汇率重复缓存的问题
问题根源
pd.read_html() 底层依赖的HTTP库默认启用缓存机制,而Azure函数的Python解释器是复用实例的,首次请求后的页面会被缓存到内存中,后续调用时直接读取缓存内容,导致无法获取最新汇率。
解决方案:手动发起无缓存的HTTP请求
不要直接让Pandas处理URL,改用requests库手动发送请求,通过设置请求头禁用缓存,再将响应内容传给pd.read_html()。
修改后的代码
import pandas as pd import requests def get_eur_cop_rate(): url_EUR_COP = 'https://www.xe.com/currencyconverter/convert/?Amount=1&From=EUR&To=COP' # 设置禁用缓存的请求头 headers = { 'Cache-Control': 'no-cache, no-store, must-revalidate', 'Pragma': 'no-cache', 'Expires': '0' } # 发起带无缓存头的请求 response = requests.get(url_EUR_COP, headers=headers, timeout=10) response.raise_for_status() # 处理请求失败的情况 # 从响应内容中解析表格 lst_url_EUR_COP = pd.read_html(response.text) df_trm_EUR_COP = pd.DataFrame(lst_url_EUR_COP[0]) return df_trm_EUR_COP
额外注意事项
- 每次调用函数时,这个方法都会强制从XE服务器拉取最新页面,彻底避免缓存问题。
- 添加
timeout参数防止请求超时卡住Azure函数实例。 - 如果后续遇到XE的反爬限制,可以添加
User-Agent头模拟浏览器请求,示例:headers = { 'Cache-Control': 'no-cache, no-store, must-revalidate', 'Pragma': 'no-cache', 'Expires': '0', 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Safari/537.36' }
内容的提问来源于stack exchange,提问作者dmantilla9
相关产品推荐
相关产品推荐

