質問

I'm using the csv module in python to create a download from one of the datastore tables in Google App Engine. The download works alright but you have to manually add an extension so that you can open it in Excel. I can't figure out how to modify the response so that the file download has a .csv extension. I could leave it like this however this web app is meant for a broad audience so I wanted to make it as easy as possible for them to use.

class fuCheckUp(webapp2.RequestHandler):

    def get(self):

      schedule_query = emailSchedule.all()
      follow_up_num = schedule_query[0].follow_up_num

      email_job_query = emailJobs.all()
      email_job_query.order('consent_date')

      header_tuple = ('last_modified', 'trigger_id', 'recipient_id', 'test_data', 'unsubscribe', 'start_date_local', 'consent_date', 'fu_period', 'last_fu_sent')
      data_tuples = ()
      variable_list = []

      for i in range(1, follow_up_num + 1):
        i = str(i)

        fu_due = 'fu' + i
        fu_sent = 'fu' + i + '_email_sent'

        variable_list.append(fu_due)
        variable_list.append(fu_sent)

        data_tuples = data_tuples + (fu_due, fu_sent)

    final_data_tuple = header_tuple + data_tuples
    data = [final_data_tuple]

    for part in email_job_query:
        last_modified = str(part.last_modified)
        trigger_id = str(part.trigger_id)
        recipient_id = str(part.recipient_id)
        test_data = str(part.test_data)
        unsubscribed = str(part.unsubscribed)
        start_date_local = str(part.start_date_local)
        consent_date = str(part.consent_date)
        fu_period = str(part.fu_period)
        last_fu_sent = str(part.last_fu_sent)

        var_list = []

        for var in variable_list:
            fu_var = getattr(part, var)
            var_list.append(str(fu_var))

        var_tuple = tuple(var_list)

        fixed_tuple = (last_modified, trigger_id, recipient_id, test_data, unsubscribed, start_date_local, consent_date, fu_period, last_fu_sent)
        csv_tuple = fixed_tuple + var_tuple

        data.append((csv_tuple))

    self.response.headers['Content-Type'] = 'application/csv'
    writer = csv.writer(self.response.out)

    for item in data:
        writer.writerow(item)
役に立ちましたか?

解決

Add another response header like this:

Content-Disposition: attachment;filename=example.csv
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top