python – pymongo.errors.ServerSelectionTimeoutError: – Stack Overflow

1.I was trying to connect to my MongoDB atlas and upload some data into the database, but it showed me some error:

here are the traceback:

127.0.0.1 - - (01/Apr/2021 08:36:26) "GET /Upload HTTP/1.1" 404 -
127.0.0.1 - - (01/Apr/2021 08:36:53) "POST /upload HTTP/1.1" 500 -
Traceback (most recent call last):
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/flask/app.py", line 2464, in __call__
    return self.wsgi_app(environ, start_response)
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/flask/app.py", line 2450, in wsgi_app
    response = self.handle_exception(e)
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/flask_cors/extension.py", line 165, in wrapped_function
    return cors_after_request(app.make_response(f(*args, **kwargs)))
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/flask/app.py", line 1867, in handle_exception
    reraise(exc_type, exc_value, tb)
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/flask/_compat.py", line 39, in reraise
    raise value
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/flask/app.py", line 2447, in wsgi_app
    response = self.full_dispatch_request()
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/flask/app.py", line 1952, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/flask_cors/extension.py", line 165, in wrapped_function
    return cors_after_request(app.make_response(f(*args, **kwargs)))
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/flask/app.py", line 1821, in handle_user_exception
    reraise(exc_type, exc_value, tb)
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/flask/_compat.py", line 39, in reraise
    raise value
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/flask/app.py", line 1950, in full_dispatch_request
    rv = self.dispatch_request()
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/flask/app.py", line 1936, in dispatch_request
    return self.view_functions(rule.endpoint)(**req.view_args)
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/flask_cors/decorator.py", line 128, in wrapped_function
    resp = make_response(f(*args, **kwargs))
  File "/Users/cheliang/Desktop/capstone/app.py", line 44, in upload
    db.collection.insert_one(student)
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/pymongo/collection.py", line 698, in insert_one
    self._insert(document,
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/pymongo/collection.py", line 613, in _insert
    return self._insert_one(
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/pymongo/collection.py", line 602, in _insert_one
    self.__database.client._retryable_write(
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/pymongo/mongo_client.py", line 1497, in _retryable_write
    with self._tmp_session(session) as s:
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/contextlib.py", line 113, in __enter__
    return next(self.gen)
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/pymongo/mongo_client.py", line 1829, in _tmp_session
    s = self._ensure_session(session)
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/pymongo/mongo_client.py", line 1816, in _ensure_session
    return self.__start_session(True, causal_consistency=False)
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/pymongo/mongo_client.py", line 1766, in __start_session
    server_session = self._get_server_session()
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/pymongo/mongo_client.py", line 1802, in _get_server_session
    return self._topology.get_server_session()
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/pymongo/topology.py", line 490, in get_server_session
    self._select_servers_loop(
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/pymongo/topology.py", line 215, in _select_servers_loop

Here are error messages:
pymongo.errors.ServerSelectionTimeoutError: cluster0-shard-00-00.nspcw.mongodb.net:27017: (SSL: CERTIFICATE_VERIFY_FAILED) certificate verify failed: unable to get local issuer certificate (_ssl.c:1123),cluster0-shard-00-02.nspcw.mongodb.net:27017: (SSL: CERTIFICATE_VERIFY_FAILED) certificate verify failed: unable to get local issuer certificate (_ssl.c:1123),cluster0-shard-00-01.nspcw.mongodb.net:27017: (SSL: CERTIFICATE_VERIFY_FAILED) certificate verify failed: unable to get local issuer certificate (_ssl.c:1123), Timeout: 30s, Topology Description: <TopologyDescription id: 6064eafc226370cef0493727, topology_type: ReplicaSetNoPrimary, servers: (<ServerDescription ('cluster0-shard-00-00.nspcw.mongodb.net', 27017) server_type: Unknown, rtt: None, error=AutoReconnect('cluster0-shard-00-00.nspcw.mongodb.net:27017: (SSL: CERTIFICATE_VERIFY_FAILED) certificate verify failed: unable to get local issuer certificate (_ssl.c:1123)')>, <ServerDescription ('cluster0-shard-00-01.nspcw.mongodb.net', 27017) server_type: Unknown, rtt: None, error=AutoReconnect('cluster0-shard-00-01.nspcw.mongodb.net:27017: (SSL: CERTIFICATE_VERIFY_FAILED) certificate verify failed: unable to get local issuer certificate (_ssl.c:1123)')>, <ServerDescription ('cluster0-shard-00-02.nspcw.mongodb.net', 27017) server_type: Unknown, rtt: None, error=AutoReconnect('cluster0-shard-00-02.nspcw.mongodb.net:27017: (SSL: CERTIFICATE_VERIFY_FAILED) certificate verify 

2.Here is my code to upload the file to MongoDB Atlas and I’M pretty sure I entered the correct URL to connect the database. I tried to create another flask project, and just simply use pymongo to MongoDB atalas. Then I can upload and delete data in the database successfully. Does this error happen because of something related to the front end? Currently, I’m trying to receive the data from the frontend(backend) and then upload file into the mongodb atalas database
:

from flask import Flask, flash, jsonify, request, render_template, make_response, redirect, url_for, abort
from werkzeug.utils import secure_filename
from flask_cors import CORS,cross_origin
from flask_restful import Api, Resource, reqparse
import os
import json
import pymongo
client = pymongo.MongoClient("mongodb://123:123@cluster0-shard-00-00.nspcw.mongodb.net:27017,cluster0-shard-00-01.nspcw.mongodb.net:27017,cluster0-shard-00-02.nspcw.mongodb.net:27017/myFirstDatabase?ssl=true&replicaSet=atlas-k7vjf4-shard-0&authSource=admin&retryWrites=true&w=majority")
db = client.datasets
app = Flask(__name__)
app.config('UPLOAD_PATH') = './public' # to create a folder which is used to save the uploaded file
CORS(app)

@app.route('/upload', methods=("GET", "POST"))
@cross_origin()
def upload():
    if request.method == "POST":

        # check if the post request has the file part
        if 'file' not in request.files:
            flash("No file part")
            return redirect(request.url)
        
        uploaded_file = request.files('file')
        print(uploaded_file)
        # if user does not select file browser also
        # submit an empty part without filename
        if uploaded_file.filename == '':
            flash('No selected file')
            return redirect(request.url)

        # check if the post request has the file part
        filename = secure_filename(uploaded_file.filename)
        print(filename) # e.g. ex.csv
        # TODO: PLEASE deal with the filename to avoid repeating name here
        file_ext = os.path.splitext(filename)(1) # get extenson of a file, like .csv
        # TODO: (replace the code below) save the file to MongoDB
        uploaded_file.save(os.path.join(app.config('UPLOAD_PATH'), filename))
        student = {
        "Name":"111",
        "TEST":"--"
        }
        collection = db.TESTQUIZ
        db.collection.insert_one(student)

        print(collection)
        

        return filename


@app.route('/datasetFiles', methods=("GET", "POST"))
def showAlldatasetFiles():
    if request.method == "GET":
        # read datasets JSON file
        # TODO: You should get the same format of (_id, FileName, Size) from MongoDB, then replace it
        # TODO: return a empty () to me if there is no file in the MongoDB
        with open('./datasetFiles.json') as f:
            data = json.load(f)
        #print(data)
    return json.dumps(data)

@app.route('/newDataset', methods=("GET"))
def sendNewdatasetFiles():
    # TODO: (replace the code below) get the uploaded dataset from MongoDB with _id, FileName, Size
    # because frontend cannot show the new file until it is saved into the MongoDB, and frontend cannot generate _id itself
    # Here, I'll create a uploaded file JSON myself, please delete it when you finish this TODO
    new_dataset = ({"_id": {"$oid": "6061862b0d830ba54020706d"},"FileName": "ex_fdy.csv", "Size": "4.68KB"})

    return json.dumps(new_dataset)


if __name__ == "__main__":
    app.run(debug = True)