Hide keyboard shortcuts

Hot-keys on this page

r m x p   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

1""" Collections of extra pieces to help smooth over community divergence. """ 

2 

3from .widgets import Widget 

4 

5 

6class TGStyleController(Widget): 

7 """ A widget mixin that provides more advanced controller routing and 

8 dispatching. 

9 

10 The need for this mainly sprung from a divergence of source trees 

11 (unintentionally forking) between the developers of tw2 while it was still 

12 alpha/beta. One team expected users to define controllers as a 'request' 

13 classmethod on the widget and another team expected users to define a 

14 Controller class as a child of the widget. Team A's pattern is now the 

15 default in the main tree. This is a shim to support Team B's approach. 

16 

17 Use it like this: 

18 

19 >>> import tw2.core 

20 >>> class MyWidget(tw2.core.TGStyleController, tw2.core.Widget): 

21 ... class Controller(object): 

22 ... @jsonify 

23 ... def some_method(self, req): 

24 ... return dict(foo="bar") 

25 

26 """ 

27 

28 @classmethod 

29 def dispatch(cls, req, controller): 

30 path = req.path_info.strip('/').split('/')[2:] 

31 if len(path) == 0: 

32 method_name = 'index' 

33 else: 

34 method_name = path[0] 

35 # later we want to better handle .ext conditions, but hey 

36 # this aint TG 

37 if method_name.endswith('.json'): 

38 method_name = method_name[:-5] 

39 method = getattr(controller, method_name, None) 

40 if not method: 

41 method = getattr(controller, 'default', None) 

42 return method 

43 

44 @classmethod 

45 def request(cls, req): 

46 """ 

47 Override this method to define your own way of handling a widget 

48 request. 

49 

50 The default does TG-style object dispatch. 

51 """ 

52 

53 authn = cls.attrs.get('_check_authn') 

54 authz = cls.attrs.get('_check_authz') 

55 

56 if authn and not authn(req): 

57 return util.abort(req, 401) 

58 

59 controller = cls.attrs.get('controller', cls.Controller) 

60 if controller is None: 

61 return util.abort(req, 404) 

62 

63 method = cls.dispatch(req, controller) 

64 if method: 

65 if authz and not authz(req, method): 

66 return util.abort(req, 403) 

67 

68 controller = cls.Controller() 

69 return method(controller, req) 

70 return util.abort(req, 404)