网络编程
位置:首页>> 网络编程>> Python编程>> python自动生成model文件过程详解

python自动生成model文件过程详解

作者:大步向前blue  发布时间:2023-09-30 02:54:05 

标签:python,生成,model,文件

生成方式

Python中想要自动生成 model文件可以通过 sqlacodegen这个命令来生成对应的model文件

sqlacodegen 你可以通过pip去安装:


pip install sqlacodegen

格式:


sqlacodegen mysql+pymysql://username:password@host/database_name > model.py

说明:

  • mysql+pymysql : 表示连接数据库的连接方式

  • username : 连接MySQL数据库的用户名

  • password : 连接MySQL数据库用户对应的密码

  • host : 数据库的主机地址

  • database_name : 需要生成model的数据库名【一定是数据库名】

问题: 如果只想生成数据库中指定表的model文件怎么办?

答案就是:

给 sqlacodegen 加一个 --table 的参数即可

案例:


👉⚡️sqlacodegen --tables products mysql+pymysql://root:root@127.0.0.1/shopify > products.py
👉⚡️ls
products.py

结果:


👉⚡️cat products.py
# coding: utf-8
from sqlalchemy import CHAR, Column, String, Text, text
from sqlalchemy.dialects.mysql import INTEGER
from sqlalchemy.ext.declarative import declarative_base

Base = declarative_base()
metadata = Base.metadata

class Product(Base):
 __tablename__ = 'products'

id = Column(INTEGER(16), primary_key=True)
 title = Column(String(256), nullable=False, server_default=text("''"))
 product_id = Column(INTEGER(16))
 shop_url = Column(String(120))
 body_html = Column(Text)
 vendor = Column(String(64))
 product_type = Column(String(64))
 created_at = Column(CHAR(30))
 updated_at = Column(CHAR(30))
 handle = Column(String(256))
 published_at = Column(CHAR(30))
 template_suffix = Column(String(256))
 tags = Column(String(256))
 published_scope = Column(CHAR(10), nullable=False, server_default=text("'web'"))
👉⚡️

来源:https://www.cnblogs.com/yinguohai/p/11778488.html

0
投稿

猜你喜欢

手机版 网络编程 asp之家 www.aspxhome.com