예: Azure 라이브러리를 사용하여 데이터베이스 만들기

이 예제에서는 Python 스크립트에서 Azure SDK 관리 라이브러리를 사용하여 Azure Database for MySQL 유연한 서버 인스턴스 및 데이터베이스를 만드는 방법을 보여 줍니다. 또한 mysql 커넥터 라이브러리(Azure SDK의 일부가 아님)를 사용하여 데이터베이스를 쿼리하는 간단한 스크립트를 제공합니다. 유사한 코드를 사용하여 Azure Database for PostgreSQL 유연한 서버 인스턴스 및 데이터베이스를 만들 수 있습니다.

해당 Azure CLI 명령은 이 문서의 뒷부분에서 설명합니다. Azure Portal을 사용하려면 MySQL 서버 만들기 또는 PostgreSQL 서버 만들기를 참조하세요.

이 문서의 모든 명령은 언급되지 않는 한 Linux/macOS bash 및 Windows 명령 셸에서 동일하게 작동합니다.

1: 로컬 개발 환경 설정

아직 실행하지 않은 경우 코드를 실행할 수 있는 환경을 설정합니다. 다음은 몇 가지 옵션입니다.

2: 필요한 Azure 라이브러리 패키지 설치

다음 내용이 포함된 requirements.txt 파일을 만듭니다.

azure-mgmt-resource
azure-mgmt-rdbms
azure-identity
mysql-connector-python

가상 환경이 활성화된 터미널에서 요구 사항을 설치합니다.

pip install -r requirements.txt

참고 항목

Windows에서 32비트 Python 라이브러리에 mysql 라이브러리를 설치하려고 시도하면 mysql.h 파일에 대한 오류가 발생합니다. 이 경우 64비트 버전의 Python을 설치하고 다시 시도합니다.

3: 데이터베이스를 만드는 코드 작성

다음 코드를 사용하여 provision_db.py라는 Python 파일을 만듭니다. 주석은 세부 정보를 설명합니다. 특히 에 대한 환경 변수 및 PUBLIC_IP_ADDRESS에 대한 환경 변수를 AZURE_SUBSCRIPTION_ID 지정합니다. 후자 변수는 이 샘플을 실행할 워크스테이션의 IP 주소입니다. WhatsIsMyIP를 사용하여 IP 주소를 찾을 수 있습니다.

import random, os
from azure.identity import DefaultAzureCredential
from azure.mgmt.resource import ResourceManagementClient
from azure.mgmt.rdbms.mysql_flexibleservers import MySQLManagementClient
from azure.mgmt.rdbms.mysql_flexibleservers.models import Server, ServerVersion

# Acquire a credential object using CLI-based authentication.
credential = DefaultAzureCredential()

# Retrieve subscription ID from environment variable
subscription_id = os.environ["AZURE_SUBSCRIPTION_ID"]

# Constants we need in multiple places: the resource group name and the region
# in which we provision resources. You can change these values however you want.
RESOURCE_GROUP_NAME = 'PythonAzureExample-DB-rg'
LOCATION = "southcentralus"

# Step 1: Provision the resource group.
resource_client = ResourceManagementClient(credential, subscription_id)

rg_result = resource_client.resource_groups.create_or_update(RESOURCE_GROUP_NAME,
    { "location": LOCATION })

print(f"Provisioned resource group {rg_result.name}")

# For details on the previous code, see Example: Provision a resource group
# at https://docs.microsoft.com/azure/developer/python/azure-sdk-example-resource-group


# Step 2: Provision the database server

# We use a random number to create a reasonably unique database server name.
# If you've already provisioned a database and need to re-run the script, set
# the DB_SERVER_NAME environment variable to that name instead.
#
# Also set DB_USER_NAME and DB_USER_PASSWORD variables to avoid using the defaults.

db_server_name = os.environ.get("DB_SERVER_NAME", f"python-azure-example-mysql-{random.randint(1,100000):05}")
db_admin_name = os.environ.get("DB_ADMIN_NAME", "azureuser")
db_admin_password = os.environ.get("DB_ADMIN_PASSWORD", "ChangePa$$w0rd24")

# Obtain the management client object
mysql_client = MySQLManagementClient(credential, subscription_id)

# Provision the server and wait for the result
poller = mysql_client.servers.begin_create(RESOURCE_GROUP_NAME,
    db_server_name, 
    Server(
        location=LOCATION,
        administrator_login=db_admin_name,
        administrator_login_password=db_admin_password,
        version=ServerVersion.FIVE7
    )
)

server = poller.result()

print(f"Provisioned MySQL server {server.name}")

# Step 3: Provision a firewall rule to allow the local workstation to connect

RULE_NAME = "allow_ip"
ip_address = os.environ["PUBLIC_IP_ADDRESS"]

# For the above code, create an environment variable named PUBLIC_IP_ADDRESS that
# contains your workstation's public IP address as reported by a site like
# https://whatismyipaddress.com/.

# Provision the rule and wait for completion
poller = mysql_client.firewall_rules.begin_create_or_update(RESOURCE_GROUP_NAME,
    db_server_name, RULE_NAME, 
    { "start_ip_address": ip_address, "end_ip_address": ip_address }  
)

firewall_rule = poller.result()

print(f"Provisioned firewall rule {firewall_rule.name}")


# Step 4: Provision a database on the server

db_name = os.environ.get("DB_NAME", "example-db1")
 
poller = mysql_client.databases.begin_create_or_update(RESOURCE_GROUP_NAME,
    db_server_name, db_name, {})

db_result = poller.result()

print(f"Provisioned MySQL database {db_result.name} with ID {db_result.id}")

코드의 인증

이 문서의 뒷부분에서 Azure CLI를 사용하여 Azure에 로그인하여 샘플 코드를 실행합니다. 계정에 Azure 구독에서 리소스 그룹 및 스토리지 리소스를 만들 수 있는 권한이 있는 경우 코드가 성공적으로 실행됩니다.

프로덕션 스크립트에서 이러한 코드를 사용하려면 인증에 서비스 주체 기반 방법을 사용하도록 환경 변수를 설정할 수 있습니다. 자세한 내용은 Azure 서비스를 사용하여 Python 앱을 인증하는 방법을 참조 하세요. 서비스 주체가 Azure에서 적절한 역할(예: 구독의 기여자 역할)을 할당하여 구독에 리소스 그룹 및 스토리지 리소스를 만들 수 있는 충분한 권한이 있는지 확인해야 합니다.

PostreSQL 데이터베이스 서버는 다음을 참조하세요.

4: 스크립트 실행

  1. 아직 로그인하지 않은 경우 Azure CLI를 사용하여 Azure에 로그인합니다.

    az login
    
  2. AZURE_SUBSCRIPTION_ID 환경 변수 및 PUBLIC_IP_ADDRESS 환경 변수를 설정합니다. az account show 명령을 실행하여 출력의 속성에서 구독 ID를 id 가져올 수 있습니다. WhatsIsMyIP를 사용하여 IP 주소를 찾을 수 있습니다.

    set AZURE_SUBSCRIPTION_ID=00000000-0000-0000-0000-000000000000
    set PUBLIC_IP_ADDRESS=<Your public IP address>
    
  3. 필요에 따라 , DB_ADMIN_NAMEDB_ADMIN_PASSWORD 환경 변수를 설정합니다DB_SERVER_NAME. 그렇지 않으면 코드 기본값이 사용됩니다.

  4. 스크립트를 실행합니다.

    python provision_db.py
    

5: 레코드 삽입 및 데이터베이스 쿼리

다음 코드를 사용하여 use_db.py라는 파일을 만듭니다. 및 DB_ADMIN_NAMEDB_ADMIN_PASSWORD 환경 변수에 DB_SERVER_NAME대한 종속성을 확인합니다. 이전 코드 provision_db.py 실행의 출력 또는 코드 자체에서 이러한 값을 가져옵니다.

이 코드는 MySQL에 대해서만 작동합니다. PostgreSQL에 다른 라이브러리를 사용합니다.

import os
import mysql.connector

db_server_name = os.environ["DB_SERVER_NAME"]
db_admin_name = os.getenv("DB_ADMIN_NAME", "azureuser")
db_admin_password = os.getenv("DB_ADMIN_PASSWORD", "ChangePa$$w0rd24")

db_name = os.getenv("DB_NAME", "example-db1")
db_port = os.getenv("DB_PORT", 3306)

connection = mysql.connector.connect(user=db_admin_name,
    password=db_admin_password, host=f"{db_server_name}.mysql.database.azure.com",
    port=db_port, database=db_name, ssl_ca='./BaltimoreCyberTrustRoot.crt.pem')

cursor = connection.cursor()

"""
# Alternate pyodbc connection; include pyodbc in requirements.txt
import pyodbc

driver = "{MySQL ODBC 5.3 UNICODE Driver}"

connect_string = f"DRIVER={driver};PORT=3306;SERVER={db_server_name}.mysql.database.azure.com;" \
                 f"DATABASE={DB_NAME};UID={db_admin_name};PWD={db_admin_password}"

connection = pyodbc.connect(connect_string)
"""

table_name = "ExampleTable1"

sql_create = f"CREATE TABLE {table_name} (name varchar(255), code int)"

cursor.execute(sql_create)
print(f"Successfully created table {table_name}")

sql_insert = f"INSERT INTO {table_name} (name, code) VALUES ('Azure', 1)"
insert_data = "('Azure', 1)"

cursor.execute(sql_insert)
print("Successfully inserted data into table")

sql_select_values= f"SELECT * FROM {table_name}"

cursor.execute(sql_select_values)
row = cursor.fetchone()

while row:
    print(str(row[0]) + " " + str(row[1]))
    row = cursor.fetchone()

connection.commit()

이 코드는 모두 mysql.connector API를 사용합니다. Azure와 관련된 유일한 부분은 MySQL 서버에 대한 전체 호스트 도메인(mysql.database.azure.com)입니다.

다음으로, Azure Database for MySQL 서버 https://www.digicert.com/CACerts/BaltimoreCyberTrustRoot.crt.pem 와 TSL/SSL을 통해 통신하는 데 필요한 인증서를 다운로드하고 인증서 파일을 Python 파일과 동일한 폴더에 저장합니다. 자세한 내용은 Azure Database for MySQL 설명서에서 SSL 인증서 가져오기를 참조하세요.

마지막으로 다음 코드를 실행합니다.

python use_db.py

클라이언트 IP 주소가 허용되지 않는다는 오류가 표시되면 환경 변수 PUBLIC_IP_ADDRESS 를 올바르게 정의한 검사. 잘못된 IP 주소로 MySQL 서버를 이미 만든 경우 Azure Portal에서 다른 서버를 추가할 수 있습니다. 포털에서 MySQL 서버를 선택한 다음, 커넥트ion 보안을 선택합니다. 워크스테이션의 IP 주소를 허용된 IP 주소 목록에 추가합니다.

6: 리소스 정리

이 예제에서 만든 리소스 그룹 및 스토리지 리소스를 유지할 필요가 없는 경우 az group delete 명령을 실행합니다.

리소스 그룹은 구독에서 진행 중인 요금이 발생하지 않지만 리소스 그룹의 스토리지 계정과 같은 리소스에는 요금이 계속 부과될 수 있습니다. 적극적으로 사용하지 않는 그룹을 클린 것이 좋습니다. 인수 --no-wait 를 사용하면 작업이 완료되는 것을 기다리는 대신 명령이 즉시 반환됩니다.

az group delete -n PythonAzureExample-DB-rg  --no-wait

ResourceManagementClient.resource_groups.begin_delete 메서드를 사용하여 코드에서 리소스 그룹을 삭제할 수도 있습니다. 예제: 리소스 그룹 만들기의 코드는 사용량을 보여 줍니다.

참조용: 해당 Azure CLI 명령

다음 Azure CLI 명령은 Python 스크립트와 동일한 프로비전 단계를 완료합니다. PostgreSQL 데이터베이스의 경우 명령을 사용합니다 az postgres flexible-server .

az group create --location southcentralus --name PythonAzureExample-DB-rg

az mysql flexible-server create --location southcentralus --resource-group PythonAzureExample-DB-rg ^
    --name python-azure-example-mysql-12345 --admin-user azureuser --admin-password ChangePa$$w0rd24 ^
    --sku-name Standard_B1ms --version 5.7 --yes

# Change the IP address to the public IP address of your workstation, that is, the address shown
# by a site like https://whatismyipaddress.com/.

az mysql flexible-server firewall-rule create --resource-group PythonAzureExample-DB-rg --name python-azure-example-mysql-12345 ^
    --rule-name allow_ip --start-ip-address 10.11.12.13 --end-ip-address 10.11.12.13

az mysql flexible-server db create --resource-group PythonAzureExample-DB-rg --server-name python-azure-example-mysql-12345 ^
    --database-name example-db1

참고 항목