File: hooks.py

package info (click to toggle)
python-falcon 4.0.2-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 5,172 kB
  • sloc: python: 33,608; javascript: 92; sh: 50; makefile: 50
file content (361 lines) | stat: -rw-r--r-- 12,040 bytes parent folder | download
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
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
# Copyright 2013 by Rackspace Hosting, Inc.
#
# 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.

"""Hook decorators."""

from __future__ import annotations

from functools import wraps
from inspect import getmembers
from inspect import iscoroutinefunction
import re
from typing import (
    Any,
    Awaitable,
    Callable,
    cast,
    Dict,
    List,
    Protocol,
    Tuple,
    TYPE_CHECKING,
    TypeVar,
    Union,
)

from falcon.constants import COMBINED_METHODS
from falcon.util.misc import get_argnames
from falcon.util.sync import _wrap_non_coroutine_unsafe

if TYPE_CHECKING:
    import falcon as wsgi
    from falcon import asgi
    from falcon._typing import AsgiResponderMethod
    from falcon._typing import Resource
    from falcon._typing import Responder
    from falcon._typing import ResponderMethod


# TODO: when targeting only 3.10+ these protocol would no longer be needed, since
# ParamSpec could be used together with Concatenate to use a simple Callable
# to type the before and after functions. This approach was prototyped in
# https://github.com/falconry/falcon/pull/2234
class SyncBeforeFn(Protocol):
    def __call__(
        self,
        req: wsgi.Request,
        resp: wsgi.Response,
        resource: Resource,
        params: Dict[str, Any],
        *args: Any,
        **kwargs: Any,
    ) -> None: ...


class AsyncBeforeFn(Protocol):
    def __call__(
        self,
        req: asgi.Request,
        resp: asgi.Response,
        resource: Resource,
        params: Dict[str, Any],
        *args: Any,
        **kwargs: Any,
    ) -> Awaitable[None]: ...


BeforeFn = Union[SyncBeforeFn, AsyncBeforeFn]


class SyncAfterFn(Protocol):
    def __call__(
        self,
        req: wsgi.Request,
        resp: wsgi.Response,
        resource: Resource,
        *args: Any,
        **kwargs: Any,
    ) -> None: ...


class AsyncAfterFn(Protocol):
    def __call__(
        self,
        req: asgi.Request,
        resp: asgi.Response,
        resource: Resource,
        *args: Any,
        **kwargs: Any,
    ) -> Awaitable[None]: ...


AfterFn = Union[SyncAfterFn, AsyncAfterFn]
_R = TypeVar('_R', bound=Union['Responder', 'Resource'])


_DECORABLE_METHOD_NAME = re.compile(
    r'^on_({})(_\w+)?$'.format('|'.join(method.lower() for method in COMBINED_METHODS))
)


def before(action: BeforeFn, *args: Any, **kwargs: Any) -> Callable[[_R], _R]:
    """Execute the given action function *before* the responder.

    The `params` argument that is passed to the hook
    contains only the fields from the URI template path; it does not
    include query string values.

    Hooks may inject extra params as needed. For example::

        def do_something(req, resp, resource, params):
            try:
                params['id'] = int(params['id'])
            except ValueError:
                raise falcon.HTTPBadRequest(title='Invalid ID',
                                            description='ID was not valid.')

            params['answer'] = 42

    Args:
        action (callable): A function of the form
            ``func(req, resp, resource, params)``, where `resource` is a
            reference to the resource class instance associated with the
            request and `params` is a dict of URI template field names,
            if any, that will be passed into the resource responder as
            kwargs.

        *args: Any additional arguments will be passed to *action* in the
            order given, immediately following the *req*, *resp*, *resource*,
            and *params* arguments.

    Keyword Args:
        **kwargs: Any additional keyword arguments will be passed through to
            *action*.
    """

    def _before(responder_or_resource: _R) -> _R:
        if isinstance(responder_or_resource, type):
            for responder_name, responder in getmembers(
                responder_or_resource, callable
            ):
                if _DECORABLE_METHOD_NAME.match(responder_name):
                    responder = cast('Responder', responder)
                    do_before_all = _wrap_with_before(responder, action, args, kwargs)

                    setattr(responder_or_resource, responder_name, do_before_all)

            return cast(_R, responder_or_resource)

        else:
            responder = cast('Responder', responder_or_resource)
            do_before_one = _wrap_with_before(responder, action, args, kwargs)

            return cast(_R, do_before_one)

    return _before


def after(action: AfterFn, *args: Any, **kwargs: Any) -> Callable[[_R], _R]:
    """Execute the given action function *after* the responder.

    Args:
        action (callable): A function of the form
            ``func(req, resp, resource)``, where `resource` is a
            reference to the resource class instance associated with the
            request

        *args: Any additional arguments will be passed to *action* in the
            order given, immediately following the *req*, *resp* and *resource*
            arguments.

    Keyword Args:
        **kwargs: Any additional keyword arguments will be passed through to
            *action*.
    """

    def _after(responder_or_resource: _R) -> _R:
        if isinstance(responder_or_resource, type):
            for responder_name, responder in getmembers(
                responder_or_resource, callable
            ):
                if _DECORABLE_METHOD_NAME.match(responder_name):
                    responder = cast('Responder', responder)
                    do_after_all = _wrap_with_after(responder, action, args, kwargs)

                    setattr(responder_or_resource, responder_name, do_after_all)

            return cast(_R, responder_or_resource)

        else:
            responder = cast('Responder', responder_or_resource)
            do_after_one = _wrap_with_after(responder, action, args, kwargs)

            return cast(_R, do_after_one)

    return _after


# -----------------------------------------------------------------------------
# Helpers
# -----------------------------------------------------------------------------


def _wrap_with_after(
    responder: Responder, action: AfterFn, action_args: Any, action_kwargs: Any
) -> Responder:
    """Execute the given action function after a responder method.

    Args:
        responder: The responder method to wrap.
        action: A function with a signature similar to a resource responder
            method, taking the form ``func(req, resp, resource)``.
        action_args: Additional positional arguments to pass to *action*.
        action_kwargs: Additional keyword arguments to pass to *action*.
    """

    responder_argnames = get_argnames(responder)
    extra_argnames = responder_argnames[2:]  # Skip req, resp
    do_after_responder: Responder

    if iscoroutinefunction(responder):
        async_action = cast('AsyncAfterFn', _wrap_non_coroutine_unsafe(action))
        async_responder = cast('AsgiResponderMethod', responder)

        @wraps(async_responder)
        async def do_after(
            self: Resource,
            req: asgi.Request,
            resp: asgi.Response,
            *args: Any,
            **kwargs: Any,
        ) -> None:
            if args:
                _merge_responder_args(args, kwargs, extra_argnames)

            await async_responder(self, req, resp, **kwargs)
            await async_action(req, resp, self, *action_args, **action_kwargs)

        do_after_responder = cast('AsgiResponderMethod', do_after)
    else:
        sync_action = cast('SyncAfterFn', action)
        sync_responder = cast('ResponderMethod', responder)

        @wraps(sync_responder)
        def do_after(
            self: Resource,
            req: wsgi.Request,
            resp: wsgi.Response,
            *args: Any,
            **kwargs: Any,
        ) -> None:
            if args:
                _merge_responder_args(args, kwargs, extra_argnames)

            sync_responder(self, req, resp, **kwargs)
            sync_action(req, resp, self, *action_args, **action_kwargs)

        do_after_responder = cast('ResponderMethod', do_after)
    return do_after_responder


def _wrap_with_before(
    responder: Responder,
    action: BeforeFn,
    action_args: Tuple[Any, ...],
    action_kwargs: Dict[str, Any],
) -> Responder:
    """Execute the given action function before a responder method.

    Args:
        responder: The responder method to wrap.
        action: A function with a similar signature to a resource responder
            method, taking the form ``func(req, resp, resource, params)``.
        action_args: Additional positional arguments to pass to *action*.
        action_kwargs: Additional keyword arguments to pass to *action*.
    """

    responder_argnames = get_argnames(responder)
    extra_argnames = responder_argnames[2:]  # Skip req, resp
    do_before_responder: Responder

    if iscoroutinefunction(responder):
        async_action = cast('AsyncBeforeFn', _wrap_non_coroutine_unsafe(action))
        async_responder = cast('AsgiResponderMethod', responder)

        @wraps(async_responder)
        async def do_before(
            self: Resource,
            req: asgi.Request,
            resp: asgi.Response,
            *args: Any,
            **kwargs: Any,
        ) -> None:
            if args:
                _merge_responder_args(args, kwargs, extra_argnames)

            await async_action(req, resp, self, kwargs, *action_args, **action_kwargs)
            await async_responder(self, req, resp, **kwargs)

        do_before_responder = cast('AsgiResponderMethod', do_before)
    else:
        sync_action = cast('SyncBeforeFn', action)
        sync_responder = cast('ResponderMethod', responder)

        @wraps(sync_responder)
        def do_before(
            self: Resource,
            req: wsgi.Request,
            resp: wsgi.Response,
            *args: Any,
            **kwargs: Any,
        ) -> None:
            if args:
                _merge_responder_args(args, kwargs, extra_argnames)

            sync_action(req, resp, self, kwargs, *action_args, **action_kwargs)
            sync_responder(self, req, resp, **kwargs)

        do_before_responder = cast('ResponderMethod', do_before)
    return do_before_responder


def _merge_responder_args(
    args: Tuple[Any, ...], kwargs: Dict[str, Any], argnames: List[str]
) -> None:
    """Merge responder args into kwargs.

    The framework always passes extra args as keyword arguments.
    However, when the app calls the responder directly, it might use
    positional arguments instead, so we need to handle that case. This
    might happen, for example, when overriding a resource and calling
    a responder via super().

    Args:
        args (tuple): Extra args passed into the responder
        kwargs (dict): Keyword args passed into the responder
        argnames (list): Extra argnames from the responder's
            signature, ordered as defined
    """

    # NOTE(kgriffs): Merge positional args into kwargs by matching
    # them up to the responder's signature. To do that, we must
    # find out the names of the positional arguments by matching
    # them in the order of the arguments named in the responder's
    # signature.
    for i, argname in enumerate(argnames):
        # NOTE(kgriffs): extra_argnames may contain keyword arguments,
        # which won't be in the args list, and are already in the kwargs
        # dict anyway, so detect and skip them.
        if argname not in kwargs:
            kwargs[argname] = args[i]