如果您使用的是“声明式”方法,则可以尝试将类本身设为“只读”:
class MyBase(object):
"""
This class is a superclass of SA-generated Base class,
which in turn is the superclass of all db-aware classes
so we can define common functions here
"""
def __setattr__(self, name, value):
"""
Raise an exception if attempting to assign to an atribute of a "read-only" object
Transient attributes need to be prefixed with "_t_"
"""
if (getattr(self, '__read_only__', False)
and name != "_sa_instance_state"
and not name.startswith("_t_")):
raise ValueError("Trying to assign to %s of a read-only object %s" % (name, self))
super(MyBase, self).__setattr__(name, value)
Base = declarative_base(cls=MyBase)
同样,您可以尝试覆盖__init__
方法以防止对象被实例化。
但是,在应用程序级别解决这个问题感觉有点脆弱 - 我只想在数据库中创建一个特殊用户供您的应用程序连接,这将节省您想要保持不变的表的有限权限。