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

1"""Pure python templates. 

2 

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""" 

6 

7from typing import Optional 

8 

9import gws 

10import gws.base.template 

11 

12gws.ext.new.template('py') 

13 

14 

15class Config(gws.base.template.Config): 

16 """Python template""" 

17 

18 path: Optional[gws.FilePath] 

19 """path to a template file""" 

20 

21 

22class Props(gws.base.template.Props): 

23 pass 

24 

25 

26_ENTRYPOINT_NAME = 'main' 

27 

28 

29class Object(gws.base.template.Object): 

30 path: str 

31 

32 def configure(self): 

33 self.path = self.cfg('path') 

34 self.compile() 

35 

36 def render(self, tri): 

37 self.notify(tri, 'begin_print') 

38 

39 args = self.prepare_args(tri) 

40 entrypoint = self.compile() 

41 

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 

47 

48 self.notify(tri, 'end_print') 

49 return res 

50 

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