Search code examples
google-app-enginewebapp2

App Engine: How can I give an image response using self.response.out using the webapp2 framework?


I am trying to send an image as a response, but I would like to do some work before that, so I basically can't just use the static .yaml route. Here is the code:

trackingModel = TrackingModel(uuid = key, ip_address=self.request.remote_addr)
        logging.info("Remote IP address: %s and current user is: %s", self.request.remote_addr, self.get_user_from_session())
        trackingModel.put()
        #self.response.write(trackingModel.time)
        self.response.headers.add_header('Access-Control-Allow-Origin', 'https://mail.google.com')
        self.response.headers.add_header('Access-Control-Allow-Credentials', 'true')
        self.response.headers['Content-Length'] = '0'
        self.response.headers['Cache-Control'] = 'max-age=0, no-cache, no-store'
        self.response.headers['Pragma'] = 'no-cache'

How can I return a 1px image from the same /static directory that returns my other static js and css files?


Solution

  • Do the work, then redirect to location of the image.

    # do work
    self.redirect('/static/image.gif')
    

    Alternatively, set the Content-Type to the mime type matching the image, then open the image as a file and write it. A bit more work on the program side, but it saves the extra round trip that the redirect introduced.