Mad*_*ing 2 python flask python-decorators
您好,我正在尝试创建一个装饰器,但出现静态方法对象不可调用的错误,下面是我的代码
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
Run Code Online (Sandbox Code Playgroud)
这是实例化 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
Run Code Online (Sandbox Code Playgroud)
现在S3Mediator 已经在 app.py 中实例化,现在我尝试使用这个装饰器作为
@s3
@staticmethod
def s3_connect(s3client):
# code don't reach here. An error is thrown
# do something here
Run Code Online (Sandbox Code Playgroud)
知道为什么它返回的静态方法对象不可调用以及如何解决这个问题
好的找到了问题的原因。我将@staticmethod放在我的装饰器下面,这就是为什么我的装饰器认为装饰器的所有方法都是静态的。我只是改变
@s3
@staticmethod
def s3_connect(s3client):
# code don't reach here. An error is thrown
# do something here
Run Code Online (Sandbox Code Playgroud)
对此
@staticmethod
@s3
def s3_connect(s3client):
# code don't reach here. An error is thrown
# do something here
Run Code Online (Sandbox Code Playgroud)