Search code examples
pythonpython-3.xtornado

Tornado send and receive bytes


I'm writing a response in tornado of a string of bytes from an opened jpg file that go something like this:

b'\xff\xd8\xff\xe0\x00\x10JFIF\x00\x01\x01\x00\x00\x01\x00\x01\x00\x00\xff\xdb\x00C\x00\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\...

When I receive the bytes with res = requests.get(url).text, I get something like this:

����JFIF��C��C����  
���
��א�I+���`��;��oI�JU����J+��Uq̧[�}�ĥ�%��6A�}~�����mKD�#�
                                                       w,ޓW�t@~�?��TF�F������򿦺G�����N"���b��

When I try to escape it:

piece = tornado.escape.utf8(res)
OR
piece = res.encode()

I get a byte string, but it is not the same as what was sent:

b'\xef\xbf\xbd\xef\xbf\xbd\xef\xbf\xbd\xef\xbf\xbd\x00\x10JFIF\x00\x01\x01\x00\x00\x01\x00\x01\x00\x00\xef\xbf\xbd\xef\xbf\xbd\x00C\x00\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x02\x02\x02\...

This is how I am opening the original jpg:

with open('file.jpg', 'rb') as f:
    content = f.read()
    # Split content into multiple parts and send each part

How can I send and receive a series of bytes with tornado?


Solution

  • res = requests.get(url).text
    

    You are trying to read the received JPEG file as a text file.

    You need to use content attribute to get the data in bytes:

    res = requests.get(url).content