다음을 통해 공유


빠른 시작: Python을 사용하여 Azure Database for PostgreSQL - 유연한 서버의 데이터 연결 및 쿼리

적용 대상: Azure Database for PostgreSQL - 유연한 서버

이 빠른 시작에서는 Python을 사용하여 Azure Database for PostgreSQL 유연한 서버 인스턴스에 연결합니다. 그런 다음, SQL 문을 사용하여 macOS, Ubuntu Linux 및 Windows 플랫폼에서 데이터베이스의 데이터를 쿼리, 삽입, 업데이트 및 삭제합니다.

이 문서의 단계에는 Microsoft Entra 인증과 PostgreSQL 인증이라는 두 가지 인증 방법이 포함되어 있습니다. 암호 없음 탭에는 Microsoft Entra 인증이 표시되고 암호 탭에는 PostgreSQL 인증이 표시됩니다.

Microsoft Entra 인증은 Microsoft Entra ID에 정의된 ID를 사용하여 Azure Database for PostgreSQL에 연결하기 위한 메커니즘입니다. Microsoft Entra 인증을 사용하면 중앙 위치에서 데이터베이스 사용자 ID 및 기타 Microsoft 서비스를 관리할 수 있으므로 권한 관리가 간소화됩니다. 자세히 알아보려면 Azure Database for PostgreSQL - 유연한 서버를 사용한 Microsoft Entra 인증을 참조하세요.

PostgreSQL 인증은 PostgreSQL에 저장된 계정을 사용합니다. 암호를 계정의 자격 증명으로 사용하도록 선택한 경우 이러한 자격 증명은 user 테이블에 저장됩니다. 이러한 암호는 PostgreSQL에 저장되기 때문에 암호 회전을 직접 관리해야 합니다.

이 문서에서는 사용자가 Python을 사용하여 개발하는 데 익숙하지만 Azure Database for PostgreSQL 유연한 서버를 처음 사용한다고 가정합니다.

필수 조건

클라이언트 워크스테이션에 대한 방화벽 규칙 추가

서버에서 Microsoft Entra 통합 구성(암호 없는 경우에만 해당)

암호 없는 인증 단계를 따르는 경우 서버 인스턴스에 대해 Microsoft Entra 인증을 구성해야 하며 서버 인스턴스에서 Microsoft Entra 관리자로 할당되어야 합니다. Microsoft Entra 통합 구성의 단계에 따라 Microsoft Entra 인증이 구성되어 있고 서버 인스턴스에서 Microsoft Entra 관리자로 할당되었는지 확인합니다.

개발 환경 준비

코드를 실행하려는 폴더로 변경하고 가상 환경을 만들고 활성화합니다. 가상 환경은 특정 버전의 Python과 해당 애플리케이션에 필요한 기타 패키지를 위한 자체 포함 디렉터리입니다.

다음 명령을 실행하여 가상 환경을 만들고 활성화합니다.

py -3 -m venv .venv
.venv\Scripts\activate

Python 라이브러리 설치

코드 예를 실행하는 데 필요한 Python 라이브러리를 설치합니다.

PostgreSQL 데이터베이스에 연결하고 쿼리할 수 있는 psycopg2 모듈과 Azure SDK 전반에 걸쳐 Microsoft Entra 토큰 인증 지원을 제공하는 azure-identity 라이브러리를 설치합니다.

pip install psycopg2
pip install azure-identity

인증 코드 추가

이 섹션에서는 작업 디렉터리에 인증 코드를 추가하고 서버 인스턴스를 통한 인증 및 권한 부여에 필요한 추가 단계를 수행합니다.

  1. 다음 코드를 편집기에 복사하고 get_conn.py라는 파일에 저장합니다.

    import urllib.parse
    import os
    
    from azure.identity import DefaultAzureCredential
    
    # IMPORTANT! This code is for demonstration purposes only. It's not suitable for use in production. 
    # For example, tokens issued by Microsoft Entra ID have a limited lifetime (24 hours by default). 
    # In production code, you need to implement a token refresh policy.
    
    def get_connection_uri():
    
        # Read URI parameters from the environment
        dbhost = os.environ['DBHOST']
        dbname = os.environ['DBNAME']
        dbuser = urllib.parse.quote(os.environ['DBUSER'])
        sslmode = os.environ['SSLMODE']
    
        # Use passwordless authentication via DefaultAzureCredential.
        # IMPORTANT! This code is for demonstration purposes only. DefaultAzureCredential() is invoked on every call.
        # In practice, it's better to persist the credential across calls and reuse it so you can take advantage of token
        # caching and minimize round trips to the identity provider. To learn more, see:
        # https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/identity/azure-identity/TOKEN_CACHING.md 
        credential = DefaultAzureCredential()
    
        # Call get_token() to get a token from Microsft Entra ID and add it as the password in the URI.
        # Note the requested scope parameter in the call to get_token, "https://ossrdbms-aad.database.windows.net/.default".
        password = credential.get_token("https://ossrdbms-aad.database.windows.net/.default").token
    
        db_uri = f"postgresql://{dbuser}:{password}@{dbhost}/{dbname}?sslmode={sslmode}"
        return db_uri
    
  2. 데이터베이스 연결 정보를 가져옵니다.

    1. Azure Portal에 로그인하고 Azure Database for PostgreSQL 유연한 서버 이름을 선택합니다.
    2. 서버의 개요 페이지에서 정규화된 서버 이름을 복사합니다. 정규화된 서버 이름은 항상 <my-server-name>.postgres.database.azure.com 형식입니다.
    3. 왼쪽 메뉴의 보안에서 인증을 선택합니다. 사용자의 계정이 Microsoft Entra Admins 아래에 나열되어 있는지 확인합니다. 그렇지 않은 경우 서버에서 Microsoft Entra 통합 구성(암호 없는 경우에만 해당) 단계를 완료합니다.
  3. 연결 URI 요소에 대한 환경 변수를 설정합니다.

    set DBHOST=<server-name>
    set DBNAME=<database-name>
    set DBUSER=<username>
    set SSLMODE=require
    

    명령에서 다음 자리 표시자 값을 바꿉니다.

    • Azure Portal에서 복사한 값이 있는 <server-name>.
    • <username>을 Azure 사용자 이름으로 바꿉니다. 예: john@contoso.com;
    • <database-name>을 Azure Database for PostgreSQL 유연한 서버 데이터베이스의 이름으로 바꿉니다. postgres라는 기본 데이터베이스는 서버를 만들 때 자동으로 생성되었습니다. 해당 데이터베이스를 사용하거나 SQL 명령을 사용하여 새 데이터베이스를 만들 수 있습니다.
  4. 워크스테이션에서 Azure에 로그인합니다. Azure CLI, Azure PowerShell 또는 Azure Developer CLI를 사용하여 로그인할 수 있습니다. 예를 들어, Azure CLI를 통해 로그인하려면 다음 명령을 입력합니다.

    az login
    

    인증 코드는 DefaultAzureCredential을 사용하여 Microsoft Entra ID로 인증하고 서버 인스턴스에서 작업을 수행할 수 있는 권한을 부여하는 토큰을 가져옵니다. DefaultAzureCredential은 인증 자격 증명 유형 체인을 지원합니다. 지원되는 자격 증명 중에는 Azure CLI, Azure PowerShell 또는 Azure Developer CLI와 같은 개발자 도구에 로그인한 자격 증명이 있습니다.

Python 예제를 실행하는 방법

이 문서의 각 코드 예제는 다음과 같습니다.

  1. 텍스트 편집기에서 새 파일을 만듭니다.

  2. 파일에 코드 예제를 추가합니다.

  3. 프로젝트 폴더의 파일을 .py 확장명을 사용하여 저장합니다(예: postgres-insert.py). Windows의 경우 파일을 저장할 때 UTF-8 인코딩을 선택해야 합니다.

  4. 프로젝트 폴더에서 python을 입력하고 그 뒤에 파일 이름을 입력합니다(예: python postgres-insert.py).

테이블 만들기 및 데이터 삽입

다음 코드 예는 psycopg2.connect 함수를 사용하여 Azure Database for PostgreSQL 유연한 서버 데이터베이스에 연결하고 SQL INSERT 문을 사용하여 데이터를 로드합니다. cursor.execute 함수는 데이터베이스에 대해 SQL 쿼리를 실행합니다.

import psycopg2
from get_conn import get_connection_uri

conn_string = get_connection_uri()

conn = psycopg2.connect(conn_string) 
print("Connection established")
cursor = conn.cursor()

# Drop previous table of same name if one exists
cursor.execute("DROP TABLE IF EXISTS inventory;")
print("Finished dropping table (if existed)")

# Create a table
cursor.execute("CREATE TABLE inventory (id serial PRIMARY KEY, name VARCHAR(50), quantity INTEGER);")
print("Finished creating table")

# Insert some data into the table
cursor.execute("INSERT INTO inventory (name, quantity) VALUES (%s, %s);", ("banana", 150))
cursor.execute("INSERT INTO inventory (name, quantity) VALUES (%s, %s);", ("orange", 154))
cursor.execute("INSERT INTO inventory (name, quantity) VALUES (%s, %s);", ("apple", 100))
print("Inserted 3 rows of data")

# Clean up
conn.commit()
cursor.close()
conn.close()

코드가 성공적으로 실행되면 다음과 같은 출력이 생성됩니다.

Connection established
Finished dropping table (if existed)
Finished creating table
Inserted 3 rows of data

데이터 읽기

다음 코드 예제에서는 Azure Database for PostgreSQL 유연한 서버 데이터베이스에 연결하고 cursor.execute와 SQL SELECT 문을 사용하여 데이터를 읽습니다. 이 함수는 쿼리를 허용하며, cursor.fetchall()을 사용하여 반복할 결과 집합을 반환합니다.

import psycopg2
from get_conn import get_connection_uri

conn_string = get_connection_uri()

conn = psycopg2.connect(conn_string) 
print("Connection established")
cursor = conn.cursor()

# Fetch all rows from table
cursor.execute("SELECT * FROM inventory;")
rows = cursor.fetchall()

# Print all rows
for row in rows:
    print("Data row = (%s, %s, %s)" %(str(row[0]), str(row[1]), str(row[2])))

# Cleanup
conn.commit()
cursor.close()
conn.close()

코드가 성공적으로 실행되면 다음과 같은 출력이 생성됩니다.

Connection established
Data row = (1, banana, 150)
Data row = (2, orange, 154)
Data row = (3, apple, 100)

데이터 업데이트

다음 코드 예제에서는 Azure Database for PostgreSQL 유연한 서버 데이터베이스에 연결하고 cursor.execute와 SQL UPDATE 문을 사용하여 데이터를 업데이트합니다.

import psycopg2
from get_conn import get_connection_uri

conn_string = get_connection_uri()

conn = psycopg2.connect(conn_string) 
print("Connection established")
cursor = conn.cursor()

# Update a data row in the table
cursor.execute("UPDATE inventory SET quantity = %s WHERE name = %s;", (200, "banana"))
print("Updated 1 row of data")

# Cleanup
conn.commit()
cursor.close()
conn.close()

데이터 삭제

다음 코드 예제에서는 Azure Database for PostgreSQL 유연한 서버 데이터베이스에 연결하고 cursor.execute와 SQL DELETE 문을 사용하여 이전에 삽입한 인벤토리 항목을 삭제합니다.

import psycopg2
from get_conn import get_connection_uri

conn_string = get_connection_uri()

conn = psycopg2.connect(conn_string) 
print("Connection established")
cursor = conn.cursor()

# Delete data row from table
cursor.execute("DELETE FROM inventory WHERE name = %s;", ("orange",))
print("Deleted 1 row of data")

# Cleanup
conn.commit()
cursor.close()
conn.close()

다음 단계