我正在终端中按照本教程编写 shell 脚本 http://docs.sqlalchemy.org/en/latest/orm/tutorial.html有关声明映射的 SQLAlchemy 教程。我需要输入
>>> from sqlalchemy import Column, Integer, String
>>> class User(Base):
__tablename__ = 'users'
id = Column(Integer, primary_key=True)
name = Column(String)
fullname = Column(String)
password = Column(String)
def __repr__(self):
return "<\User(name='%s', fullname='%s', password='%s')>" % (
self.name, self.fullname, self.password)
问题是在我输入密码 = Column(String) 后,我按两次 Enter 键,然后 .... 更改为 >>>。然后我重新输入所有内容,但随后抛出了一个错误,因为该类已经存在......我不完全确定如何解决这个问题。如何在 shell 脚本中打开该类并对其进行编辑(添加到 def repr 中)
抛出的错误如下:
/Users/GaryPeters/TFsqlAlc001/lib/python2.7/site-packages/sqlalchemy/ext/declarative/clsregistry.py:160: SAWarning: This declarative base already contains a class with the same class name and module name as __main__.User, and will be replaced in the string-lookup table.
existing.add_item(cls)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Users/GaryPeters/TFsqlAlc001/lib/python2.7/site-packages/sqlalchemy/ext/declarative/api.py", line 53, in __init__
_as_declarative(cls, classname, cls.__dict__)
File "/Users/GaryPeters/TFsqlAlc001/lib/python2.7/site-packages/sqlalchemy/ext/declarative/base.py", line 251, in _as_declarative
**table_kw)
File "/Users/GaryPeters/TFsqlAlc001/lib/python2.7/site-packages/sqlalchemy/sql/schema.py", line 339, in __new__
"existing Table object." % key)
sqlalchemy.exc.InvalidRequestError: Table 'users' is already defined for this MetaData instance. Specify 'extend_existing=True' to redefine options and columns on an existing Table object.
最佳答案
只需关闭并重新打开 shell,然后再次输入所有内容,这一次请确保仅按 enter 一次,而不是两次。
或者,请确保在遇到空行时添加缩进 - 如果您按 enter,然后按 tab 或 space适当的次数,以便您缩进到正确的级别,然后您应该能够再次按 enter ,而 shell 不会结束您的定义并再次显示 >>>
.
您还应该在 shell 中重新定义类,所以我不太确定“抛出错误”是什么意思 - 如果您要编辑帖子以包含特定堆栈,这可能会有所帮助跟踪。
关于python - 在 Shell 和 SQLAlchemy 中编辑 Python 类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23346211/