Reputation: 20429
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:
Upvotes: 0
Views: 273
Reputation: 24966
A 1x1 transparent PNG (or GIF) is small enough that you can hard-code the base64 representation directly and emit it directly via self.response.write()
(after decoding).
Reading from disk every time is relatively expensive. If you want to go that route, lazily initialize a global variable.
Upvotes: 3
Reputation: 10360
In a more general case, I'd use the blobstore and the BlobstoreDownloadHandler, but for a tiny gif that will definitely fit into memory, something like this to read the file's content:
with open('path/to/file.gif') as f:
img_content = f.read()
I'd put this outside of my handler, so it was done once per instance. If you're using 2.5, then you'll need to import 'with' from future, or open and close the file yourself.
then in your handler, assuming webapp2:
self.response.content_type = 'image/gif'
self.response.write(img_content)
Upvotes: 2