V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
0x0208v0
V2EX  ›  Python

我用 type()动态创建了一个类,怎么生成这个类的 Python 源代码??有现成的工具吗?需求的场景是这样的

  •  
  •   0x0208v0 · 2021-05-06 19:49:40 +08:00 · 934 次点击
    这是一个创建于 1078 天前的主题,其中的信息可能已经有所发展或是发生改变。

    如题。通过 type 函数创建一个类,如何生成这个类的 python 代码的形式? 我有一个 json,类似这样

    {
        "table_name": "student",
         "columns":  [
             {"name": "name",  "type": "str"},
             {"name": "gender", "type": "str"},
             {"name": "age", "type": "int"} 
         ]
    }
    

    我想用代码生成一个 py 文件,里面是 sqlalchemy 的 model,类似这样

    class Student(BaseModel):
        name = Column(String(64), nullable=False)
        gender = Column(String(1), nullable=False)
        age = Column(BigInteger, nullable=False)
    

    我的想法是用 jinja2 写一个模版,然后往里面填充数据,类似这样

    class {{ class_name }} (BaseModel):
        {% for column in columns %}
        {{column.name}} = Column({{blablablabla}})
        {% endfor %}
    

    但是感觉这样的方法太笨拙了,请问有高级一点的实现方式吗?比如通过 json, 先用 type()生成一个 model,然后把这个内存对象逆向成字节码,再通过字节码还原成 python 代码??? 不知道我有没有描述清楚,请大佬们帮帮忙

    第 1 条附言  ·  2021-05-07 00:00:08 +08:00
    sqlacodegen 解决了该问题
    1 条回复    2021-05-07 17:05:29 +08:00
    ruanimal
        1
    ruanimal  
       2021-05-07 17:05:29 +08:00   ❤️ 1
    sqlalchemy 可以自动映射表, 不需要手动生成文件
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   5176 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 29ms · UTC 08:07 · PVG 16:07 · LAX 01:07 · JFK 04:07
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.