Using BlobStore Upload in a Template

Viewed 309

This Code Works well when i want to upload to my blobstore

import os
import urllib

from google.appengine.api import mail
from google.appengine.ext import blobstore
from google.appengine.ext import webapp
from google.appengine.ext.webapp import blobstore_handlers
from google.appengine.ext.webapp import template
from google.appengine.ext.webapp.util import run_wsgi_app

class MainHandler(webapp.RequestHandler):
    def get(self):
        upload_url = blobstore.create_upload_url('/upload')
        self.response.out.write('<html><body>')
        self.response.out.write('<form action="%s" method="POST" enctype="multipart/form-data">' % upload_url)
        self.response.out.write("""Upload File: <input type="file" name="file"><br> <input type="submit" 
            name="submit" value="Submit"> </form></body></html>""")

class UploadHandler(blobstore_handlers.BlobstoreUploadHandler):
    def post(self):
        upload_files = self.get_uploads('file')  # 'file' is file upload field in the form
        blob_info = upload_files[0]
        blob_reader = blobstore.BlobReader(blob_info.key())
        message = mail.EmailMessage(sender = 'crowdstardomain@gmail.com', subject = 'CSV')
        message.to = 'crowdstardomain@gmail.com'
        message.body = 'Download attached CSV'
        message.attachments = [blob_info.filename,blob_reader.read()]
        message.send()
        self.redirect('/serve/%s' % blob_info.key())

class ServeHandler(blobstore_handlers.BlobstoreDownloadHandler):
    def get(self, resource):
        resource = str(urllib.unquote(resource))
        blob_info = blobstore.BlobInfo.get(resource)
        self.send_blob(blob_info,save_as=True)

app = webapp.WSGIApplication(
  [('/', MainHandler),
    ('/upload', UploadHandler),
    ('/serve/([^/]+)?', ServeHandler),
  ], debug=True)

if __name__ == '__main__':
    run_wsgi_app(app)

in a case when i want to do this in a template, say jinja template, i did something like this in my MainHandler class

MainHandler(webapp.RequestHandler):
   def get(self):
        pageTitle = 'Make an Upload'
        template = JINJA_ENVIRONMENT.get_template('/otherPages/learn/subLearn/UploadForm.html')
        upload_url = blobstore.create_upload_url('/upload')
        variables = {
'upload':upload_url,
'pageTitle':pageTitle
                     }
        self.response.out.write(template.render(variables))

and i do this in my template (the code below is just a fragment)

         ....
          <div>


                   {% autoescape on %}
<form action="{{upload}}" method="POST" enctype="multipart/form-data">
      <input type="file" name="file"><br> <input type="submit" 
            name="submit" value="Submit"> </form>


{% endautoescape %}             



              </div>
                 ...

but this approach seems not to upload the file to my blobstore. Please, how can i solve this. Thanks in advance

0 Answers
Related