root / trunk / twisted / web2 / plugin.py

Revision 15171, 1.7 kB (checked in by dreid, 4 years ago)

merge dreid/remove-context

Line 
1 # -*- test-case-name: twisted.web2.test.test_plugin -*-
2 # Copyright (c) 2001-2004 Twisted Matrix Laboratories.
3 # See LICENSE for details.
4
5 """I'm a set of utility functions and resources for using twisted.plugins
6 to locate resources.
7
8 Example Usage:
9 root.putChild('test', resourcePlugger('TestResource'))
10 """
11
12 from twisted.web2 import resource, http, iweb
13 from twisted.plugin import getPlugins
14 from twisted.python.reflect import namedClass
15
16 class PluginResource(resource.Resource):
17     def __init__(self, *args, **kwargs):
18         """A plugin resource atleast has to accept any arguments given to it,
19         but it doesn't have to do anything with it, this is dumb I know.
20         """
21         pass
22
23
24 class TestResource(PluginResource, resource.LeafResource):
25     def __init__(self, foo=None, bar=None):
26         self.foo = foo
27         self.bar = bar
28
29     def locateChild(self, req, segments):
30         return resource.LeafResource.locateChild(self, req, segments)
31
32     def render(self, req):
33         return http.Response(200, stream="I am a very simple resource, a pluggable resource too")
34
35
36 class NoPlugin(resource.LeafResource):
37     def __init__(self, plugin):
38         self.plugin = plugin
39        
40     def render(self, req):
41         return http.Response(404, stream="No Such Plugin %s" % self.plugin)
42
43
44 def resourcePlugger(name, *args, **kwargs):
45     resrcClass = None
46
47     for p in getPlugins(iweb.IResource):
48         if p.name == name:
49             resrcClass = namedClass(p.className)
50             break
51
52     if resrcClass is None:
53         resrcClass = kwargs.get('defaultResource', None)
54         if resrcClass is None:
55             return NoPlugin(name)
56        
57         del kwargs['defaultResource']
58
59     return resrcClass(*args, **kwargs)
Note: See TracBrowser for help on using the browser.