Skip to content

Instantly share code, notes, and snippets.

@jvanasco
Created April 4, 2014 23:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jvanasco/9984822 to your computer and use it in GitHub Desktop.
Save jvanasco/9984822 to your computer and use it in GitHub Desktop.
pyramid_debugtoolbar - SqlAlchemy as CSV
def make_application(settings, parent_registry):
""" WSGI application for rendering the debug toolbar."""
...
config.add_route('debugtoolbar.request.sql_csv', '/{request_id}/sql.csv')
...
import pyramid_debugtoolbar.panels.sqla
import csv
import StringIO
@view_config(
route_name='debugtoolbar.request.sql_csv',
permission=NO_PERMISSION_REQUIRED,
custom_predicates=(valid_host, valid_request),
)
def request_sql_csv(request):
history = find_request_history(request)
try:
last_request_pair = history.last(1)[0]
except IndexError:
last_request_pair = None
last_request_id = None
else:
last_request_id = last_request_pair[0]
request_id = request.matchdict.get('request_id', last_request_id)
toolbar = history.get(request_id, None)
if not toolbar:
raise NotFound
sqla_panel = None
for panel in toolbar.panels :
if isinstance(panel, pyramid_debugtoolbar.panels.sqla.SQLADebugPanel):
sqla_panel = panel
if not sqla_panel:
raise NotFound
csvfile = StringIO.StringIO()
csvwriter = csv.writer(csvfile)
for query in sqla_panel.data['queries'] :
csvwriter.writerow( (query['duration'], query['raw_sql'], pyramid_debugtoolbar.panels.sqla.text(query['parameters']) ) )
csvfile.seek(0)
as_csv = Response(\
content_type = 'text/csv',
body_file = csvfile,
status = 200,
)
as_csv.headers['Content-Disposition'] = str('attachment; filename= sql-%s.csv' % request_id)
return as_csv
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment