File: app.py

package info (click to toggle)
python-trame 3.12.0-2
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 101,620 kB
  • sloc: python: 13,515; sh: 183; javascript: 93; makefile: 7
file content (66 lines) | stat: -rw-r--r-- 1,880 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
import time

from aiohttp import web

from trame.app import get_server
from trame.decorators import TrameApp, controller
from trame.ui.vuetify3 import SinglePageLayout
from trame.widgets import html
from trame.widgets import vuetify3 as v3


@TrameApp()
class App:
    def __init__(self, server=None):
        self.server = get_server(server, client_type="vue3")
        self.server.cli.add_argument("--session")
        self._build_ui()

        # Use CLI to know when used inside docker
        args, _ = self.server.cli.parse_known_args()
        session = args.session

        # simple default state
        self.state.response = {}
        self.state.session = session
        self.state.url = "/trame-endpoint"

        # Need to adjust URL when within docker
        if session:
            self.state.url = f"/api/{session}/trame-endpoint"

    @property
    def state(self):
        return self.server.state

    @controller.add("on_server_bind")
    def _bind_routes(self, wslink_server):
        wslink_server.app.add_routes(
            [web.get("/trame-endpoint", self.on_trame_endpoint)]
        )

    def on_trame_endpoint(self, request):
        return web.json_response({"url": self.state.url, "time": time.time()})

    def _build_ui(self):
        with SinglePageLayout(self.server) as layout:
            with layout.toolbar:
                v3.VSpacer()
                v3.VBtn(
                    "Make request",
                    click="utils.get('fetch')(url).then(v => v.json()).then(v => (response = v))",
                )
            with layout.content:
                html.Div("URL: {{ url }}")
                html.Div("Session: {{ session }}")
                html.Div("Response")
                html.Pre("{{ JSON.stringify(response, null, 2) }}")


def main():
    app = App()
    app.server.start()


if __name__ == "__main__":
    main()