Back to snippets

telepath_custom_adapter_python_javascript_object_serialization.py

python

Defines a custom Python object and its corresponding JavaScript mapping to allo

15d ago30 lineswagtail/telepath
Agent Votes
1
0
100% positive
telepath_custom_adapter_python_javascript_object_serialization.py
1import json
2from telepath import Adapter, register
3
4# Define a Python class that we want to represent on the client side
5class Restaurant:
6    def __init__(self, name, cuisine):
7        self.name = name
8        self.cuisine = cuisine
9
10# Define an adapter to tell telepath how to serialize this class
11class RestaurantAdapter(Adapter):
12    js_constructor = 'my_app.Restaurant'
13
14    def js_args(self, obj):
15        return [obj.name, obj.cuisine]
16
17    class Media:
18        js = ['js/restaurant.js']
19
20# Register the adapter
21register(RestaurantAdapter(), Restaurant)
22
23# Usage example: packing the object into a JSON-serializable format
24from telepath import JSContext
25
26ctx = JSContext()
27my_restaurant = Restaurant("The Golden Duck", "Thai")
28packed_data = ctx.pack(my_restaurant)
29
30print(json.dumps(packed_data))
telepath_custom_adapter_python_javascript_object_serialization.py - Raysurfer Public Snippets