重复初始化具有相同参数(金字塔)的类的最佳实践?

2024-03-28 16:39:42 发布

您现在位置:Python中文网/ 问答频道 /正文

我想简化/减少我的代码,所以我试着将具有重复参数的类的初始化放在它们自己的扩展类中。这是一个基于金字塔和檐口的restapi。你知道吗

当我总是在初始化时添加相同的头时,如何初始化pyramid.httpexceptions.HTTPUnauthorized?这也适用于其他HTTP响应,在这些响应中,我重复初始化它们,而不更改它们的参数。你知道吗

目前,我已经提出了这个扩展类:

class _401(HTTPUnauthorized):
    def basic_jwt_header(self):
        self.headers.add('WWW-Authenticate','JWT')
        self.headers.add('WWW-Authenticate', 'Basic realm="Please log in"')
        return self

    def jwt_header(self):
        self.headers.add('WWW-Authenticate','JWT')
        return self

我在这样的视图中使用:

@forbidden_view_config()
def authenticate(request):
    response = _401()
    return _401.basic_jwt_header(response)

但感觉和看起来都不对劲。有更好更干净的方法吗?你知道吗


Tags: 代码selfadd参数returnbasicresponsedef
2条回答

由于在实例化_401实例后使用的是两种不同的方法,因此最好使用类级工厂方法,这样可以创建实例并设置所需的头:

class _401(HTTPUnauthorized):

    @classmethod
    def basic_jwt_header(cls):
        ret = cls()
        ret.headers.add('WWW-Authenticate','JWT')
        ret.headers.add('WWW-Authenticate', 'Basic realm="Please log in"')
        return ret

    @classmethod
    def jwt_header(cls):
        ret = cls()
        ret.headers.add('WWW-Authenticate','JWT')
        return ret

resp = _401.basic_jwt_header()
print resp.headers

现在不需要创建__init__,也不需要调用super()什么的。我们使用cls而不是显式的_401类来支持_401的任何未来子类。你知道吗

在类上创建__init__方法:

class _401(HTTPUnauthorized):

    def __init__(self):
        # call base class __init__ first, which will set up the
        # headers instance variable
        super(_401, self).__init__()
        # in Python 3, just use this:
        # super().__init__()

        # now add the headers that you always enter
        self.headers.add('WWW-Authenticate','JWT')
        self.headers.add('WWW-Authenticate', 'Basic realm="Please log in"')

resp = _401()
print resp.headers

相关问题 更多 >