Safe and general serialization in Python

I want to (de) serialize simple objects in Python in a human readable format (like JSON). Data may come from an untrusted source. I really like how the Rust, serde library works:

#[derive(Serialize, Deserialize, Debug)]
struct Point {
    x: i32,
    y: i32,
}

fn main() {
    let point = Point { x: 1, y: 2 };

    // Convert the Point to a JSON string.
    let serialized = serde_json::to_string(&point).unwrap();

    // Prints serialized = {"x":1,"y":2}
    println!("serialized = {}", serialized);

    // Convert the JSON string back to a Point.
    let deserialized: Point = serde_json::from_str(&serialized).unwrap();

    // Prints deserialized = Point { x: 1, y: 2 }
    println!("deserialized = {:?}", deserialized);
}

I would like to achieve something similar in Python. Since Python is not statically typed, I expect the syntax to look something like this:

deserialized = library.loads(data_str, ClassName)

where ClassNameis the expected class.

  • jsonpickleBad, bad, bad. This does absolutely no sanitation, and its use leads to arbitrary code execution.
  • There serialization library: lima, marshmallow, kim, but they all require manual serialization schema definitions. This essentially leads to code duplication, which is bad.

-, , , Python?

EDIT: ,

+4
1

Python ,

  • .

, .

, : https://github.com/dimagi/jsonobject

:

import jsonobject


class Node(jsonobject.JsonObject):
    id = jsonobject.IntegerProperty(required=True)
    name = jsonobject.StringProperty(required=True)


class Transaction(jsonobject.JsonObject):
    provider = jsonobject.ObjectProperty(Node)
    requestor = jsonobject.ObjectProperty(Node)


req = Node(id=42, name="REQ")
prov = Node(id=24, name="PROV")

tx = Transaction(provider=prov, requestor=req)
js = tx.to_json()
tx2 = Transaction(js)
print(tx)
print(tx2)
0

Source: https://habr.com/ru/post/1684120/


All Articles