クイック スタート:Python を使用して Azure Database for PostgreSQL - フレキシブル サーバーに接続し、データのクエリを実行する

適用対象: Azure Database for PostgreSQL - フレキシブル サーバー

このクイックスタートでは、Python を使用して Azure Database for PostgreSQL のフレキシブル サーバー インスタンスに接続します。 macOS、Ubuntu Linux、Windows の各プラットフォームから SQL ステートメントを使用して、データベース内のデータを照会、挿入、更新、削除できます。

この記事の手順には、Microsoft Entra 認証と PostgreSQL 認証の 2 つの認証方法が含まれています。 [パスワードレス] タブには 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 管理者] にアカウントの一覧が表示されていることを確認します。 そうでない場合は、「サーバーで Microsoft Entra 統合を構成する (パスワードレスのみ)」の手順を完了します。
  3. 接続 URI 要素用の環境変数を設定します。

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

    コマンドで次のプレースホルダー値を置き換えます。

    • <server-name> を、Azure portal からコピーした値に置き換えます。
    • <username> を、Azure ユーザー名に置き換えます。例: [https://login.microsoftonline.com/consumers/](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()

次のステップ