python自動生成model文件過程詳解
更新時間:2019年11月02日 11:00:24 作者:大步向前blue
這篇文章主要介紹了python自動生成model文件過程詳解,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值
生成方式
Python中想要自動生成 model文件可以通過 sqlacodegen這個命令來生成對應的model文件
sqlacodegen 你可以通過pip去安裝:
pip install sqlacodegen
格式:
sqlacodegen mysql+pymysql://username:password@host/database_name > model.py
說明:
- mysql+pymysql : 表示連接數(shù)據(jù)庫的連接方式
- username : 連接MySQL數(shù)據(jù)庫的用戶名
- password : 連接MySQL數(shù)據(jù)庫用戶對應的密碼
- host : 數(shù)據(jù)庫的主機地址
- database_name : 需要生成model的數(shù)據(jù)庫名【一定是數(shù)據(jù)庫名】
問題: 如果只想生成數(shù)據(jù)庫中指定表的model文件怎么辦?
答案就是:
給 sqlacodegen 加一個 --table 的參數(shù)即可
案例:
👉⚡️sqlacodegen --tables products mysql+pymysql://root:root@127.0.0.1/shopify > products.py 👉⚡️ls products.py
結(jié)果:
👉⚡️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'"))
👉⚡️
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
pygame開發(fā):馬賽邏輯小游戲的代碼實現(xiàn)
這篇文章主要介紹了pygame開發(fā),通過本文,您可以使用pygame開發(fā)一個馬賽邏輯小游戲~有需要的朋友可以借鑒參考下,希望能夠有所幫助2021-09-09
python中pivot()函數(shù)基礎(chǔ)知識點
在本篇內(nèi)容里小編給大家分享的是一篇關(guān)于python中pivot()函數(shù)基礎(chǔ)知識點內(nèi)容,對此有興趣的朋友們可以參考學習下。2021-01-01
教你用一行Python代碼實現(xiàn)并行任務(wù)(附代碼)
這篇文章主要介紹了教你用一行Python代碼實現(xiàn)并行任務(wù)(附代碼),小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-02-02
詳解程序意外中斷自動重啟shell腳本(以Python為例)
這篇文章主要介紹了詳解程序意外中斷自動重啟shell腳本(以Python為例),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2019-07-07

