choox
choox

Reputation: 11

How to serve a pdf as a download programmatically in GAE and Webapp2?

I am a newbie at using GAE and am at my wits end.

I have a webpage displaying a form which when submitted (using angularjs $http) is supposed to result in the user being offered a pdf to download. The pdf is in the root directory of the folder I am uploading to GAE using appcfg, and currently can be seen by browsing to mydomain/mypdf.pdf.

My code to handle returning the pdf is here:

import os
import webapp2

class ServePDF(webapp2.RequestHandler):
    def post(self):
        q = 'mypdf.pdf'
        self.response.headers['Content-Type'] = 'application/octet-stream'
        self.response.headers['Content-Disposition'] = 'attachment; filename="%s"' % q
        self.response.out.write (open(os.path.dirname(__file__) + '/' + q).read())

app = webapp2.WSGIApplication([
    ('/servepdf', ServePDF)
], debug=True)

My app.yaml looks like this:

application: myapp
version: 1
runtime: python27
api_version: 1
threadsafe: true

handlers:
- url: /(.*\.(gif|png|jpg|ico|js|css))
  static_files: \1
  upload: (.*\.(gif|png|jpg|ico|js|css))

- url: /mypdf.pdf
  static_files: mypdf.pdf
  upload: mypdf.pdf 

- url: /robots.txt
  static_files: robots.txt
  upload: robots.txt 

- url: .*
  script: main.app

libraries:
- name: webapp2
  version: latest

What I see is that the pdf never appears due to an 500 (Internal server error) and the Google developers console gives me this response:

  File "/base/data/home/apps/myapp/1.382205997234590276/main.py", line 9, in post
    self.response.out.write (open(os.path.dirname(__file__) + '/' + q).read())
IOError: [Errno 2] No such file or directory: '/base/data/home/apps/myapp/1.382205997234590276/mypdf.pdf'

Maybe there's something wrong with my app.yaml? Thanks for any help.

Upvotes: 0

Views: 565

Answers (1)

gipsy
gipsy

Reputation: 3859

Your mypdf.pdf is not set up as application readable. You can do that in app.yaml

- url: /mypdf.pdf
  static_files: mypdf.pdf
  upload: mypdf.pdf 
  application_readable: true

Upvotes: 1

Related Questions