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

yipeiwu_com5年前Python基础

生成方式

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'"))
👉⚡️

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

Python常见异常分类与处理方法

Python常见异常类型大概分为以下类: 1.AssertionError:当assert断言条件为假的时候抛出的异常 2.AttributeError:当访问的对象属性不存在的时候抛出...

python复制文件的方法实例详解

本文实例讲述了python复制文件的方法。分享给大家供大家参考。具体分析如下: 这里涉及Python复制文件在实际操作方案中的实际应用以及Python复制文件 的相关代码说明,希望你会有...

Python的Django框架可适配的各种数据库介绍

在 Django 中使用 PostgreSQL 使用 PostgreSQL 的话,你需要从 http://www.djangoproject.com/r/python-pgsql/ 下载...

用Python解决计数原理问题的方法

用Python解决计数原理问题的方法

前几天遇到这样一道数学题: 用四种不同颜色给三棱柱六个顶点涂色,要求每个点涂一种颜色,且每条棱的两个端点涂不同颜色,则不同的涂色方法有多少种? 当我看完题目后,顿时不知所措。于是我拿起...

python切片及sys.argv[]用法详解

一、python切片 a=a[::-1] 倒序 a=a[1:10:2] 下标1~10,以2间隔取 a=a[::2] 2间隔返回a[:] a=[1,2,3,4,5,6,7] print...