推荐学习书目
› Learn Python the Hard Way
Python Sites
› PyPI - Python Package Index
› http://diveintopython.org/toc/index.html
› Pocoo
值得关注的项目
› PyPy
› Celery
› Jinja2
› Read the Docs
› gevent
› pyenv
› virtualenv
› Stackless Python
› Beautiful Soup
› 结巴中文分词
› Green Unicorn
› Sentry
› Shovel
› Pyflakes
› pytest
Python 编程
› pep8 Checker
Styles
› PEP 8
› Google Python Style Guide
› Code Style from The Hitchhiker's Guide
aieike
V2EX  ›  Python

我想在 flask 里返回 pandas 生成的 Excel 表格, 但又不想保存这个文件 有没有办法,跳过生成文件这个步骤? 我想到用流处理,但不知道该怎么弄

  •  
  •   aieike ·
    AIEIKE · Aug 19, 2019 · 4277 views
    This topic created in 2637 days ago, the information mentioned may be changed or developed.

    这是代码

    def download_excel():
        try:
            logger.info('download_excel, %s' % str(request.form))
            form_data = json.loads(request.form.get('data'))
            header_names = form_data['header_names']
            headers = form_data['headers']
            rows = form_data['list']
            data = OrderedDefault(list)
            for row in rows:
                for i, header_name in enumerate(header_names):
                    header = headers[i]
                    data[header_name].append(row[header])
            file_name = 'temp_data/temp.xlsx'
            pd.DataFrame(data).to_excel(file_name, index=False)
            response = make_response(send_file(file_name))
            return response
        except Exception as e:
            logger.exception(e)
            return make_response('Error', 301)
    
    Supplement 1  ·  Aug 20, 2019

    修改完后代码

    def download_excel():
        try:
            logger.info('download_excel, %s' % str(request.form))
            form_data = json.loads(request.form.get('data'))
            header_names = form_data['header_names']
            headers = form_data['headers']
            rows = form_data['list']
            data = OrderedDefault(list)
            for row in rows:
                for i, header_name in enumerate(header_names):
                    header = headers[i]
                    data[header_name].append(row[header])
            bf = io.BytesIO()
            pd.DataFrame(data).to_excel(bf, index=False)
            logger.info('Excel file size: {}'.format(bf.tell()))
            bf.seek(0)
            return send_file(bf, mimetype='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
    
        except Exception as e:
            logger.exception(e)
            return make_response('Error', 301)
    
    16 replies  •  2019-08-27 20:04:29 +08:00
    Nostalgiaaaa
    Nostalgiaaaa
    Aug 19, 2019
    1
    试试 StringIO ?
    aieike
    aieike
    OP
    Aug 19, 2019
    2
    @Nostalgiaaaa 我试了,但没成功,可能我的方法不对
    sunhk25
    sunhk25
    Aug 19, 2019 via Android
    4
    参考一下 https://zdyxry.github.io/2018/07/08/Flask-%E6%B5%81%E5%BC%8F%E5%93%8D%E5%BA%94/
    这个功能以后有时间也想实现一下
    julyclyde
    julyclyde
    Aug 19, 2019
    5
    @aieike “没成功”三个字没什么信息量
    你需要写的是“但是遇到了叉叉错误”
    aieike
    aieike
    OP
    Aug 19, 2019
    6
    @vZexc0m 谢谢, 用这句解决了
    response = send_file(buffer,
    attachment_filename=filename,
    as_attachment=True)
    wuwukai007
    wuwukai007
    Aug 19, 2019 via Android
    7
    有个问题,这个 io 是放在内存当中,如何放入 redis 中呢,或者集成到类似 django 的 cache 中
    janxin
    janxin
    Aug 19, 2019
    8
    @wuwukai007 这个 io 是 file-like,支持读写操作
    wuwukai007
    wuwukai007
    Aug 19, 2019 via Android
    9
    @ janxin 我的意思是,如果用户量大的话,这个 io 是用的本地的内存,怎么用 redis 之类作为 io 的存储
    reself
    reself
    Aug 19, 2019 via Android
    10
    用 BytesIO 试试看,pandas 有个 ExcelWriter 组件,可以往 filelike 的对象里写东西。对了,io 对象写好过后记得要 seek(0)。
    1462326016
    1462326016
    Aug 20, 2019
    11
    一楼的意思应该是 BytesIO ?
    ebingtel
    ebingtel
    Aug 20, 2019
    12
    @wuwukai007 既然是 file-like,可以 read 出来,存进 redis 的吧?但是存个 excel 的 io 好,还是存原始的数据,这个还需要权衡下
    aieike
    aieike
    OP
    Aug 20, 2019
    13
    @reself 对的, 我当时没有 seek(0), 也没加 minetype, 所以报错了
    aieike
    aieike
    OP
    Aug 20, 2019
    14
    还有一个问题,想问一下, 这个 Bytesio 需不需要像文件那样 close
    LUXiaobo
    LUXiaobo
    Aug 21, 2019
    15
    试试 tempfile
    aieike
    aieike
    OP
    Aug 27, 2019
    16
    @LUXiaobo 是个不错的方法[赞]
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   1485 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 43ms · UTC 15:38 · PVG 23:38 · LAX 07:38 · JFK 10:38
    ♥ Do have faith in what you're doing.