首页 > 解决方案 > 如何将条件传递给游标中的 PostgreSQL 查询

问题描述

我正在尝试将条件传递给查询,并且在 apache 气流中使用 PostgreSQLHook。当我运行 dag 时出现错误

TypeError:“日期时间”类型的对象不是 JSON 可序列化的

目前我将我的 sql 存储在一个不同的文件中,并且我正在导入该文件以在我的 python 文件中执行。

sql pg_query文件

SELECT
    *
FROM
    public.airtimes
WHERE created_at > '{}';

蟒蛇脚本

def read_latest_data_from_pg(**kwargs):
    with open('dags/scripts/sql_scripts/pg_query.sql','r') as sqlfile:
            pg_export_data_query=str(sqlfile.read())
    pg_date = '2021-05-01'
    pg_hook = PostgresHook(postgres_conn_id='pg_conn', delegate_to=None, use_legacy_sql=False)
    conn = pg_hook.get_conn()
    cursor = conn.cursor()
    cursor.execute(pg_export_data_query.format(pg_date))
    result = cursor.fetchall()
    print('result', result)
    return result

我错过了什么?

标签: pythonpostgresqlcursorairflow

解决方案


推荐阅读