Welcome, guest | Sign In | My Account | Store | Cart

Simple decorator for CherryPy/TurboGears useful for publishing some data as a CSV file.

Python, 24 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
def expose_as_csv(f):
    @expose()
    @strongly_expire
    def wrap(*args, **kw):
        rows = f(*args, **kw)
        out = StringIO.StringIO()
        writer = csv.writer(out) #quoting=csv.QUOTE_ALL
        writer.writerows(rows)
        cherrypy.response.headerMap["Content-Type"] = "text/csv"
        cherrypy.response.headerMap["Content-Length"] = out.len
        return out.getvalue()
    return wrap


# Usage
class Root(...

    @expose_as_csv
    def somereport_csv(self):
        data = [('a', 1), ('b', 2), ('c', 3)]
        return data

# Test
wget http://yourdomain/somereport.csv
Created by Shekhar Tiwatne on Thu, 19 Jun 2008 (PSF)
Python recipes (4591)
Shekhar Tiwatne's recipes (6)

Required Modules

  • (none specified)

Other Information and Tasks