utils.py 文件源码

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

项目:osp-api 作者: opensyllabus 项目源码 文件源码
def add_mocks_to_method(self, resource_method):
        """Resource method decorator which supplies a mock
        response if a client specifies `mock=True`.

        Please see `osp_api.mocks`. A naming convention is used
        to automatically find and use the appropriate mock as a
        response.

        Warning:
            Mocks bypass any authentication (and possibly
            other decorators, too!).

        """

        resource_class_name, resource_type = self.resource_method_info(
            resource_method,
        )
        if resource_type == ResourceType.collection:
            index_before_suffix = -10
            mock_suffix = '_collection'
        elif resource_type == ResourceType.singleton:
            index_before_suffix = -9
            mock_suffix = '_singleton'

        # Get the "resource name," e.g., "TopWorksCollection" becomes
        # "top-works_collection."
        resource_name = ''
        for i, letter in enumerate(resource_class_name[:index_before_suffix]):
            if i == 0:
                resource_name += letter.lower()
            elif letter.isupper():
                resource_name += '-' + letter.lower()
            else:
                resource_name += letter

        http_method = resource_method.__name__
        mock_name = resource_name + mock_suffix + '_' + http_method

        @wraps(resource_method)
        def wrapped_resource_method(*args, **kwargs):
            """Replace the existing method with this one."""
            if bool(flask.request.args.get('mock')):
                mock_response = utils.load_json_mock(mock_name)
                return mock_response
            else:
                return resource_method(*args, **kwargs)

        return wrapped_resource_method

    # FIXME: eventually this will be redone to tell ElasticSearch to use
    # an index consisting of records a year of age or older. The age is
    # measured by class year (when it was taught in a syllabus) and NOT
    # simply when it was added to our database.
评论列表
文章目录


问题


面经


文章

微信
公众号

扫码关注公众号