28
loading...
This website collects cookies to deliver better user experience
foo
which takes an argument x
and return x * (x + x)
. Which I want to store inside a DB.def foo(x: float) -> float:
return x * (x + x)
pickle
. module.import pickle
byte_string = pickle.dumps(foo)
obj_string = f"{byte_string}"
from pysondb import db
a = db.getDb("test.json")
a.add({
"name": "foo_function",
"obj": obj_string
})
data = a.getBy({"name": "foo_function"})
data
will look something like this.[{'name': 'foo_function', 'obj': "b'\\x80\\x04\\x95\\x14\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x8c\\x08__main__\\x94\\x8c\\x03foo\\x94\\x93\\x94.'", 'id': 316182400052721056}]
str_obj = data[0]["obj"]
str_obj
is still a string and not a byte string, which is what we need, since the required byte string is inside this string, we can simply evaluate the string.import ast
byte_obj = ast.literal_eval(str_obj)
call_obj = pickle.loads(byte_obj)
print(call_obj(3))
# output
18
import ast
import pickle
from pysondb import db
def foo(x: float) -> float:
return x * (x + x)
byte_string = pickle.dumps(foo)
obj_string = f"{byte_string}"
a = db.getDb("test2.json")
a.add({
"name": "foo_function",
"obj": obj_string
})
data = a.getBy({"name": "foo_function"})
str_obj = data[0]["obj"]
byte_obj = ast.literal_eval(str_obj)
call_obj = pickle.loads(byte_obj)
print(call_obj(3))