Tipfy: How to display blob in template?

2019-04-10 23:34发布

Given is on gae using tipfy (python) the following model:

greeting.avatar = db.Blob(avatar)

What is the template-tag to display a blob (here image)?

2条回答
不美不萌又怎样
2楼-- · 2019-04-10 23:52

There isn't a built-in template tag for displaying arbitrary data like that. I can think of two approaches:

  1. Write a request handler for serving avatars as images. Based on your example, request handler would just need to look up the greeting to get the image data, send an appropriate Content-Type: image/jpeg (or image/png or whatever) header and then write the blob data to the response stream.

    Then, in your template, you'd display the image like this:

    <img src="/show-avatar/{{ greeting.key().id() }}">
    
  2. Write a custom template tag/template filter that takes the blob data and generates an appropiate data URL, which would encode the image data directly in the HTML document you're generating.

    Then, in your template, you'd display the image something like this:

    <img src="{{ greeting.avatar|dataurl }}">
    

    which would result in output along these lines in the template:

    <img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAoAAAAKCAYAAACNMs+9AAAABGdBTUEAALGPC/xhBQAAAAlwSFlzAAALEwAACxMBAJqcGAAAAAd0SU1FB9YGARc5KB0XV+IAAAAddEVYdENvbW1lbnQAQ3JlYXRlZCB3aXRoIFRoZSBHSU1Q72QlbgAAAF1JREFUGNO9zL0NglAAxPEfdLTs4BZM4DIO4C7OwQg2JoQ9LE1exdlYvBBeZ7jqch9//q1uH4TLzw4d6+ErXMMcXuHWxId3KOETnnXXV6MJpcq2MLaI97CER3N0vr4MkhoXe0rZigAAAABJRU5ErkJggg==" />
    
查看更多
迷人小祖宗
3楼-- · 2019-04-11 00:08

In this case the blob is an an image, which is great. Just use images.get_serving_url(blob_key) and you're happy. I've used this function, and trust me, it is awesome for serving images. Just append =sxx to the url where xx is the pixel size you want. It automatically resizes the image and serves it.

If the blob isn't an image, then you're out of luck w.r.t an easy way out. Maybe use the BlobReader to make a string representation and output it?

If it isn't an image or text, though, what could you possibly want to write to HTML?

查看更多
登录 后发表回答