我想简化/减少我的代码,所以我尝试将具有重复参数的类的初始化放在它们自己的扩展类中。这是一个基于 Pyramid & Cornice 的 REST API。
我如何初始化 pyramid.httpexceptions.HTTPUnauthorized当我总是在初始化时添加相同的 header 时?这也适用于其他 HTTP 响应,我在不更改其参数的情况下重复初始化它们。
目前我想出了这个来扩展类(class):
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
我在这样的 View 中使用:
@forbidden_view_config()
def authenticate(request):
response = _401()
return _401.basic_jwt_header(response)
但是感觉和看起来都不对劲。有没有更好、更干净的方法?
最佳答案
在类上创建一个 __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
关于python - 使用相同参数重复初始化类的最佳实践(金字塔)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34978749/