テキストと画像をアップロードするアプリを作成しています。私は blobstore と Google High Performance Image Serving について多くのことを読んできましたが、ついにそれらをすべてまとめて実装する方法を手に入れました。
私が知りたいのは、すべてがうまくいっているか、より良い方法で実行できるか、また、serving_url をモデルに保存する方が良いか、ページに画像を印刷するたびに計算する必要があるかです。
ユーザーと画像のみがあります。
これはコードです (要約すると、私の custom.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 テンプレートに画像を表示します。
{% for line in data %}
<tr>
<td class="col-center-data"><img src="{{ line.servingUrl }}"></td>
したがって、List クラスでは、各提供 URL を計算し、一時的にモデルに追加します。URLが時間とともに変化する可能性があるかどうかわからないため、モデルに直接保存するのが良いかどうかは正確にはわかりません。画像の URL は永続的になりますか? その場合、計算する代わりに保存できますよね?
Send クラスは、画像をアップロードするためのフォームのみを表示し、データをモデルに保存します。ドキュメントがそれについて話しているので、ページを再レンダリングする場合は常に新しい form_action リンクを生成します。そうですか?
コードは機能していますが、パフォーマンスとリソース節約の観点から、どちらがより良い方法かを知りたいです。