Redis哈希-如何保存声音文件?

时间:2019-01-04 13:56:25

标签: python redis blob py-redis

有人可以告诉我如何在Redis中保存文件吗? 我希望能够执行以下操作:

 hmset 12345 sound_bytes <pathtofile/filename.mp3>

作为示例。

我使用的是python,因此需要使用python打开mp3文件,将其保存为我猜为(?)的字节数组,然后将该字节数组保存为redis。

我知道我可以像这样在python中打开文件:

with open(filename, 'rb') as fd:
    contents = fd.read()

但是,如果我想以某种方式在REDIS中保存“内容”,则当我稍后检索它以实际播放它或通过REST方法将其传递回去时,还有其他需要做的事情吗?我需要做什么才能让python“识别”为声音文件,而不仅仅是字符串?

我以前从未尝试过类似的方法,因此任何指针或陷阱都将不胜感激。

编辑1

到目前为止,这是我一直在玩的代码:

14 def sound_file_to_bytes(pathtofile):
15     try:
16         with open(pathtofile, 'rb') as fd:
17             contents = fd.read()
18             logging.info(contents)
19             fd.close()
20             return contents
21     except Exception as ex:
22         return "Error:", ex
23
24 def sound_as_bytes_to_db(soundbytes):
25     try:
26         logging.info('attempting to save sound bytes')
27         my_redis = redis.Redis(connection_pool=POOL)
28         response = my_redis.hmset('55555', 'greeting', soundbytes)
29         logging.info(response)
30         return True
31     except Exception as ex:
32         return False

通过日志,我可以看到文件的内容正在读入我的变量中。尝试转过头并写入数据库时​​没有出现任何错误,但是SET中“ greeting”键值的内容为空。 注意下面的redis输出:

127.0.0.1:6379[5]> hgetall 55555
1) "email1"
2) "johndoe@hotmail.com"
3) "email2"
4) "jd@yahoo.com"
5) "greeting"
6) ""
127.0.0.1:6379[5]>

编辑2

我发现了为什么没有将内容保存到数据库中的原因。 hmset命令存在语法问题。现在的代码如下:

  28         response = my_redis.hmset('55555',{'greeting':soundbytes})

0 个答案:

没有答案
相关问题