passing blob parameter to django

2019-06-14 02:01发布

I keep my images in the DB as blobs:

class MyClass(db.Model):
    icon=db.BlobProperty()

Now, I want to send the blob to my HTML like this : lets say I have myClass as an instance of MyClass

result = """<div img_attr=%s> Bla Bla </div>""" % (myClass.icon)

Some how it doesn't work. Do you have any idea?

3条回答
Evening l夕情丶
2楼-- · 2019-06-14 02:45

You cannot just dump raw image data into your html page. You need to do this in two pieces:

In your html, you need to refer to an image file:

result = "<div>"
         "<img src='{0}' />"
         "</div>"
         .format(MYSITE + MYIMAGEDIR + myClass.name)

Your browser reads the html page, finds out you want to include an image, and goes looking for the image file to include - so it asks your site for something like http://www.myexample.com/images/icon01.jpg

Now, separately, you respond to this second request with the image content, as @anand has shown.

查看更多
3楼-- · 2019-06-14 02:56

Your code suggests that you are working on Google application engine with Django.

You just need to query the image in your view and return it as http response.

image = myclassObject.icon

response = HttpResponse(image)

response['Content-Type'] = 'image/jpg'

return response

查看更多
在下西门庆
4楼-- · 2019-06-14 02:58

The value stored in the the data store, and returned by appengine with a db.BlobProperty is not the actual bytes of the blob, but rather a BlobKey that is used to reference it. There are two ways you can use that key. You can create a BlobReader to load the bytes of the blob from the BlobStore into your app, or you can craft a response with ServeHandler.send_blob to transfer those bytes to the client.

Doing the second one in Django is a bit of a headache, because ServeHandler doesn't really fit in well with the Django request processing stack. Here's a view that will do it for you without too much trouble:

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
查看更多
登录 后发表回答