我不明白为什么我不能运行sqlacodegen。我希望使用它从我现有的PostgreSQL数据库创建一个SQLAlchemy模型。它不能运行。
当我键入sqlacodegen --help寻求帮助时,我得到的结果是:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: bad operand type for unary -: '_Helper'基本说明为here。
发布于 2015-03-01 07:30:10
这是因为您在Python shell中执行了此操作:
>>> import sqlacodegen
>>> sqlacodegen --help
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: bad operand type for unary -: '_Helper'您应该已经在Windows命令外壳/命令提示符中执行了sqlacodegen --help
% sqlacodegen --help
usage: sqlacodegen [-h] [--version] [--schema SCHEMA] [--tables TABLES]
[--noviews] [--noindexes] [--noconstraints] [--nojoined]
[--noinflect] [--outfile OUTFILE]
[url]
Generates SQLAlchemy model code from an existing database.
positional arguments:
url SQLAlchemy url to the database
optional arguments:
-h, --help show this help message and exit
--version print the version number and exit
--schema SCHEMA load tables from an alternate schema
--tables TABLES tables to process (comma-separated, default: all)
--noviews ignore views
--noindexes ignore indexes
--noconstraints ignore constraints
--nojoined don't autodetect joined table inheritance
--noinflect don't try to convert tables names to singular form
--outfile OUTFILE file to write output to (default: stdout)实际命令的示例如下:
% sqlacodegen --outfile models.py \
postgresql://gollyjer:swordfish@localhost:5432/mydatabase其中,gollyjer:swordfish是采用user:password格式的凭据。
发布于 2015-11-05 09:04:56
这里已经回答了几个问题:
应使用pip
发布于 2021-07-22 15:41:52
正如@Antti建议的那样,sqlacodegen应该在命令shell中使用。
无论如何,可以使用CodeGenerator类和SqlAlchemy将代码生成嵌入到您自己的代码中
import io
import sys
from sqlalchemy import create_engine, MetaData
from sqlacodegen.codegen import CodeGenerator
def generate_model(host, user, password, database, outfile = None):
engine = create_engine(f'postgresql+psycopg2://{user}:{password}@{host}/{database}')
metadata = MetaData(bind=engine)
metadata.reflect()
outfile = io.open(outfile, 'w', encoding='utf-8') if outfile else sys.stdout
generator = CodeGenerator(metadata)
generator.render(outfile)
if __name__ == '__main__':
generate_model('database.example.org', 'dbuser', 'secretpassword', 'mydatabase', 'db.py')这将在db.py文件中创建数据库模型。
https://stackoverflow.com/questions/28788186
复制相似问题