我不明白为什么我不能运行sqlacodegen。我希望用它来从我现有的PostgreSQL数据库创建一个SQLAlchemy模型。它不会运行。
当我输入sqlacodegen --help
寻求帮助时,我得到了:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: bad operand type for unary -: '_Helper'
基本说明为here。
答案 0 :(得分:14)
这是因为你在Python shell中这样做了:
>>> import sqlacodegen
>>> sqlacodegen --help
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: bad operand type for unary -: '_Helper'
您应该在 Unix命令shell / 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
。
答案 1 :(得分:1)
这里已经回答了很少的事情:
答案 2 :(得分:0)
正如@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
文件中创建数据库模型。