如何运行sqlacodegen?

时间:2015-02-28 23:25:11

标签: python sqlalchemy sqlacodegen

我不明白为什么我不能运行sqlacodegen。我希望用它来从我现有的PostgreSQL数据库创建一个SQLAlchemy模型。它不会运行。

当我输入sqlacodegen --help寻求帮助时,我得到了:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: bad operand type for unary -: '_Helper'

基本说明为here

3 个答案:

答案 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)

这里已经回答了很少的事情:

  1. 应使用pip
  2. 安装sqlacodegen
  3. 一旦安装,它应该从Windows命令提示符而不是从python shell运行。
  4. 如果您提供多个表名,请不要在表名之间提供任何空格,只提供逗号。

答案 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 文件中创建数据库模型。

相关问题