将blob参数传递给Django
我把我的图片存储在数据库里,作为二进制大对象(blob):
class MyClass(db.Model):
icon=db.BlobProperty()
现在,我想把这个二进制大对象发送到我的HTML里,比如说我有一个叫 myClass
的 MyClass
实例。
result = """<div img_attr=%s> Bla Bla </div>""" % (myClass.icon)
但是不知怎么的,这个方法不行。你有什么想法吗?
3 个回答
在数据存储中,使用 db.BlobProperty 存储的值并不是实际的二进制数据,而是一个叫做 BlobKey 的东西,用来指向这些数据。你可以用这个 BlobKey 做两件事。第一,你可以创建一个 BlobReader,从 BlobStore 中加载这些二进制数据到你的应用里;第二,你可以使用 ServeHandler.send_blob 来把这些数据传给客户端。
不过,在 Django 中使用第二种方法有点麻烦,因为 ServeHandler 和 Django 的请求处理流程不太兼容。下面是一个视图示例,可以帮你轻松实现这个功能:
def get_image_data(request, key, filename):
"serve original uploaded image"
# verify the users' ability to get the requested image
key = urllib.unquote(key)
img = _load_metadata(request, key)
blob = img.data;
blobkey = blob.key()
# and tell google to serve it
response = http.HttpResponse(
content='',
content_type=blob.content_type)
response['X-AppEngine-BlobKey'] = str(blobkey)
return response
你的代码看起来是在使用Django开发Google应用引擎的项目。
你只需要在你的视图中查询图片,然后把它作为HTTP响应返回就可以了。
image = myclassObject.icon
response = HttpResponse(image)
response['Content-Type'] = 'image/jpg'
return response
你不能直接把原始的图片数据放到你的网页里。你需要分两步来做这件事:
在你的html里,你需要引用一个图片文件:
result = "<div>"
"<img src='{0}' />"
"</div>"
.format(MYSITE + MYIMAGEDIR + myClass.name)
你的浏览器会读取这个html页面,发现你想要插入一张图片,然后它会去找这个图片文件 - 所以它会向你的网站请求类似于 http://www.myexample.com/images/icon01.jpg 这样的地址。
接下来,你需要单独回应这个第二个请求,把图片的内容提供给它,就像@anand所展示的那样。