Flask從數據庫已有表自動生成model


准備

我們需要提前准備兩個包,分別是 flask-sqlacodegen 和 psycopg2 安裝方式為

pip install flask-sqlacodegen
pip install psycopg2

開始

我們直接使用命令開始生成

# 單張表
flask-sqlacodegen "postgresql://postgres:36o%*********2022@127.0.0.1:5432/situation" --tables TABLENAME --outfile "model.py" --flask
# 多張表
flask-sqlacodegen "postgresql://postgres:36o%*********2022@127.0.0.1:5432/situation" --tables TABLENAME,TABLENAME,TABLENAME --outfile "model.py" --flask
# 全部表
flask-sqlacodegen "postgresql://postgres:36o%*********2022@127.0.0.1:5432/situation" --outfile "model.py" --flask

ps:(大寫 “TABLENAME” 要換成自己對應的實際情況)

此步驟有可能會報錯,但是沒關系,在目錄下已經生成了對應文件

 

 

 最后

我們最后在加上 inspect 完成初始化就OK啦!

def __init__(self, **kwargs):
    for c in inspect(self).mapper.column_attrs:
        setattr(self, c.key, kwargs.get(c.key)) if kwargs.get(c.key) else setattr(self, c.key, None)

def to_dict(self):
    return {c.key: getattr(self, c.key) for c in inspect(self).mapper.column_attrs}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM