I am new to mondodb. I have installed mongodb and its working fine in the terminal.
But when i connect via flask app. It throws the ServerSelectionTimeoutError error. What could be the issue?
import datetime
import os
import urllib
import pymongo
from flask import Flask
app = Flask(__name__)
app.config['DEBUG'] = True
config = {
"username": "vishesh",
"password": "Test@123",
"server": "mongo",
}
connector = "mongodb://{}:{}@{}".format(urllib.parse.quote(config['username']), urllib.parse.quote(config['password']), urllib.parse.quote(config['server']))
client = pymongo.MongoClient(connector)
db = client.get_database('alertme')
@app.route('/')
def hello():
print(db.alerts.find()) ## Returns: <pymongo.cursor.Cursor object at 0x7f7eb2190c10>
blah = list(db.alerts.find())
return blah
if __name__ == '__main__':
port = int(os.environ.get('PORT', 5000))
app.run(port = port)
the issue is probably that you failed to connect to the data base could it be that you didn't insert all the variables in the correct order and the correct variables? for example when the MongoDB client receives the format {}:{} the second {} should represent the port(typically 27017) and the first {} is the ip so the final result should look something like this:
client = MongoClient("mongodb://%s:%d" % (config["address"], 27017),
username=config["username"],
password=config["password"])