'Download the query results as csv.'

@has_access
@expose(u'/csv/<client_id>')
@log_this
def csv(self, client_id):

    logging.info(u'Exporting    CSV    file    [{}]'.format(client_id))
    query = db.session.query(Query).filter_by(client_id=client_id).one()
    rejected_tables = self.rejected_datasources(query.sql, query.database, query.schema)
    if rejected_tables:
        flash(get_datasource_access_error_msg(u'{}'.format(rejected_tables)))
        return redirect(u'/')
    blob = None
    if (results_backend and query.results_key):
        logging.info(u'Fetching    CSV    from    results    backend    [{}]'.format(query.results_key))
        blob = results_backend.get(query.results_key)
    if blob:
        logging.info(u'Decompressing')
        json_payload = utils.zlib_decompress_to_string(blob)
        obj = json.loads(json_payload)
        columns = [c[u'name'] for c in obj[u'columns']]
        df = pd.DataFrame.from_records(obj[u'data'], columns=columns)
        logging.info(u'Using    pandas    to    convert    to    CSV')
        csv = df.to_csv(index=False, encoding=u'utf-8')
    else:
        logging.info(u'Running    a    query    to    turn    into    CSV')
        sql = (query.select_sql or query.executed_sql)
        df = query.database.get_df(sql, query.schema)
        csv = df.to_csv(index=False, encoding=u'utf-8')
    response = Response(csv, mimetype=u'text/csv')
    response.headers[u'Content-Disposition'] = u'attachment;    filename={}.csv'.format(query.name)
    logging.info(u'Ready    to    return    response')
    return response
