在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)
相关推荐
上班日常摸鱼6 小时前
Shell脚本基础教程:变量、条件判断、循环、函数实战(附案例)
python
无心水6 小时前
【Python实战进阶】5、Python字符串终极指南:从基础到高性能处理的完整秘籍
开发语言·网络·python·字符串·unicode·python实战进阶·python工业化实战进阶
2301_807583236 小时前
了解python,并编写第一个程序,常见的bug
linux·python
小白学大数据6 小时前
构建混合爬虫:何时使用Requests,何时切换至Selenium处理请求头?
爬虫·python·selenium·测试工具
2401_827560206 小时前
【Python脚本系列】PyAudio+librosa+dtw库录制、识别音频并实现点击(四)
python·语音识别
BBB努力学习程序设计7 小时前
Python自动化脚本:告别重复劳动
python·pycharm
BBB努力学习程序设计7 小时前
Python函数式编程:优雅的代码艺术
python·pycharm
2501_940943917 小时前
体系课\ Python Web全栈工程师
开发语言·前端·python
田姐姐tmner8 小时前
Python切片
开发语言·python
t***31658 小时前
爬虫学习案例3
爬虫·python·学习