简体   繁体   English

使用 psycopg2 的 Lambda 函数 python 脚本

[英]Lambda function python script using psycopg2

Full screenshot完整截图

Runtime settings运行时设置

I am going to connect RDS postgresql Database using Lambda function (python script) I attached screenhot.我将使用我附加的屏幕截图的 Lambda 函数(python 脚本)连接 RDS postgresql 数据库。 The error logs here.错误记录在这里。 Unable to import module 'postgres_test': No module named 'psycopg2'

python version is 3.6 python版本是3.6

This issue causing due to not installed psycopg2 package.由于未安装 psycopg2 软件包而导致的此问题。 Then I don't know how can I install the package on lambda Pls guide me for it.然后我不知道如何在 lambda 上安装该软件包,请指导我。

postgres_test.py: postgres_test.py:

` `

import sys
import logging
import psycopg2

from db_util import make_conn, fetch_data
def lambda_handler(event, context):
query_cmd = "select count(*) from tablename"
# print query_cmd

# get a connection, if a connect cannot be made an exception will be raised here
conn = make_conn()

result = fetch_data(conn, query_cmd)
conn.close()

return result

db_util.py: db_util.py:

` ​`

   ​import psycopg2

   ​db_host = "db_host" 
   ​db_port = 5432
   ​db_name = "db_name "
   ​db_user = "db_user "
   ​db_pass = "db_pass "
   ​db_table = "users"


   ​def make_conn():
       ​conn = None
       ​try:
           ​conn = psycopg2.connect("dbname='%s' user='%s' host='%s' 
   ​password='%s'" % (db_name, db_user, db_host, db_pass))
       ​except:
           ​print "I am unable to connect to the database"
       ​return conn


   ​def fetch_data(conn, query):
       ​result = []
       ​print "Now executing: %s" % (query)
       ​cursor = conn.cursor()
       ​cursor.execute(query)

       ​raw = cursor.fetchall()
       ​for line in raw:
           ​result.append(line)

       ​return result

To work with different libraries in lambda you have to install the library in the current project and upload it as zip file to lambda.要在 lambda 中使用不同的库,您必须在当前项目中安装该库并将其作为 zip 文件上传到 lambda。

Specific to psycopg2 use this repo https://github.com/jkehler/awslambda-psycopg2特定于 psycopg2 使用此 repo https://github.com/jkehler/awslambda-psycopg2

And to install some other library use the below command并安装一些其他库使用以下命令
For example requests library例如requests

pip install requests -t .

Your project will look something like below您的项目将如下所示

.
├── lambda_function.py
├── psycopg2
├── <library2>

To upload a project to lambda using zip file method you can use the following links要使用 zip 文件方法将项目上传到 lambda,您可以使用以下链接

https://docs.aws.amazon.com/lambda/latest/dg/gettingstarted-package.html https://alexharv074.github.io/2018/08/18/creating-a-zip-file-for-an-aws-lambda-python-function.html https://docs.aws.amazon.com/lambda/latest/dg/gettingstarted-package.html https://alexharv074.github.io/2018/08/18/creating-a-zip-file-for-an -aws-lambda-python-function.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM