我正在尝试将图像存储在redis中并检索它并将其发送到HTML模板。我能够缓存图像,但我不知道如何检索图像并将其发送到HTML模板。这是我的代码中执行缓存和检索的部分。
from urllib2 import Request, urlopen
import json
import redis
import urlparse
import os
from StringIO import StringIO
import requests
from PIL import Image
from flask import send_file
REDIS_URL = urlparse.urlparse(os.environ.get('REDISCLOUD_URL', 'redis://:@localhost:6379/'))
r = redis.StrictRedis(
host=REDIS_URL.hostname, port=REDIS_URL.port,
password=REDIS_URL.password)
class MovieInfo(object):
def __init__(self, movie):
self.movie_name = movie.replace(" ", "+")
def get_movie_info(self):
url = 'http://www.omdbapi.com/?t=' + self.movie_name + '&y=&plot=short&r=json'
result = Request(url)
response = urlopen(result)
infoFromJson = json.loads(response.read())
self._cache_image(infoFromJson)
return infoFromJson
def _cache_image(self, infoFromJson):
key = "{}".format(infoFromJson['Title'])
# Open redis.
cached = r.get(key)
if not cached:
response = requests.get(infoFromJson['Poster'])
image = Image.open(StringIO(response.content))
r.setex(key, (60*60*5), image)
return True
def get_image(self, key):
cached = r.get(key)
if cached:
image = StringIO(cached)
image.seek(0)
return send_file(image, mimetype='image/jpg')
if __name__ == '__main__':
M = MovieInfo("Furious 7")
M.get_movie_info()
M.get_image("Furious 7")
检索部分的任何帮助都会有所帮助。还有什么是将图像文件从缓存发送到Flask中的HTML模板的最佳方式。
答案 0 :(得分:1)
你在Redis中保存的是一个字符串,
有点喜欢:'<PIL.JpegImagePlugin.JpegImageFile image mode=RGB size=300x475 at 0x4874090>'
。
response.content
是rawData。 使用 Image.frombytes()
来获取Image对象。
点击此处:Doc
您无法在Redis中创建嵌套结构,这意味着您无法使用 示例)将本机redis列表存储在本机redis哈希映射中。
如果你真的需要嵌套结构,你可能只想存储一个 相反,JSON-blob(或类似的东西)。另一个选择是存储 一个&#34; id&#34; /键到另一个redis对象作为map键的值, 但这需要多次调用服务器才能获得完整的对象。
试试这个:
response = requests.get(infoFromJson['Poster'])
# Create a string buffer then set it raw data in redis.
output = StringIO(response.content)
r.setex(key, (60*60*5), output.getvalue())
output.close()