【发布时间】:2018-05-07 08:06:24
【问题描述】:
您好,我正在尝试创建一个装饰器,但我收到 staticmethod object not callable 错误,下面是我的代码
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
知道为什么它返回一个 staticmethod 对象不可调用以及如何解决这个问题
【问题讨论】:
-
你想把一个独立的函数变成一个静态方法?
-
正如@khelwood 所说,您忘记缩进 get_s3_connection 函数。根据定义,该函数不是 S3Mediator 类的一部分
-
老实说,我不确定我在做什么,因为这几乎是我们当前项目中的确切代码。做到这一点的最佳方法是什么?我正在尝试使 s3 连接在整个应用程序中保持持久
-
@Vyko 抱歉拼写错误。但是我的代码缩进是正确的
-
不要在你的问题中放文字截图。将堆栈跟踪作为文本。
标签: python flask python-decorators