我有装饰器传递变量'insurance_mode'的问题.我会通过以下装饰器声明来做到这一点:
@execute_complete_reservation(True)
def test_booking_gta_object(self):
self.test_select_gta_object()
Run Code Online (Sandbox Code Playgroud)
但不幸的是,这种说法不起作用.也许有更好的方法可以解决这个问题.
def execute_complete_reservation(test_case,insurance_mode):
def inner_function(self,*args,**kwargs):
self.test_create_qsf_query()
test_case(self,*args,**kwargs)
self.test_select_room_option()
if insurance_mode:
self.test_accept_insurance_crosseling()
else:
self.test_decline_insurance_crosseling()
self.test_configure_pax_details()
self.test_configure_payer_details
return inner_function
Run Code Online (Sandbox Code Playgroud) 我在我的Django项目中创建了一个装饰器,用于将参数值注入到装饰方法的参数中.
我这样做是inspect.getargspec为了检查方法中存在哪些参数并将它们放入kwargs.否则,由于方法中的参数数量不正确,我会收到错误.
虽然这在单个视图方法中正常工作,但在Django基于类的视图方面却失败了.
我相信这可能是因为装饰器@method_decorator在类级别应用于dispatch方法而不是个人get和post方法.
我是一个蟒蛇新手,可能会忽略一些明显的东西.
有没有更好的方法来做我正在做的事情?是否可以在基于类的视图中获取方法参数名称?
我正在使用Python 2.7和Django 1.11
装饰者
def need_jwt_verification(decorated_function):
@wraps(decorated_function)
def decorator(*args, **kwargs):
request = args[0]
if not isinstance(request, HttpRequest):
raise RuntimeError(
"This decorator can only work with django view methods accepting a HTTPRequest as the first parameter")
if AUTHORIZATION_HEADER_NAME not in request.META:
return HttpResponse("Missing authentication header", status=401)
jwt_token = request.META[AUTHORIZATION_HEADER_NAME].replace(BEARER_METHOD_TEXT, "")
try:
decoded_payload = jwt_service.verify_token(jwt_token)
parameter_names = inspect.getargspec(decorated_function).args
if "phone_number" in parameter_names or "phone_number" …Run Code Online (Sandbox Code Playgroud)