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')>]>
1 Resposta
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
ESPECIALISTA
Uri
respondido há 10 meses
  • Great thanks do you know if there is a tutorial with the step by step and follow

Você não está conectado. Fazer login para postar uma resposta.

Uma boa resposta responde claramente à pergunta, dá feedback construtivo e incentiva o crescimento profissional de quem perguntou.

Diretrizes para responder a perguntas