在flask服务中远程读取该Excel的内容

在flask服务中远程读取该Excel的内容:

python 复制代码
from flask import Flask, jsonify  
import requests  
import pandas as pd  
import os  
import tempfile  
  
app = Flask(__name__)  
  
@app.route('/read_excel', methods=['GET'])  
def read_excel():  
    # Excel 文件的 URL  
    excel_url = 'https://xxx.xxx.xlsx'  
      
    # 发送请求并下载文件  
    response = requests.get(excel_url)  
      
    # 确保请求成功  
    if response.status_code != 200:  
        return jsonify({'error': 'Failed to retrieve Excel file'}), 400  
      
    # 创建一个临时文件来保存 Excel 文件  
    with tempfile.NamedTemporaryFile(delete=False) as tmp:  
        tmp.write(response.content)  
        tmp_file_path = tmp.name  
      
    try:  
        # 读取 Excel 文件  
        df = pd.read_excel(tmp_file_path)  
          
        # 这里可以处理数据,比如转换成 JSON 格式  
        data = df.to_json(orient='records')  
          
        # 返回数据  
        return jsonify(data)  
      
    except Exception as e:  
        # 如果发生错误,返回错误信息  
        return jsonify({'error': str(e)}), 500  
      
    finally:  
        # 删除临时文件  
        os.remove(tmp_file_path)  
  
if __name__ == '__main__':  
    app.run(debug=True)
相关推荐
啊哈哈1213821 小时前
系统设计复盘:为什么 Agent 的 ReAct 循环必须内嵌确定性保护层——以 FitMind 健康助手的路由与步骤控制为例
人工智能·python·react
一颗牙牙1 天前
安装mmcv
开发语言·python·深度学习
大数据魔法师1 天前
Streamlit(二)- Streamlit 架构与运行机制
python·web
m0_470857641 天前
PHP怎么实现工厂模式_Factory模式编写指南【指南】
jvm·数据库·python
大数据魔法师1 天前
Streamlit(三)- Streamlit 多页面应用开发
python·web
我的xiaodoujiao1 天前
API 接口自动化测试详细图文教程学习系列20--结合Pytest框架使用
python·学习·测试工具·pytest
python在学ing1 天前
前端-CSS学习笔记
前端·css·python·学习
IT策士1 天前
Django 从 0 到 1 打造完整电商平台:为什么用 Django 做电商?
后端·python·django
zkkkkkkkkkkkkk1 天前
Linux进行管理工具Supervisor配置与使用
linux·python·supervisor
2301_783848651 天前
mysql数据库迁移到云平台流程_使用数据传输服务DTS工具
jvm·数据库·python