简体   繁体   中英

Unwanted template code attached to response.out.write

I'm stuck with trying to create a downloadable content. I'm using webapp2.RequestHandler and I've got the following scenario:

  1. I'm using Jinja 2 to create a page with a 'download this as csv' link.
  2. When you click the link, the file is downloaded correctly, starts with the correct content, and at the end it has got the template content added.

Here's my class:

class xmlAnalyzer(Handler):
    def get(self):
        displaySample = self.request.get('SamplePage')
        downloadMapping = self.request.get('downloadMapping')

        if downloadMapping:
            r = self.request.get('srcTgtMapping')
            srcTgtMapping = r.split('], [')

            csvContents = 'Column name; Source name; Source type; Column name; Target name; Target type;\n'
            self.response.headers['Content-Disposition'] = 'attachment; filename=' + str(downloadMapping) +'.csv'
            self.response.out.write(csvContents)

        elif displaySample == '2':
            testString = 'abracadabra'
            self.response.headers['Content-Disposition'] = 'attachment; filename=' + 'testFile.csv'
            self.response.write(testString)

Now while the second case works fine (if SamplePage=2 parameter is provided) file contains just the word 'abracadabra'. In the first case however, the dowloaded file looks as follows:

Column name; Source name; Source type; Column name; Target name; Target type;
<!DOCTYPE html>

<link rel="stylesheet" type="text/css" href="/stylesheets/styles.css">
<Content-Type: text/html; charset=utf-8>
<html>
<body class="body">

<div class="main-title">Welcome to XML Analyzer for Informatica PowerCenter</div>

The first line is what I expect. But that should be all. The rest is the template - any idea why is this getting added? Thanks in advance!

Hard to say, but intuitively, deciding by the code you showed us, I would guess it's either...

  • got to do with the self.response.out.clear() in the first if block—the second one doesn't have it;
  • or with automatic template rendering by the webapp2 framework; but this doesn't explain why the 2 cases behave differently, so this is what made me notice that self.response.out.clear() call.

PS by the way, are you sure you've shown us all the relevant pieces of your code?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM