我正在制作一个上传文本和图片的应用程序。我读了很多关于blobstore和Google高性能图像服务的文章,最后我找到了一种方法来实现它们。在
我想知道的是,是否所有的工作都做得很好,或者可以用更好的方式来做,以及是否最好在模型中保存服务的url,或者每次我想打印页面中的图像时都必须进行计算。在
只有一个用户和一张图片。在
这是代码(总结,忘了我的自定义.PageHandler,只具有轻松呈现页面的函数,以及用于检查表单值的内容等):
class User(ndb.Model):
""" A User """
username = ndb.StringProperty(required=True)
password = ndb.StringProperty(required=True)
email = ndb.StringProperty(required=True)
class Picture(ndb.Model):
""" All pictures that a User has uploaded """
title = ndb.StringProperty(required=True)
description = ndb.StringProperty(required=True)
blobKey = ndb.BlobKeyProperty(required=True)
servingUrl = ndb.StringProperty()
created = ndb.DateTimeProperty(auto_now_add=True)
user = ndb.KeyProperty(kind=User)
# This class shows the user pics
class List(custom.PageHandler):
def get(self):
# Get the actual user pics
pics = Picture.by_user(self.user.key)
for pic in pics:
pic.servingUrl = images.get_serving_url(pic.blobKey, size=90, crop=True)
self.render_page("myPictures.htm", data=pics)
# Get and post for the send page
class Send(custom.PageHandler, blobstore_handlers.BlobstoreUploadHandler):
def get(self):
uploadUrl = blobstore.create_upload_url('/addPic')
self.render_page("addPicture.htm", form_action=uploadUrl)
def post(self):
# Create a dictionary with the values, we will need in case of error
templateValues = self.template_from_request()
# Test if all data form is valid
testErrors = check_fields(self)
if testErrors[0]:
# No errors, save the object
try:
# Get the file and upload it
uploadFiles = self.get_uploads('picture')
# Get the key returned from blobstore, for the first element
blobInfo = uploadFiles[0]
# Add the key to the template
templateValues['blobKey'] = blobInfo.key()
# Save all
pic = Picture.save(self.user.key, **templateValues)
if pic is None:
logging.error('Picture save error.')
self.redirect("/myPics")
except:
self.render_page("customMessage.htm", custom_msg=_("Problems while uploading the picture."))
else:
# Errors, render the page again, with the values, and showing the errors
templateValues = custom.prepare_errors(templateValues, testErrors[1])
# The session for upload a file must be new every reload page
templateValues['form_action'] = blobstore.create_upload_url('/addPic')
self.render_page("addPicture.htm", **templateValues)
基本上,我列出了所有图片,在jinja2模板中显示了以下行:
^{pr2}$所以在List类中,我计算每个服务url并将其临时添加到模型中。我不知道是否可以直接将其保存在模型中,因为我不知道url是否会随时间而改变。这个图片的网址是永久的吗?那样的话,我可以保存它而不是计算,对吗?在
Send类只显示一个表单来上传图像并将数据保存到模型中。在重新呈现页面的情况下,我总是生成一个新的form_action链接,因为文档会讨论它。对吗?在
代码正在工作,但我想知道在性能和资源节约方面,哪种方法更好。在
你说得对。您确实希望保存get_serving_url(),而不是重复调用它。它保持不变。在
请注意,当您处理完url时,会有一个delete_serving_url(),就像删除blob一样。在
相关问题 更多 >
编程相关推荐