首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何运行sqlacodegen?

如何运行sqlacodegen?
EN

Stack Overflow用户
提问于 2015-03-01 07:25:11
回答 3查看 13.1K关注 0票数 7

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

当我键入sqlacodegen --help寻求帮助时,我得到的结果是:

代码语言:javascript
复制
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: bad operand type for unary -: '_Helper'

基本说明为here

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2015-03-01 07:30:10

这是因为您在Python shell中执行了此操作:

代码语言:javascript
复制
>>> 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

代码语言:javascript
复制
% 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)

实际命令的示例如下:

代码语言:javascript
复制
% sqlacodegen --outfile models.py \
postgresql://gollyjer:swordfish@localhost:5432/mydatabase

其中,gollyjer:swordfish是采用user:password格式的凭据。

票数 27
EN

Stack Overflow用户

发布于 2015-11-05 09:04:56

这里已经回答了几个问题:

应使用pip

  • 安装
  1. sqlacodegen。安装后,应从windows命令提示符运行,而不是从python shell运行。
  2. 如果要给出多个表名,请不要在表名之间留出任何空格,只提供逗号。
票数 1
EN

Stack Overflow用户

发布于 2021-07-22 15:41:52

正如@Antti建议的那样,sqlacodegen应该在命令shell中使用。

无论如何,可以使用CodeGenerator类和SqlAlchemy将代码生成嵌入到您自己的代码中

代码语言:javascript
复制
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文件中创建数据库模型。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/28788186

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档