찾다
백엔드 개발파이썬 튜토리얼Flask-SQLAlchemy 및 Alembic: Python 웹 애플리케이션에서 데이터베이스 마이그레이션 모범 사례(2부)

Flask-SQLAlchemy 및 Alembic: Python 웹 애플리케이션에서 데이터베이스 마이그레이션을 위한 모범 사례(2부)

이전 기사에서는 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 마이그레이션 스크립트 파일을 수정하여 새 열을 추가해야 합니다. 업그레이드() 함수에서 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 ###

열을 삭제하려면 해당 소멸자 Degrad()에서 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 모델을 조사해 보면 모델에 고유 값 제약 조건이 없다는 것을 알 수 있습니다. 다음 코드를 사용하여 이름 및 생년월일 열에 고유 값 제약 조건을 추가할 수 있습니다.

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 웹 애플리케이션에서 데이터베이스 마이그레이션 모범 사례(2부)의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
어레이는 파이썬으로 과학 컴퓨팅에 어떻게 사용됩니까?어레이는 파이썬으로 과학 컴퓨팅에 어떻게 사용됩니까?Apr 25, 2025 am 12:28 AM

Arraysinpython, 특히 비밀 복구를위한 ArecrucialInscientificcomputing.1) theaRearedFornumericalOperations, DataAnalysis 및 MachinELearning.2) Numpy'SimplementationIncensuressuressurations thanpythonlists.3) arraysenablequick

같은 시스템에서 다른 파이썬 버전을 어떻게 처리합니까?같은 시스템에서 다른 파이썬 버전을 어떻게 처리합니까?Apr 25, 2025 am 12:24 AM

Pyenv, Venv 및 Anaconda를 사용하여 다양한 Python 버전을 관리 할 수 ​​있습니다. 1) PYENV를 사용하여 여러 Python 버전을 관리합니다. Pyenv를 설치하고 글로벌 및 로컬 버전을 설정하십시오. 2) VENV를 사용하여 프로젝트 종속성을 분리하기 위해 가상 환경을 만듭니다. 3) Anaconda를 사용하여 데이터 과학 프로젝트에서 Python 버전을 관리하십시오. 4) 시스템 수준의 작업을 위해 시스템 파이썬을 유지하십시오. 이러한 도구와 전략을 통해 다양한 버전의 Python을 효과적으로 관리하여 프로젝트의 원활한 실행을 보장 할 수 있습니다.

표준 파이썬 어레이를 통해 Numpy Array를 사용하면 몇 가지 장점은 무엇입니까?표준 파이썬 어레이를 통해 Numpy Array를 사용하면 몇 가지 장점은 무엇입니까?Apr 25, 2025 am 12:21 AM

Numpyarrayshaveseveraladvantagesstandardpythonarrays : 1) thearemuchfasterduetoc 기반 간증, 2) thearemorememory-refficient, 특히 withlargedatasets 및 3) wepferoptizedformationsformationstaticaloperations, 만들기, 만들기

어레이의 균질 한 특성은 성능에 어떤 영향을 미칩니 까?어레이의 균질 한 특성은 성능에 어떤 영향을 미칩니 까?Apr 25, 2025 am 12:13 AM

어레이의 균질성이 성능에 미치는 영향은 이중입니다. 1) 균질성은 컴파일러가 메모리 액세스를 최적화하고 성능을 향상시킬 수 있습니다. 2) 그러나 유형 다양성을 제한하여 비 효율성으로 이어질 수 있습니다. 요컨대, 올바른 데이터 구조를 선택하는 것이 중요합니다.

실행 파이썬 스크립트를 작성하기위한 모범 사례는 무엇입니까?실행 파이썬 스크립트를 작성하기위한 모범 사례는 무엇입니까?Apr 25, 2025 am 12:11 AM

tocraftexecutablepythonscripts, 다음과 같은 비스트 프랙티스를 따르십시오 : 1) 1) addashebangline (#!/usr/bin/envpython3) tomakethescriptexecutable.2) setpermissionswithchmod xyour_script.py.3) organtionewithlarstringanduseifname == "__"

Numpy 배열은 배열 모듈을 사용하여 생성 된 배열과 어떻게 다릅니 까?Numpy 배열은 배열 모듈을 사용하여 생성 된 배열과 어떻게 다릅니 까?Apr 24, 2025 pm 03:53 PM

numpyarraysarebetterfornumericaloperations 및 multi-dimensionaldata, mumemer-efficientArrays

Numpy Array의 사용은 Python에서 어레이 모듈 어레이를 사용하는 것과 어떻게 비교됩니까?Numpy Array의 사용은 Python에서 어레이 모듈 어레이를 사용하는 것과 어떻게 비교됩니까?Apr 24, 2025 pm 03:49 PM

numpyarraysarebetterforheavynumericalcomputing, whilearraymoduleisiMoresuily-sportainedprojectswithsimpledatatypes.1) numpyarraysofferversatively 및 formanceforgedatasets 및 complexoperations.2) Thearraymoduleisweighit 및 ep

CTYPES 모듈은 파이썬의 어레이와 어떤 관련이 있습니까?CTYPES 모듈은 파이썬의 어레이와 어떤 관련이 있습니까?Apr 24, 2025 pm 03:45 PM

ctypesallowscreatingandmanipulatingC-stylearraysinPython.1)UsectypestointerfacewithClibrariesforperformance.2)CreateC-stylearraysfornumericalcomputations.3)PassarraystoCfunctionsforefficientoperations.However,becautiousofmemorymanagement,performanceo

See all articles

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

Video Face Swap

Video Face Swap

완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

뜨거운 도구

MinGW - Windows용 미니멀리스트 GNU

MinGW - Windows용 미니멀리스트 GNU

이 프로젝트는 osdn.net/projects/mingw로 마이그레이션되는 중입니다. 계속해서 그곳에서 우리를 팔로우할 수 있습니다. MinGW: GCC(GNU Compiler Collection)의 기본 Windows 포트로, 기본 Windows 애플리케이션을 구축하기 위한 무료 배포 가능 가져오기 라이브러리 및 헤더 파일로 C99 기능을 지원하는 MSVC 런타임에 대한 확장이 포함되어 있습니다. 모든 MinGW 소프트웨어는 64비트 Windows 플랫폼에서 실행될 수 있습니다.

ZendStudio 13.5.1 맥

ZendStudio 13.5.1 맥

강력한 PHP 통합 개발 환경

VSCode Windows 64비트 다운로드

VSCode Windows 64비트 다운로드

Microsoft에서 출시한 강력한 무료 IDE 편집기

Eclipse용 SAP NetWeaver 서버 어댑터

Eclipse용 SAP NetWeaver 서버 어댑터

Eclipse를 SAP NetWeaver 애플리케이션 서버와 통합합니다.

PhpStorm 맥 버전

PhpStorm 맥 버전

최신(2018.2.1) 전문 PHP 통합 개발 도구