hooks.py 文件源码

python
阅读 32 收藏 0 点赞 0 评论 0

项目:zenchmarks 作者: squeaky-pl 项目源码 文件源码
def before(action):
    """Decorator to execute the given action function *before* the responder.

    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.

            Note:
                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('Invalid ID',
                                                        'ID was not valid.')

                        params['answer'] = 42

    """

    def _before(responder_or_resource):
        if isinstance(responder_or_resource, six.class_types):
            resource = responder_or_resource

            for method in HTTP_METHODS:
                responder_name = 'on_' + method.lower()

                try:
                    responder = getattr(resource, responder_name)
                except AttributeError:
                    # resource does not implement this method
                    pass
                else:
                    # Usually expect a method, but any callable will do
                    if callable(responder):
                        # This pattern is necessary to capture the current
                        # value of responder in the do_before_all closure;
                        # otherwise, they will capture the same responder
                        # variable that is shared between iterations of the
                        # for loop, above.
                        def let(responder=responder):
                            do_before_all = _wrap_with_before(action, responder)

                            setattr(resource, responder_name, do_before_all)

                        let()

            return resource

        else:
            responder = responder_or_resource
            do_before_one = _wrap_with_before(action, responder)

            return do_before_one

    return _before
评论列表
文章目录


问题


面经


文章

微信
公众号

扫码关注公众号