在模板中使用BlobStore上载

时间:2013-12-25 11:28:13

标签: python google-app-engine jinja2 blobstore

当我想上传到我的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)

在我想在模板中执行此操作的情况下,比如jinja模板,我在我的MainHandler类中做了类似的事情

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))

我在我的模板中执行此操作(下面的代码只是一个片段)

         ....
          <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>
                 ...

但这种方法似乎不会将文件上传到我的blobstore。拜托,我该怎么解决这个问题。提前致谢

0 个答案:

没有答案