【发布时间】:2015-07-26 11:11:44
【问题描述】:
SQLAlchemy 似乎在 pylint 上给了我很多我无法解决的错误。
第一个问题是每个表都必须定义为一个新的类。
例子:
class Person(BASE):
"""Person Table Definition"""
__tablename__ = 'person'
id = Column(Integer, primary_key=True)
name = Column(String(30))
...导致这些错误对于我定义的每个表:
W: 20, 0: Class has no __init__ method (no-init)
R: 20, 0: Too few public methods (0/2) (too-few-public-methods)
第二个问题是为 SQLAlchemy engine 和 BASE 构造使用全局变量。我不确定如何重构此代码以使这些变量不是全局变量,因为必须将参数 BASE 传递到上面的表类定义中。
BASE = sqlalchemy.ext.declarative.declarative_base()
global engine
...
def create_sqla_engine():
"""Create the SQLA engine"""
global engine
engine = create_engine('mysql+mysqlconnector://root:@127.0.0.1:3306/sqlalchemy_example')
我是 python 新手,但这看起来很难看。 pylint 也抱怨它:
C: 51, 0: Invalid constant name "engine" (invalid-name)
最后,pylint 认为我没有使用我在这段代码中明确使用的导入。
W: 15, 0: Unused declarative_base imported from sqlalchemy.ext.declarative (unused-import)
W: 16, 0: Unused sessionmaker imported from sqlalchemy.orm (unused-import)
...为什么? pylint 与 python3 不兼容吗?我应该在它们使用的方法中导入我需要的模块,而不是在文件的顶部?
【问题讨论】:
-
虽然
BASE应该不会造成任何问题,但global engine确实是代码异味。了解如何从方法中返回引擎实例。您只需要谨慎使用引擎;您应该主要向sessionmaker请求会话,这很便宜。 -
WRT 'no init' 和 'too few public methods' 对于有元类的类,比如表,有an open bug。
标签: python sqlalchemy pylint