user6142029
user6142029

Reputation:

Best way to transfer type and value using pickle

I have type and value parameters that I want send from client to server using pickle. I am wondering what will be the best, and most conventional way to do this (The data should be sent from client to server).

The options I thought about:

tuple:

(type, value)

dictionary:

{type:value}

class:

class request(object):
    def __init__(self, request_type, value):
        self.typ = request_type
        self.value = value

Upvotes: 0

Views: 123

Answers (1)

sudo
sudo

Reputation: 5804

APIs in general seem to prefer the "named parameter" approach that you'd use a dictionary for, not the tuple approach. This tends to work more easily with either end and makes human errors less likely.

Without knowing what type is exactly, there are a couple of options:

{ type: value } # if type is a parameter name
{ "request": type, "parameter_name": value } # if type is a request type, and you've got one or more values with parameter names

You'd do the first one only if the request type is somehow otherwise indicated. Like if this is over HTTP, you use the URL endpoint to indicate that, e.g. "http://my_server/login" for a login request. If you're doing this directly on top of L4 (say TCP), you do something like the second one to indicate the request type.

Neither of these are necessarily the most space-efficient solution. You'd use something like Protobuf if that's a concern. But many public web APIs just use JSON with these parameter names as keys since that's easier for general users.

I see you don't care since it's educational only, but for others reading, you shouldn't do this in Pickle. JSON would be a better approach and is equally easy in Python as long as you're only sending the supported data types (strings, numbers, lists, dicts, bools, a few others).

Upvotes: 1

Related Questions