summaryrefslogtreecommitdiff
path: root/oslo_middleware/base.py
blob: fd45d9a79fa7e65fc1fe4dc5d6f65a27192a1929 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
# Copyright 2011 OpenStack Foundation.
# All Rights Reserved.
#
#    Licensed under the Apache License, Version 2.0 (the "License"); you may
#    not use this file except in compliance with the License. You may obtain
#    a copy of the License at
#
#         http://www.apache.org/licenses/LICENSE-2.0
#
#    Unless required by applicable law or agreed to in writing, software
#    distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
#    WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
#    License for the specific language governing permissions and limitations
#    under the License.

"""Base class(es) for WSGI Middleware."""

from inspect import getargspec
import webob.dec

from oslo_config import cfg


class ConfigurableMiddleware(object):
    """Base WSGI middleware wrapper.

    These classes require an application to be initialized that will be called
    next.  By default the middleware will simply call its wrapped app, or you
    can override __call__ to customize its behavior.
    """

    @classmethod
    def factory(cls, global_conf, **local_conf):
        """Factory method for paste.deploy."""
        conf = global_conf.copy() if global_conf else {}
        conf.update(local_conf)

        def middleware_filter(app):
            return cls(app, conf)

        return middleware_filter

    def __init__(self, application, conf=None):
        """Base middleware constructor

        :param  conf: a dict of options or a cfg.ConfigOpts object
        """
        self.application = application

        # NOTE(sileht): If the configuration come from oslo.config
        # just use it.
        if isinstance(conf, cfg.ConfigOpts):
            self.conf = {}
            self.oslo_conf = conf
        else:
            self.conf = conf or {}
            if "oslo_config_project" in self.conf:
                if 'oslo_config_file' in self.conf:
                    default_config_files = [self.conf['oslo_config_file']]
                else:
                    default_config_files = None
                self.oslo_conf = cfg.ConfigOpts()
                self.oslo_conf([], project=self.conf['oslo_config_project'],
                               default_config_files=default_config_files,
                               validate_default_values=True)

            else:
                # Fallback to global object
                self.oslo_conf = cfg.CONF

    def _conf_get(self, key, group="oslo_middleware"):
        if key in self.conf:
            # Validate value type
            self.oslo_conf.set_override(key, self.conf[key], group=group,
                                        enforce_type=True)
        return getattr(getattr(self.oslo_conf, group), key)

    @staticmethod
    def process_request(req):
        """Called on each request.

        If this returns None, the next application down the stack will be
        executed. If it returns a response then that response will be returned
        and execution will stop here.
        """
        return None

    @staticmethod
    def process_response(response, request=None):
        """Do whatever you'd like to the response."""
        return response

    @webob.dec.wsgify
    def __call__(self, req):
        response = self.process_request(req)
        if response:
            return response
        response = req.get_response(self.application)

        (args, varargs, varkw, defaults) = getargspec(self.process_response)
        if 'request' in args:
            return self.process_response(response, request=req)
        return self.process_response(response)


class Middleware(ConfigurableMiddleware):
    """Legacy base WSGI middleware wrapper.

    Legacy interface that doesn't pass configuration options
    to the middleware when it's loaded via paste.deploy.
    """

    @classmethod
    def factory(cls, global_conf, **local_conf):
        """Factory method for paste.deploy."""
        return cls