python-3.x 尝试将本地Azure函数连接到Mongo的本地Docker示例,但不断收到服务器选择错误

u1ehiz5o  于 2023-06-07  发布在  Python
关注(0)|答案(1)|浏览(83)

我希望正常运行该函数,能够连接到数据库,但它一直返回服务器选择错误,我尝试使用localhost和172.17.0.2(这是docker检查结果),它根本无法连接。问题不在于数据库,因为我可以通过localhost和172.17.0.2连接到它。
我已经将MONGO_URL env var添加到local.settings.json中,由于它表示无法连接到正确的IP,因此它被抓取

env = os.getenv("MONGO_URL")
client = pymongo.MongoClient(env)
db = client["data"]
col = db["objects"]

而且,奇怪的是,当我试图调试客户机调用时,我尝试在客户机调用之前打印内容,而连接将在print语句之前运行,即使它们被放置在连接之前

[2023-05-31T16:04:33.213Z] Executed 'Functions.HttpTrigger1' (Failed, Duration=30422ms)
[2023-05-31T16:04:33.213Z] System.Private.CoreLib: Exception while executing function: Functions.HttpTrigger1. System.Private.CoreLib: Result: Failure
[2023-05-31T16:04:33.213Z] Exception: ServerSelectionTimeoutError: 172.17.0.2:27017: timed out, Timeout: 30s, Topology Description: <TopologyDescription topology_type: Unknown, servers: [<ServerDescription ('172.17.0.2', 27017) server_type: Unknown, rtt: None, error=NetworkTimeout('172.17.0.2:27017: timed out')>]>

我认为这很好,但以防万一,这是我的local.settings.json

{
  "IsEncrypted": false,
  "Values": {
    "FUNCTIONS_WORKER_RUNTIME": "python",
    "AzureWebJobsStorage": "UseDevelopmentStorage=true",
    "AzureWebJobsFeatureFlags": "EnableWorkerIndexing",
    "MONGO_URL": "mongodb://172.17.0.2:27017"
  }
}
piah890a

piah890a1#

Microsoft Azure Cosmos DB for MongoDBAzure function

connection_string = os.environ["MongoConnectionString"]
try:

client = MongoClient(connection_string)

db = client['your_database_name']

collection = db['your_collection_name']

documents = collection.find()

for  document  in  documents:
logging.info(document)

return  func.HttpResponse("Data retrieved successfully.")

except  pymongo.errors.PyMongoError as  e:

logging.error('Error connecting to Azure Cosmos DB: %s',  str(e))

return  func.HttpResponse("Error connecting to Azure Cosmos DB.",  status_code=500)

输出:

相关问题