0

glowscript.org is a Python-based GAE that stores user-written scripts in a datastore. How would I program in the Python server and/or JavaScript client a button that lets the user download to the user's Download directory one or more of the user's scripts? All I was able to find in my searching seemed to be oriented to me downloading the datastore from a command line, which seems unrelated to my case.

Tudormi
  • 1,092
  • 7
  • 18
user1114907
  • 972
  • 8
  • 15

1 Answers1

1

Edit: I modified my csv example to download a python file (.py) instead

My Datastore model

class MetricsJob(ndb.Model):
    result = ndb.TextProperty(compressed=True) # the file body
    name = ndb.StringProperty()
    # ... other fields

My Request handler

class MetricsDownload(webapp2.RequestHandler):
    def get(self, key):
        obj = ndb.Key(urlsafe=key).get()
        self.response.headers['Content-disposition'] = 'attachment; filename='+obj.name+'.py'
        self.response.headers['Content-Transfer-Encoding'] = 'Binary'
        self.response.headers['Content-Type'] = 'text/plain'
        self.response.out.write(obj.result)

HTML code, all you need to do is initiate a HTTP GET:

<a target="_blank" href="/metrics/download/ahFkZXZ-cGF5LXRvbGxvLXdlYnIRCxIEVXNlchiAgICAgODECww/"></a>

The key to getting the browser to treat the HTTP GET as a file download was the response headers.

For your use case I would imagine you would need to set:

self.response.headers['Content-Type'] = 'text/plain'

I'm not sure about the others

Alex
  • 5,141
  • 12
  • 26
  • I've tried many permutations of your code without success. I've seen hints that maybe I have to do something to my app.yaml file, but I don't know what. Did you have to specify something in your yaml file to make this work? – user1114907 Mar 20 '18 at 13:45
  • I wouldn't think you have to do any `app.yaml` changes, maybe you saw someone talking about setting `mime_type` for `static_dir`. One thing i noticed I had that my answer didn't have was `target="_blank"` in my html. I made a couple other tweaks to my answer, I did a temporary change to my code and I'm able to download that csv as a python file now instead. Your webserver may be overwriting your headers after you set them. Are you also using webapp2? – Alex Mar 26 '18 at 21:41
  • After looking at lots of notes on the subject, I finally round a solution that works in my environment: https://stackoverflow.com/questions/49460202/google-app-engine-download-a-file-to-users-local-download-folder?noredirect=1#comment85928658_49460202 – user1114907 Mar 28 '18 at 00:07