Coverage for gws-app/gws/plugin/template/py/__init__.py: 0%
33 statements
« prev ^ index » next coverage.py v7.8.0, created at 2025-04-17 01:37 +0200
« prev ^ index » next coverage.py v7.8.0, created at 2025-04-17 01:37 +0200
1"""Pure python templates.
3A template is a python module. This module must provide a function called ``main``,
4which receives the arguments object and returns a :obj:`gws.Response` object.
5"""
7from typing import Optional
9import gws
10import gws.base.template
12gws.ext.new.template('py')
15class Config(gws.base.template.Config):
16 """Python template"""
18 path: Optional[gws.FilePath]
19 """path to a template file"""
22class Props(gws.base.template.Props):
23 pass
26_ENTRYPOINT_NAME = 'main'
29class Object(gws.base.template.Object):
30 path: str
32 def configure(self):
33 self.path = self.cfg('path')
34 self.compile()
36 def render(self, tri):
37 self.notify(tri, 'begin_print')
39 args = self.prepare_args(tri)
40 entrypoint = self.compile()
42 try:
43 res = entrypoint(args)
44 except Exception as exc:
45 # @TODO stack traces with the filename
46 raise gws.Error(f'py error: {exc!r} path={self.path!r}') from exc
48 self.notify(tri, 'end_print')
49 return res
51 def compile(self):
52 text = gws.u.read_file(self.path)
53 try:
54 g = {}
55 exec(text, g)
56 return g[_ENTRYPOINT_NAME]
57 except Exception as exc:
58 raise gws.Error(f'py load error: {exc!r} in {self.path!r}') from exc