Tipfy: How to display blob in template?

我们两清 提交于 2020-01-01 14:35:02

问题


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)?


回答1:


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?




回答2:


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==" />
    


来源:https://stackoverflow.com/questions/4763715/tipfy-how-to-display-blob-in-template

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!