如何从Blobstore显示图片?
我正在试着理解这份文档 使用 Images Python API,但我对如何获取关键字和显示头像感到困惑。
文档提到,Image
处理器会通过 /img
路径来提供图片。
我不太明白这个 Image
处理器到底是干什么的。我在下面评论了我的理解;请指正。谢谢:
class Image (webapp.RequestHandler):
def get(self):
#get the key of the image "img_id" from datastore
#what is the value of "img_id"? Where does it come from?
#how does the app engine know to get what key for which image?
greeting = db.get(self.request.get("img_id"))
#what is greeting.avatar?
#is it img_id.avatar ?
#I assume "avatar" refers to the "avatar" property in the model
if greeting.avatar:
self.response.headers['Content-Type'] = "image/png"
#does this display the avatar?
#I thought the img tag displayed the avatar
self.response.out.write(greeting.avatar)
else:
self.error(404)
非常感谢你的帮助。
更新(关于 Gabi Purcaru 的回答)
再次感谢你的清晰回答。我有一个查询,用来显示用户评论,像这样:
for result in results:
self.response.out.write("<li>")
self.response.out.write("<b>%s</b> %s " % (result.userName, result.userLatestComment))
self.response.out.write("</li>")
self.response.out.write("</ol></body></html>")
所以,我从 MainPage 处理器 复制了包含图片标签的那一行
self.response.out.write("<div><img src='img?img_id=%s'></img>" % greeting.key())
然后修改
greeting.key()
为
result.key()
我假设,这样应该可以在用户评论旁边显示头像:
for result in results:
self.response.out.write("<li>")
self.response.out.write("<b>%s</b> %s " % (result.userName, result.userLatestComment))
self.response.out.write("<div><img src='img?img_id=%s'></img>" % result.key())
self.response.out.write("</li>")
self.response.out.write("</ol></body></html>")
但我还是不明白为什么 result.key()
是我想要显示的图片的关键字?
1 个回答
"img_id"
是从网址的 GET 部分获取的(类似于 "www.example.com/img?img_id=12312")。系统会为数据库中的每个模型分配一个新的唯一标识符。greeting.avatar
是与img_id
这个标识符对应的模型的头像属性。所以,从某种意义上说,你可以把它理解为img_id.avatar
,虽然从技术上讲这样说并不完全准确。这并不是显示头像,而只是返回头像。为了让你更好理解,我们用一个常见的图片来举个例子。当你写
<img src="some_link" />
时,浏览器会去寻找"some_link"
,并把那张图片包含进来。浏览器会从文件系统中读取这张图片,然后返回给用户。你的处理程序所做的事情是改变后端的部分,让网络服务器从数据存储中返回这张图片(特别是那个avatar
属性),而不是从普通文件中获取。浏览器和用户看到的仍然是普通的图片。
编辑:
result.key()
是数据库自动为你的模型分配的唯一标识符。你需要把这个信息“告诉”你刚写的图片处理程序,以便它知道你需要哪个特定模型的头像。你可以通过设置网址中的 img_id
GET 变量来做到这一点(这就是你刚刚做的)。
我不确定你是否理解 .key()
的整个概念。让我来解释一下:
任何数据库都需要区分不同的记录(在我们的例子中是模型)。这就是为什么数据库会 自动 为每一条插入的记录分配一个新的、最重要的是 唯一 的标识符(在我们的例子中是键)。你需要提供模型的键,以便你的处理程序能够返回该模型的头像。
让我们用一个现实生活中的例子来说明:你是许多人中的一个。你的国家通过某种社会安全号码(SSN)来唯一识别你。在我所在的国家,这个号码是一个13位的代码(例如 1024582485008
)。如果我想申请驾驶执照,我需要提供我的名字,但这还不够——我不是我国家唯一的 Gabi Purcaru。我还需要提供我的 SSN,这样才能准确地告诉别人我是谁。如果我们做个类比,你需要向处理程序提供模型的“SSN”(即键),这样它才能知道从数据库中获取哪个模型并返回它的头像。