Return to Snippet

Revision: 61663
at January 4, 2013 02:46 by doronhor


Initial Code
import xlwt
import StringIO
import mimetypes
from flask import Response
from werkzeug.datastructures import Headers

#... code for setting up Flask

@app.route('/export/')
def export_view():
    #########################
    # Code for creating Flask
    # response
    #########################
    response = Response()
    response.status_code = 200


    ##################################
    # Code for creating Excel data and
    # inserting into Flask response
    ##################################
    workbook = xlwt.Workbook()

    #.... code here for adding worksheets and cells

    output = StringIO.StringIO()
    workbook.save(output)
    response.data = output.getvalue()

    ################################
    # Code for setting correct
    # headers for jquery.fileDownload
    #################################
    filename = export.xls
    mimetype_tuple = mimetypes.guess_type(filename)

    #HTTP headers for forcing file download
    response_headers = Headers({
            'Pragma': "public",  # required,
            'Expires': '0',
            'Cache-Control': 'must-revalidate, post-check=0, pre-check=0',
            'Cache-Control': 'private',  # required for certain browsers,
            'Content-Type': mimetype_tuple[0],
            'Content-Disposition': 'attachment; filename=\"%s\";' % filename,
            'Content-Transfer-Encoding': 'binary',
            'Content-Length': len(response.data)
        })

    if not mimetype_tuple[1] is None:
        response.update({
                'Content-Encoding': mimetype_tuple[1]
            })

    response.headers = response_headers

    #as per jquery.fileDownload.js requirements
    response.set_cookie('fileDownload', 'true', path='/')

    ################################
    # Return the response
    #################################
    return response

Initial URL

                                

Initial Description
A combinations of 3 technologies.
Needed to create Excel files within a Python Flask web framework environment and have it sent via HTTP to client to be handled by the jquery.fileDownload library.

Notes:
1. Flask has to set a cookie specified by jquery.fileDownload
2. Divided code into blocks of code that can be maybe reusable in functions
3. 'app' is not declared but it is obvious a Flask application object

relevant projects:
1.  http://flask.pocoo.org/
2. pypi.python.org/pypi/xlwt and www.python-excel.org/
3. https://github.com/johnculviner/jquery.fileDownload

Initial Title
Create Excel file with xlwt and insert in Flask response valid for jquery.fileDownload

Initial Tags
excel

Initial Language
Python