【问题标题】:[Python][Flask] PyLint too many instance attributes, is this resource correctly written? [duplicate][Python][Flask] PyLint too many instance attributes, is this resource correctly written? [duplicate]
【发布时间】:2022-01-03 16:10:39
【问题描述】:

我正在使用 Flask 在 Python 中编写应用程序,现在在为端点创建资源类期间,我收到 Pylint 'too-many-instance-attributes' 警告。现在我不知道我正在做的是否是一种“正确”的编写资源的方式。

我像这样将依赖项注入到资源中:

api.add_resource(TicketsQuery, '/tickets/query',
             '/ticket/query/<int:ticketID>',
             resource_class_kwargs={'cleaner': Cleaner(StrategyResponseTickets()),
                                    'machine_cleaner': Cleaner(StrategyResponseMachines()),
                                    'db': soap_caller,
                                    'cache': cache,
                                    'field_map': app.config['FIELD_FILTER_MAP']['TICKETS'],
                                    'endpoint_permission': TicketsQueryPermission
                                    })

然后在资源中显示为 kwargs 参数。我还装饰了 init 中的函数,因为我需要类中的一个变量(自己进行装饰)。

class TicketsQuery(Resource):
def __init__(self, **kwargs):
    # Dependencies
    self.cleaner = kwargs['cleaner']
    self.machine_cleaner = kwargs['machine_cleaner']
    self.db = kwargs['db']
    self.cache = kwargs['cache']
    self.field_map = kwargs['field_map']
    self.endpoint_permission = kwargs['endpoint_permission']

    # Permissions of endpoint method calls, implemented using wrapper
    self.get = authorization_required(self.endpoint_permission, UserType.GENERIC_EMPLOYEE)(self.get)
    self.post = authorization_required(self.endpoint_permission, UserType.GENERIC_EMPLOYEE)(self.post)

def get(self, permission_set: TicketsPermissionSet, ticketID=-1):

这是在 Flask 中编写资源的正确方法吗?还是有更好的结构可以坚持?感谢您提供任何见解或提示!

【问题讨论】:

    标签: python flask-restful pylint


    【解决方案1】:

    不要因 linter 警告而气馁 ~ 它会提醒您坚持特定的风格。如果您在项目的根文件夹中还没有.pylintrc,那么 linter 将使用默认规则;这只是针对“实例中的变量过多”的一种样式警告〜即太多self.*'s - 这是 100% 的 pylint 事情,与 Flask 无关

    您可以通过在课程的def __init__(...): 上方添加评论# pylint: disable=too-many-instance-attributes 来取消对此的警告,但使其对任何其他人保持有效。

    如果您想要一种更 pylintesque 的解决方法,请在您项目的根文件夹以生成.pylintrc

    从那里您可以将错误代码R0902 添加到disable= 列表~ 即disable=R0902disable=A*,B*,R0902 ~ 如果你禁用多个警告(接受通配符,所以你可以 只是禁用 ALL R* 消息,但最好只在您确定知道要关闭哪些警告时才这样做)。 ,您可以在[DESIGN] 下找到max-attributes= 行,并将该数字设置/设置为您认为更合理的更高值。

    作为参考,如果您想进一步探索,可以找到此信息的资源 ~ here's a list of the warnings you can get from pylint,您可以通过错误名称 too-many-instance-attributes 或其代码 R0902here's a sample pylintrc 进行搜索,您可以大部分通过代码(即R0902)浏览以找到其中影响该警告的属性。

    最后,如果您想了解更多示例,这里是关于同一 pylint 错误消息的另一篇 SO 文章 ~ How to deal with Pylint's "too-many-instance-attributes" message?

    【讨论】:

      猜你喜欢
      • 2014-08-17
      • 2021-11-16
      • 2019-01-19
      • 1970-01-01
      • 2020-12-03
      • 1970-01-01
      • 1970-01-01
      • 2021-07-26
      • 2020-08-23
      相关资源
      最近更新 更多