comparison libervia/pages/_browser/aio_bridge.py @ 1347:48e2a8b07c0b

browser: async version of bridge
author Goffi <goffi@goffi.org>
date Sat, 05 Sep 2020 21:59:11 +0200
parents
children 72f9639594b2
comparison
equal deleted inserted replaced
1346:cda5537c71d6 1347:48e2a8b07c0b
1 from browser import window, aio
2 import javascript
3
4
5 class BridgeException(Exception):
6 """An exception which has been raised from the backend and arrived to the frontend."""
7
8 def __init__(self, name, message="", condition=""):
9 """
10
11 @param name (str): full exception class name (with module)
12 @param message (str): error message
13 @param condition (str) : error condition
14 """
15 Exception.__init__(self)
16 self.fullname = str(name)
17 self.message = str(message)
18 self.condition = str(condition) if condition else ""
19 self.module, __, self.classname = str(self.fullname).rpartition(".")
20
21 def __str__(self):
22 message = (": %s" % self.message) if self.message else ""
23 return self.classname + message
24
25 def __eq__(self, other):
26 return self.classname == other
27
28
29 class Bridge:
30
31 def __getattr__(self, attr):
32 return lambda *args, **kwargs: self.call(attr, *args, **kwargs)
33
34 async def call(self, method_name, *args, **kwargs):
35 data = javascript.JSON.stringify({
36 "args": args,
37 "kwargs": kwargs,
38 })
39 url = f"/_bridge/{method_name}"
40 r = await aio.post(
41 url,
42 headers={
43 'X-Csrf-Token': window.csrf_token,
44 },
45 data=data,
46 )
47
48 if r.status == 200:
49 return javascript.JSON.parse(r.data)
50 elif r.status == 502:
51 ret = javascript.JSON.parse(r.data)
52 raise BridgeException(ret['fullname'], ret['message'], ret['condition'])
53 else:
54 print(f"bridge called failed: code: {r.status}, text: {r.statusText}")
55 raise BridgeException("InternalError", r.statusText)