Failing to download search results as csv

7 views
Skip to first unread message

mostwanted

unread,
Aug 22, 2023, 5:32:48 AMAug 22
to web2py-users
Hi guys, i need help downloading results as csv, i am failing dismally I dont know what to do
After the search results return values I want to download those results into my computer somewhere the current version of my code is giving me an error:
<class 'TypeError'> string indices must be integers

Here is my code
FROM THE SEARCH VIEW:
 <a href="{{=URL('download_results', args=request.vars)}}" class="btn">Download Results as CSV</a>

DOWNLOAD CONTROLLER:
import csv
from io import StringIO

def download_results():
    # Retrieve the filtered records
    records = request.vars

    #  CSV data
    csv_data = []
    csv_data.append(['First Name', 'Last Name', 'Program', 'Study Mode'])  # Header row
    for record in records:
        csv_data.append([record['first_name'], record['last_name'], record['program'], record['study_mode']])

    # Create a response to download the CSV file
    response.headers['Content-Type'] = 'text/csv'
    response.headers['Content-Disposition'] = 'attachment; filename=registration_results.csv'

    # Write CSV data to a StringIO object
    output = StringIO()
    csv_writer = csv.writer(output)
    for row in csv_data:
        csv_writer.writerow(row)

    # Return the content as bytes
    return output.getvalue().encode('utf-8')
Reply all
Reply to author
Forward
0 new messages