0

Each time user accesses http://www.example.com/some-random-symbols-1x1.png, I should return transparent image 1x1px. I've created according file, but how should I read it in my code to return to the user? I know how to display the image from the datastore or blobstore. But have no idea how to read and return binary file.

It can not be static file due to the following reasons:

  1. url will contain some-random-symbols;
  2. once url is accessed, prior to displaying images, I would like to log that somebody accessed the file.
4

2 回答 2

3

1x1 透明 PNG(或 GIF)足够小,您可以直接硬编码 base64 表示并通过self.response.write()(解码后)直接发出它。

每次从磁盘读取相对昂贵。如果你想走那条路,懒惰地初始化一个全局变量。

于 2012-10-23T19:24:30.087 回答
2

在更一般的情况下,我会使用 blobstore 和BlobstoreDownloadHandler,但对于一个绝对适合内存的小 gif ,像这样读取文件内容的东西:

with open('path/to/file.gif') as f:
  img_content = f.read()

我把它放在我的处理程序之外,所以每个实例都做一次。如果您使用的是 2.5,那么您需要从将来导入“with”,或者自己打开和关闭文件。

然后在您的处理程序中,假设 webapp2:

self.response.content_type = 'image/gif'
self.response.write(img_content)
于 2012-10-23T18:13:10.130 回答