Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python sending dictionary through TCP

I'm a python beginner, and I'm curious how can I send a dictionary through TCP

like image 230
OHLÁLÁ Avatar asked Jun 14 '11 09:06

OHLÁLÁ


3 Answers

You should serialize it with pickle:

import pickle
dict = {...}
tcp_send(pickle.dumps(dict))

And on the other end:

import pickle
dict = pickle.loads(tcp_recieve())

If the other end is not written in python, you can use a data serialization format, like xml, json or yaml.

like image 141
Gabi Purcaru Avatar answered Nov 01 '22 03:11

Gabi Purcaru


You can use pickle to convert any Python object (including a dictionary) to a byte stream, which can then be sent over TCP and un-pickled on the receiving end.

Alternatively, you can use json, which isn't dependent on the receiving end being a Python client.

like image 21
Sebastian Paaske Tørholm Avatar answered Nov 01 '22 01:11

Sebastian Paaske Tørholm


Pickle is considered insecure for sending data structures across connections as the object can never be trustfully reconstructed. This is why yaml, json or any other format is considered preferable.

like image 33
Jakob Bowyer Avatar answered Nov 01 '22 02:11

Jakob Bowyer