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

问题描述

我是气流的新手,并且在我的代码中使用了 AwsLambdaInvokeFunctionoperatorpayload 中的 OutputLocation一个变量 S3 路径,name 作为变量,我试图使用 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,)

解决方法

您要么必须将其拆分为多个较小的字符串,其中一个是 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 弦的“插入”部分为黑色,而“常规”弦部分为绿色。

,

如何把它写成一个字符串?

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