开发者想要创建一个应用程序,以便用户可以上传文本和图片。他希望使用 GAE、NDB、Blobstore 和 Google 高性能图片服务来实现这一目标。开发者想知道他的实现方式是否正确,并且希望了解一些性能和资源节省方面的最佳实践。
- 解决方案
- 优化图片服务 URL 的存储:
- 开发者之前在每次都要打印图片时计算图片服务 URL。这可能会导致性能下降,因为计算 URL 需要花费时间。
- 为了提高性能,开发者可以将图片服务 URL 直接存储在 Picture 模型中。这样,他就不需要每次都要计算 URL 了。
- 开发者可以放心地将图片服务 URL 保存到模型中,因为该 URL 在图片的生命周期内保持不变。
- 使用 BlobstoreUploadHandler 处理图片上传:
- 开发者使用 BlobstoreUploadHandler 来处理图片上传。这是一种最佳做法,因为它可以确保文件正确上传到 Blobstore。
- 开发者在创建表单操作链接时使用 blobstore.create_upload_url()。这是一种最佳做法,因为它可以确保表单操作链接是有效的。
- 删除过期的图片服务 URL:
- 当开发者删除图片时,他应该使用 images.delete_serving_url() 来删除图片服务 URL。这是一种最佳做法,因为它可以释放资源并且防止未使用的 URL 累积。
- 优化图片服务 URL 的存储:
以下是优化后的代码示例:
# 这里展示的用户图片
class List(custom.PageHandler):
def get(self):
# 获取当前用户的图片
pics = Picture.by_user(self.user.key)
# 如果图片服务 URL 未在模型中,则计算并将其保存到模型中
for pic in pics:
if not pic.servingUrl:
pic.servingUrl = images.get_serving_url(pic.blobKey, size=90, crop=True)
# 渲染页面,显示图片
self.render_page("myPictures.htm", data=pics)
# 发送页面(用于上传图片)
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):
# 创建一个字典来存储值,以便在发生错误时使用
templateValues = self.template_from_request()
# 验证表单数据是否有效
testErrors = check_fields(self)
if testErrors[0]:
# 没有错误,保存对象
try:
# 获取文件并上传
uploadFiles = self.get_uploads('picture')
# 获取 Blobstore 返回的第一个元素的密钥
blobInfo = uploadFiles[0]
# 将密钥添加到模板中
templateValues['blobKey'] = blobInfo.key()
# 计算图片服务 URL 并将其保存到模型中
templateValues['servingUrl'] = images.get_serving_url(blobInfo.key(), size=90, crop=True)
# 保存所有数据
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:
# 存在错误,重新渲染页面,显示值并显示错误
templateValues = custom.prepare_errors(templateValues, testErrors[1])
# 每次重新加载页面时,上传文件的会话都必须是新的
templateValues['form_action'] = blobstore.create_upload_url('/addPic')
self.render_page("addPicture.htm", **templateValues)
希望这些信息对你有帮助!