三引号字符串中的f字符串

2024-05-29 05:48:02 发布

您现在位置:Python中文网/ 问答频道 /正文

我对airflow是新手,在代码中使用AwsLambdaInvokeFunctionOperator有效负载中的OutputLocation是一个变量S3路径,其中名称作为变量,我试图使用fstring实现它,但没有成功。 有人可以指导我如何在有效负载的路径中使用变量名吗

client=boto3.Session().client('ssm')

NAME=client.get_parameter(
     Name='name',
     WithDecryption=True
 )['Parameter']['Value']
test_lambda = AwsLambdaInvokeFunctionOperator(
    region_name='ap-southeast-1',
    check_success_function=lambda_pass,
    task_id="test_lambda",
    function_name='test-function',
    awslogs_group="/airflow/lambda/{0}".format('test-function'),
    payload="""{
                "AthenaOut":{"QueryExecution": {"ResultConfiguration": {"OutputLocation": 
                f"s3://datasource/test/{name}/output/result.csv" }}},
                "primary_keys":["id"],
                "table": "student",
                 "schema": "public" 
              }""",
    dag=dag,
    depends_on_past=False,
    wait_for_downstream=False,
)

Tags: lambda代码nametest路径clientidfalse
2条回答

把它写成字符串怎么样

payload=json.dumps({
    "AthenaOut": {
        "QueryExecution": {
            "ResultConfiguration": {
                "OutputLocation": f"s3://datasource/test/{name}/output/result.csv"
            }
        }
    },
    "primary_keys": ["id"],
    "table": "student",
    "schema": "public",
}),

您可以将其拆分为多个较小的字符串,其中一个是f字符串:

payload= '{' \
                + '"AthenaOut":{"QueryExecution": {"ResultConfiguration": {"OutputLocation": ' \
                + f'"s3://datasource/test/{name}/output/result.csv"' \
                + ' }}},' \
                + '"primary_keys":["id"],' \
                + '"table": "student",' \
                + ' "schema": "public" ' \
              + '}'

或者需要将整个三引号设为f字符串,这将需要转义所有的花括号(双花括号{{是f字符串中的文字花括号):

payload=f"""{{
                "AthenaOut":{{"QueryExecution": {{"ResultConfiguration": {{"OutputLocation": 
                "s3://datasource/test/{name}/output/result.csv" }}}}}},
                "primary_keys":["id"],
                "table": "student",
                 "schema": "public" 
              }}"""

注意上面代码块中突出显示的语法。f字符串的“插入”部分为黑色,而“常规”字符串部分为绿色

相关问题 更多 >

    热门问题