python-需要帮助来处理Google App Engine Blobstore的上传表单
作者:互联网
我正在尝试学习blobstore API …,我能够成功上传文件并将其取回,但是我没有运气尝试将上传表单与常规网络表单结合使用,从而能够关联其他功能文件的相关信息,例如文件的昵称.
以下是我一直在玩的一个简单应用程序的代码.它基于google提供的示例.
#!/usr/bin/env python
#
import os
import urllib
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
from google.appengine.ext import db
class StoredFiles(db.Model):
nickname = db.StringProperty()
blobkey = blobstore.BlobReferenceProperty()
@staticmethod
def get_all():
query = db.Query(StoredFiles)
files = query.get()
return files
def doRender(handler, page, templatevalues=None):
path = os.path.join(os.path.dirname(__file__), page)
handler.response.out.write(template.render(path, templatevalues))
class MainHandler(webapp.RequestHandler):
def get(self):
allfiles = StoredFiles.get_all()
upload_url = blobstore.create_upload_url('/upload')
templatevalues = {
'allfiles': allfiles,
'upload_url': upload_url,
}
doRender(self, 'index.html', templatevalues)
class UploadHandler(blobstore_handlers.BlobstoreUploadHandler):
def post(self):
upload_files = self.get_uploads('file')
blob_info = upload_files[0]
self.redirect('/save/%s' % blob_info.key())
class SaveHandler(webapp.RequestHandler):
def get(self, resource):
newFile = StoredFiles()
newFile.nickname = self.request.get('nickname')
resource = str(urllib.unquote(resource))
newFile.blobkey = resource
newFile.put()
self.redirect('/')
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)
def main():
application = webapp.WSGIApplication(
[('/', MainHandler),
('/upload', UploadHandler),
('/save/([^/]+)?', SaveHandler),
], debug=True)
run_wsgi_app(application)
if __name__ == '__main__':
main()
根据文档,blobstore处理程序应该通过blob键传递,并将表单的其余部分传递给该处理程序,并将其重定向到… blob键可以正常通过,但是没有其他方法.
有人可以指出我要搞砸的地方,还是可以指向介绍此用例的优秀教程?
解决方法:
问题是当您将请求重定向到“ / save /%s”时,您发布的表单数据会丢失,这很正常.
而不是重定向,您应该将代码放在UploadHandler中,如下所示(未经测试的代码):
class UploadHandler(blobstore_handlers.BlobstoreUploadHandler):
def post(self):
try:
upload_files = self.get_uploads('file')
blob_info = upload_files[0]
newFile = StoredFiles()
newFile.nickname = self.request.get('nickname')
newFile.blobkey = blob_info.key()
newFile.put()
self.redirect('/')
except:
self.redirect('/upload_failure.html')
请参阅文档中的此页面,以获取类似示例:http://code.google.com/appengine/docs/python/tools/webapp/blobstorehandlers.html#BlobstoreUploadHandler
标签:blobstore,google-app-engine,python 来源: https://codeday.me/bug/20191105/1997505.html