如何解决python+flask+mongodb ServerSelectionTimeoutError?

问题描述 投票:0回答:2

我是 mondodb 的新手。我已经安装了 mongodb 并且它在终端中工作正常。

enter image description here

但是当我通过 Flask 应用程序连接时。它会引发 ServerSelectionTimeoutError 错误。可能是什么问题?

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)

错误: enter image description here

python mongodb flask pymongo
2个回答
1
投票

问题可能是您无法连接到数据库,是否您没有以正确的顺序和正确的变量插入所有变量? 例如,当 MongoDB 客户端收到格式 {}:{} 时 第二个 {} 应代表端口(通常为 27017),第一个 {} 是 IP,因此最终结果应如下所示:

client = MongoClient("mongodb://%s:%d" % (config["address"], 27017),
                                      username=config["username"],
                                      password=config["password"])

-1
投票

您可以尝试使用 mongodb atlas 集群,确保进入网络访问并添加 IP 地址 0.0.0/0 以允许每个人进行连接,然后尝试在浏览器中运行 API 并查看它是否返回预期的数据

© www.soinside.com 2019 - 2024. All rights reserved.