【问题标题】:How to define Lambda variables to query Redshift over API Gateway如何定义 Lambda 变量以通过 API Gateway 查询 Redshift
【发布时间】:2021-03-17 12:01:44
【问题描述】:

我遇到了一个问题,如何为 API Gateway 设置参数以使用 Lambda 函数查询 Amazon Redshift。

我的连接工作正常,但我一直得到全表响应。 我需要定义变量,用户可以查询特定的参数、值和模式

有人可以建议一个示例如何设置它

我的配置是:

    #!/usr/bin/env python

import psycopg2
import logging
import traceback
import json
from os import environ

query="SELECT * from public"

logger=logging.getLogger()
logger.setLevel(logging.INFO)

def make_connection():
    conn=psycopg2.connect(dbname= 'database', host='redshift-cluster.amazonaws.com',
    port= '5439', user= 'user', password= 'password')
    conn.autocommit=True
    return conn


    def log_err(errmsg):
        logger.error(errmsg)
        return {"body": errmsg , "headers": {}, "statusCode": 400,
        "isBase64Encoded":"false"}

        logger.info("Cold start complete.")

        print('Loading Function')

        def handler(event,context):

            try:
                cnx = make_connection()
                cursor=cnx.cursor()

                try:
                    cursor.execute(query)
                except:
                    return log_err ("ERROR: Cannot execute cursor.\n{}".format(
                    traceback.format_exc()) )

                    try:
                        results_list=[]
                        for result in cursor: results_list.append(result)
                        print(results_list)
                        cursor.close()

                    except:
                        return log_err ("ERROR: Cannot retrieve query data.\n{}".format(
                        traceback.format_exc()))


                        return {"body": str(results_list), "headers": {}, "statusCode": 200,
                        "isBase64Encoded":"false"}


                    except:
                        return log_err("ERROR: Cannot connect to database from handler.\n{}".format(
                        traceback.format_exc()))


                    finally:
                        try:
                            cnx.close()
                        except:
                            pass


                            if __name__== "__main__":
                                handler(None,None)

【问题讨论】:

    标签: sql amazon-web-services aws-lambda amazon-redshift aws-api-gateway


    【解决方案1】:

    我会推荐Using the Amazon Redshift Data API,而不是使用psycopg2。它提供了一种在 Amazon Redshift 上运行查询的更简单方法。

    首先,使用execute_statement() 发送查询,然后使用get_statement_result() 检索结果。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-08-19
      • 1970-01-01
      • 2017-04-13
      • 2019-10-20
      • 2021-01-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多