Python装饰器staticmethod对象不可调用

时间:2017-11-23 11:11:23

标签: python flask python-decorators

您好我正在尝试创建一个装饰器,但我收到的错误 staticmethod对象不可调用下面是我的代码

from db.persistence import S3Mediator
from sqlalchemy.ext.declarative import declarative_base
import logging
from functools import wraps

Base = declarative_base()

def s3(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
        try:
            s3client = S3Mediator.get_s3_connection()
            kwargs["s3client"] = s3client
            retval = func(*args, **kwargs) #### an error is raised here
        except Exception as e:
            raise e
        return retval
    return wrapper

这是实例化s3对象的中介

import boto3
import logging

class S3Mediator(object):
    s3_client = None

    def __init__(self, host, access_key, secret):
        self.client = boto3.client(
            's3',
            aws_access_key_id= access_key,
            aws_secret_access_key= secret
        )

        S3Mediator.s3_client = self.client

    @staticmethod
    def get_s3_connection():
        return S3Mediator.s3_client

现在 S3Mediator已经在app.py实例化了现在我正在尝试使用这个装饰器

@s3
@staticmethod
def s3_connect(s3client):
  # code don't reach here. An error is thrown
  # do something here

enter image description here

知道为什么它返回一个 staticmethod对象不可调用以及如何解决这个问题

1 个答案:

答案 0 :(得分:0)

好的找到了问题的原因。我把 @staticmethod 放在我的装饰器下面,这就是为什么我的装饰师认为装饰器的所有方法都是静态的。我只是改变了

@s3
@staticmethod
def s3_connect(s3client):
  # code don't reach here. An error is thrown
  # do something here

到这个

@staticmethod
@s3
def s3_connect(s3client):
  # code don't reach here. An error is thrown
  # do something here