Ruslan Osipov
Ruslan Osipov

Reputation: 5843

Organize data sent between client-server

Pardon me if this has been addressed before, but how do I organize data exchanged between client and server in python application (sockets)?

Let's say I have some elements I have to send - strings, tuples, dicts:

"hello world", (1, 2, 3), {"k": "v"}

What I currently do is I simply convert everything to string - call repr() before sending and eval() after receiving. This obviously seem a bit redundant.

How should I send these chunks of data? Is there a convention? Preferred format? How do I compress it?

Upvotes: 0

Views: 127

Answers (3)

schesis
schesis

Reputation: 59148

You should never eval() data from an untrusted source, which means you should never eval() anything arriving over an unsecured network connection (or where you can't be absolutely certain the entity at the other end is who or what it says it is).

The obvious solution here is to encode the data as JSON at one end, and decode it at the other (unless you have specific performance requirements that require a highly-compressed format like e.g msgpack).

Upvotes: 1

sdamashek
sdamashek

Reputation: 628

JSON is what you're looking for. If you have an object and you import the JSON functions:

from json import dumps, loads

you can use dumps(obj) to encode into JSON and loads(str) to convert a JSON string back to an object. For example:

dumps([[1,2,3],{"a":"b", "c":"d"}])

yields '[[1, 2, 3], {"a": "b", "c": "d"}]' and

loads('[[1, 2, 3], {"a": "b", "c": "d"}]')

yields [[1, 2, 3], {u'a': u'b', u'c': u'd'}].

Upvotes: 3

Jonathan
Jonathan

Reputation: 2845

The easiest way is to pickle them on the client side and unpickle them on the server side. However, to need to ensure that the data is coming from a trusted source as it is possible to force unpickle to execute arbitrary code. Make sure you use cPickle to get the C language implementation.

Upvotes: 1

Related Questions