1

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) "johndoe@hotmail.com"
3) "email2"
4) "jd@yahoo.com"
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})
dot
  • 14,928
  • 41
  • 110
  • 218
  • 2
    Just as an aside and to help testing... you can put an MP3 file into **Redis** just from the Terminal with `redis-cli -x hmset 12345 sound < track.mp3` and read it back with `redis-cli hmget 12345 sound > returned.mp3` – Mark Setchell Jan 04 '19 at 15:03
  • 1
    @MarkSetchell that's very helpful!! thank you!!! I'll give that a try – dot Jan 04 '19 at 15:04
  • @MarkSetchell I try executing the above commands from command line and it looks like the file is corrupted when I tried to get the audio file back. I tried this with the .wav file format. Does it work for anyone? – Bharath Sep 09 '19 at 05:08
  • @Bharath Try putting 3-4 different files in, and getting them out again and seeing if the lengths you get are always the same and how they differ from the file you put in. – Mark Setchell Sep 09 '19 at 06:17

0 Answers0