Pymongo connection issue in AWS Lambda

0

How to connect AWS Lambda in python with MonboDB cluster, here is the sample code:

import pymongo
import json
from urllib.parse import quote_plus
username = quote_plus('user')
password = quote_plus('pwd')
cluster = 'ai-beta.60op4nu.mongodb.net'
authSource = 'database'
authMechanism = 'SCRAM-SHA-256'
uri = 'mongodb+srv://' + username + ':' + password + '@' + cluster + '/?authSource=' + authSource + '&authMechanism=' + authMechanism
print(uri)
try:
    client = pymongo.MongoClient(uri)
    result = client['truvideo']['dealers'].find()
    for x in result:
        print(x)
except Exception as e:
    print("An error occurred:", e)

But always i got en error like this:

An error occurred: ac-7itqhz7-shard-00-00.60op4nu.mongodb.net:27017: connection closed,ac-7itqhz7-shard-00-02.60op4nu.mongodb.net:27017: connection closed,ac-7itqhz7-shard-00-01.60op4nu.mongodb.net:27017: connection closed, Timeout: 30s, Topology Description: <TopologyDescription id: 64ca404b198e0bba955fe143, topology_type: ReplicaSetNoPrimary, servers: [<ServerDescription ('ac-7itqhz7-shard-00-00.60op4nu.mongodb.net', 27017) server_type: Unknown, rtt: None, error=AutoReconnect('ac-7itqhz7-shard-00-00.60op4nu.mongodb.net:27017: connection closed')>, <ServerDescription ('ac-7itqhz7-shard-00-01.60op4nu.mongodb.net', 27017) server_type: Unknown, rtt: None, error=AutoReconnect('ac-7itqhz7-shard-00-01.60op4nu.mongodb.net:27017: connection closed')>, <ServerDescription ('ac-7itqhz7-shard-00-02.60op4nu.mongodb.net', 27017) server_type: Unknown, rtt: None, error=AutoReconnect('ac-7itqhz7-shard-00-02.60op4nu.mongodb.net:27017: connection closed')>]>
asked 9 months ago345 views
1 Answer
0

You got a timeout most probably because your Lambda function was not able to reach the database. Is your database in a VPC? If so, the Lambda should be attached to the VCP as well and the security groups should allow the connection. If your DB is on the internet, your Lambda function should have internet access, i.e., either it is not attached to a VPC, or, if attached, there should be a NAT Gateway in the VPC that lets the function access the internet.

profile pictureAWS
EXPERT
Uri
answered 9 months ago
  • Great thanks do you know if there is a tutorial with the step by step and follow

You are not logged in. Log in to post an answer.

A good answer clearly answers the question and provides constructive feedback and encourages professional growth in the question asker.

Guidelines for Answering Questions