Mercurial > libervia-web
comparison libervia/pages/_browser/bridge.py @ 1297:999dccf0093e
browser: new bridge module to access restricted bridge from browser
author | Goffi <goffi@goffi.org> |
---|---|
date | Fri, 19 Jun 2020 16:47:51 +0200 |
parents | |
children | 8998f01088ac |
comparison
equal
deleted
inserted
replaced
1296:b1215347b5c3 | 1297:999dccf0093e |
---|---|
1 from browser import window | |
2 import javascript | |
3 | |
4 | |
5 class Bridge: | |
6 | |
7 def __getattr__(self, attr): | |
8 return lambda *args, **kwargs: self.call(attr, *args, **kwargs) | |
9 | |
10 def on_load(self, xhr, ev, callback, errback): | |
11 if xhr.status == 200: | |
12 ret = javascript.JSON.parse(xhr.response) | |
13 if ret is None: | |
14 callback() | |
15 else: | |
16 callback(ret) | |
17 elif xhr.status == 502: | |
18 # PROXY_ERROR is used for bridge error | |
19 ret = javascript.JSON.parse(xhr.response) | |
20 errback(ret) | |
21 else: | |
22 print(f"bridge called failed: code: {xhr.response}, text: {xhr.statusText}") | |
23 errback({"fullname": "InternalError", "message": xhr.statusText}) | |
24 | |
25 def call(self, method_name, *args, callback, errback, **kwargs): | |
26 xhr = window.XMLHttpRequest.new() | |
27 xhr.bind('load', lambda ev: self.on_load(xhr, ev, callback, errback)) | |
28 xhr.bind('error', lambda ev: errback( | |
29 {"fullname": "ConnectionError", "message": xhr.statusText})) | |
30 xhr.open("POST", f"/_bridge/{method_name}", True) | |
31 data = javascript.JSON.stringify({ | |
32 "args": args, | |
33 "kwargs": kwargs, | |
34 }) | |
35 xhr.setRequestHeader('X-Csrf-Token', window.csrf_token) | |
36 xhr.send(data) |