首頁  >  文章  >  後端開發  >  Flask-SQLAlchemy和Alembic: Python web應用程式中遷移資料庫的最佳實務(第二部分)

Flask-SQLAlchemy和Alembic: Python web應用程式中遷移資料庫的最佳實務(第二部分)

PHPz
PHPz原創
2023-06-17 20:34:381267瀏覽

Flask-SQLAlchemy和Alembic: Python web應用程式中遷移資料庫的最佳實踐(第二部分)

在上一篇文章中,我們討論了Flask-SQLAlchemy 和Alembic 是如何協作的。本文將主要介紹如何在一些基本的資料模型中新增和移除列,並對一些列修改類型或限制的方法。這些變化在實際的專案開發過程中非常常見。

列的新增和刪除

在使用 Flask-SQLAlchemy 和 Alembic 進行資料庫遷移時,新增和移除表的列非常常見。為了示範這個過程,我們將在以下範例 Person 模型中新增一些新欄位。

from flask_sqlalchemy import SQLAlchemy

db = SQLAlchemy()

class Person(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(255), nullable=False)
    age = db.Column(db.Integer)

    def __repr__(self):
        return '<Person %r>' % self.name

假設我們要新增兩個新列,一個是出生日期(birthdate)以及一個布林類型的列,表示這個人是否已經結婚(is_married)。我們可以使用以下命令產生遷移腳本:

$ alembic revision -m "add birthdate, is_married columns to person"

接著,我們需要修改生成的.py遷移腳本文件,來新增列。我們可以在 upgrade() 函數中使用 add_column()。

from alembic import op
import sqlalchemy as sa

def upgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.add_column('person', sa.Column('birthdate', sa.Date(), nullable=True))
    op.add_column('person', sa.Column('is_married', sa.Boolean(), nullable=True))
    # ### end Alembic commands ###

對於刪除列,我們可以在對應的析構函數 degrade() 中使用 drop_column() 函數,從資料庫模型中刪除列。

def downgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.drop_column('person', 'birthdate')
    op.drop_column('person', 'is_married')
    # ### end Alembic commands ###

該遷移腳本的完整範例程式碼可以在下面找到。

"""add birthdate, is_married columns to person"""
from alembic import op
import sqlalchemy as sa


# revision identifiers, used by Alembic.
revision = 'eab2c4f1c9fb'
down_revision = '7cfae59c2402'
branch_labels = None
depends_on = None


def upgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.add_column('person', sa.Column('birthdate', sa.Date(), nullable=True))
    op.add_column('person', sa.Column('is_married', sa.Boolean(), nullable=True))
    # ### end Alembic commands ###


def downgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.drop_column('person', 'birthdate')
    op.drop_column('person', 'is_married')
    # ### end Alembic commands ###

列的類型變更和約束脩改

在許多情況下,我們需要對列的類型和約束進行修改。假設我們想要將 Person 模型的 age 欄位類型從 INTEGER 變更為 SMALLINT。我們可以在產生的.py遷移腳本檔案中使用 alter_column() 函數來實作。

def upgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.alter_column('person', 'age', existing_type=sa.Integer(),
               type_=sa.SmallInteger(), nullable=True)
    # ### end Alembic commands ###

我們也可以修改列上的約束。檢查 Person 模型,我們注意到模型中沒有唯一值約束。我們可以使用以下程式碼為 name 和 birthdate 欄位新增唯一值約束。

from alembic import op
import sqlalchemy as sa

def upgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.create_unique_constraint(op.f('uq_person_name'), 'person', ['name'])
    op.create_unique_constraint(op.f('uq_person_birthdate'), 'person', ['birthdate'])
    # ### end Alembic commands ###

如果我們以後需要取消惟一值約束,我們可以使用 drop_constraint() 函數。例如:

def downgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.drop_constraint(op.f('uq_person_name'), 'person', type_='unique')
    op.drop_constraint(op.f('uq_person_birthdate'), 'person', type_='unique')
    # ### end Alembic commands ###

本文介紹了一些常見的資料庫模式變更類型,例如新增和刪除列,更改列約束和更改列資料類型。它示範如何使用 Flask-SQLAlchemy 和 Alembic 進行資料庫遷移的最佳實踐。這將幫助您更有效率地管理資料庫模式以及在團隊環境中更容易共享遷移檔案。

參考連結:

  • Flask-SQLAlchemy - https://flask-sqlalchemy.palletsprojects.com/
  • Alembic - https://alembic.sqlalchemy. org/en/latest/

以上是Flask-SQLAlchemy和Alembic: Python web應用程式中遷移資料庫的最佳實務(第二部分)的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn