redis hash - how to save a sound file?

1.3k Views Asked by At

Can someone tell me how to save a file in redis? I'd like to be able to do something like:

 hmset 12345 sound_bytes <pathtofile/filename.mp3>

as an example.

I'm using python and so will need to open the mp3 file using python, save it as a byte array I guess (?) and then save that byte array into redis.

I know I can open a file like so in python:

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

But if i were to somehow save "contents" in REDIS, when I retrieve it later on to actually play it or pass it back via a REST method, is there anything else that needs doing? What do I need to do to have python "recognize" this as a sound file and not just a string?

I've never tried something like this before, so any pointers or gotchas would be appreciated.

EDIT 1

So far, this is the code I've been playing around with:

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

Through the log, I can see that the contents of the file is being read into my variable. I don't get any errors when I try to turn around and write to the database, but the contents of the value of the 'greeting' key in my SET is empty. Notice the redis output below:

127.0.0.1:6379[5]> hgetall 55555
1) "email1"
2) "[email protected]"
3) "email2"
4) "[email protected]"
5) "greeting"
6) ""
127.0.0.1:6379[5]>

EDIT 2

I found out why it wasn't saving the contents to the database. I had syntax problem with the hmset command. now the code looks like this:

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

There are 0 best solutions below