Python Class(クラス)インスタンスからDictに変換

Python Class(クラス)インスタンスからDictに変換

Pythonクラスインスタンスから Dictに 変換するコード例です。

下のような クラスを用意しました

class UserRow:
    def __init__(self, id, name):        
        self.name = name
        self.id = id

このUserRow クラス インスタンスを使った変数を用意し print()すると 下記のように 表示されます

print()してもクラスの中身は見れません

中身を表示したい場合、 dictに変換すると print()でも表示できます。

dict に変換しprint()

vars()を 使えば dict型の変数に 変換できます

class UserRow:
    def __init__(self, id, name):        
        self.name = name
        self.id = id

user_row = UserRow(123,"my name") #クラスインスタンス作成
user_dict = vars(user_row) #varsで クラスインスタンスからdict型変数へ変換
print(user_dict)

結果、 「{‘name’: ‘my name’, ‘id’: 123}」←のように表示されました

Python Cognito AccessTokenからUserAttributesを取得

Pythonスクリプトを使って、 Amazon Cognitoで作成したユーザープールの ユーザーに接続し AccessTokenからUserAttributesを取得する方法です。

Cognitoの ユーザープール側は、 [アプリケーションクライアント]の「認証フロー」で、 ALLOW_ADMIN_USER_PASSWORD_AUTHに チェックする必要があります。

認証のための管理 API のユーザー名パスワード認証
import boto3

config = {
    "profile":None,
    "pool_id": "プールID",
    "client_id": "クライアントID",
    "region": "リージョン"
}

try:
    session = boto3.Session(profile_name=config['profile'])
    # aws_access_key_id, aws_secret_access_keyを入れる場合↓
    cognito = session.client('cognito-idp', region_name=config['region'])
    res = cognito.admin_initiate_auth(
            UserPoolId = config["pool_id"],
            ClientId = config["client_id"],
            AuthFlow = "ADMIN_USER_PASSWORD_AUTH",
            AuthParameters = {
                "USERNAME": "ユーザー名",
                "PASSWORD": "パスワード",
            }
    )
    user_info = cognito.get_user(AccessToken=res["AuthenticationResult"]["AccessToken"])
    for info in  user_info['UserAttributes']:
        print(f"{info['Name']}:{info['Value']}")
except Exception as e:
    print(e)

Cognito 設定画面[アプリケーションクライアント]の 認証フローで ALLOW_ADMIN_USER_PASSWORD_AUTHが 設定されていない場合、 下のInvalidParameterExceptionが 出ます

An error occurred (InvalidParameterException) when calling the AdminInitiateAuth operation: Auth flow not enabled for this client

ユーザー名もしくはパスワードが 間違えている場合 NotAuthorizedExceptionです

An error occurred (NotAuthorizedException) when calling the AdminInitiateAuth operation: Incorrect username or password.
2022 MJELD TECHNOLOGIES. ALL RIGHTS RESERVED