root/trunk/twisted/web2/plugin.py

Revision 15171, 1.7 KB (checked in by dreid, 5 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
6to locate resources.
7
8Example Usage:
9root.putChild('test', resourcePlugger('TestResource'))
10"""
11
12from twisted.web2 import resource, http, iweb
13from twisted.plugin import getPlugins
14from twisted.python.reflect import namedClass
15
16class 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
24class 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
36class 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
44def 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.