[英]Python recursion error: UnboundLocalError: local variable 'n' referenced before assignment. Shuffling deck python code
[英]UnboundLocalError: local variable 'secret' referenced before assignment. AWS secrets manager python code
这是来自 AWS Secret Manager 的 python 代码。 我不确定为什么我会收到错误消息。 我尝试将 function 之外的“秘密”定义为全局变量,然后在 function 中徒劳地声明它。
请帮助我。
import boto3
import base64
from botocore.exceptions import ClientError
import json
def get_secret():
# Create a Secrets Manager client
session = boto3.session.Session()
client = session.client(
service_name='secretsmanager',
region_name=region_name
)
# In this sample we only handle the specific exceptions for the 'GetSecretValue' API.
# See https://docs.aws.amazon.com/secretsmanager/latest/apireference/API_GetSecretValue.html
# We rethrow the exception by default.
try:
get_secret_value_response = client.get_secret_value(
SecretId=secret_name
)
except ClientError as e:
if e.response['Error']['Code'] == 'DecryptionFailureException':
# Secrets Manager can't decrypt the protected secret text using the provided KMS key.
# Deal with the exception here, and/or rethrow at your discretion.
raise e
elif e.response['Error']['Code'] == 'InternalServiceErrorException':
# An error occurred on the server side.
# Deal with the exception here, and/or rethrow at your discretion.
raise e
elif e.response['Error']['Code'] == 'InvalidParameterException':
# You provided an invalid value for a parameter.
# Deal with the exception here, and/or rethrow at your discretion.
raise e
elif e.response['Error']['Code'] == 'InvalidRequestException':
# You provided a parameter value that is not valid for the current state of the resource.
# Deal with the exception here, and/or rethrow at your discretion.
raise e
elif e.response['Error']['Code'] == 'ResourceNotFoundException':
# We can't find the resource that you asked for.
# Deal with the exception here, and/or rethrow at your discretion.
raise e
else:
# Decrypts secret using the associated KMS CMK.
# Depending on whether the secret is a string or binary, one of these fields will be populated
if 'SecretString' in get_secret_value_response:
secret = get_secret_value_response['SecretString']
else:
secret = base64.b64decode(get_secret_value_response['SecretBinary'])
return json.loads(secret)
我收到以下错误:
UnboundLocalError: local variable 'secret' referenced before assignment.
修改 else 语句对我有用。
else:
# Decrypts secret using the associated KMS CMK.
# Depending on whether the secret is a string or binary, one of these fields will be populated
if 'SecretString' in get_secret_value_response:
return json.loads(get_secret_value_response['SecretString'])
return json.loads(base64.b64decode(get_secret_value_response['SecretBinary']))
我对错误的理解是变量 'secret' 是 else 块的本地变量,但它被外部引用。 以上只是纠正它的一种选择。
代码没有错。 此问题是由于错误/缺少 aws 凭据而发生的。 请检查您的凭据,确保您已连接 aws,然后重试。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.