0

I'm currently trying to implement a user creation & login system in my Flask webapp using MongoDB Atlas (so it's a cloud server which I think makes a big difference for this error), mongoengine, and pymongo (all latest versions as of this post). Whenever I submit the username and password on the create-user form and try to validate that the username doesn't already exist by querying the database, I get this error message:

pymongo.errors.ServerSelectionTimeoutError: localhost:27017: [WinError 10061] No connection could be made because the target machine actively refused it

And here is the full traceback:

    File "C:\Programming\Python\Lib\site-packages\flask\app.py", line 2463, in __call__
    return self.wsgi_app(environ, start_response)
  File "C:\Programming\Python\Lib\site-packages\flask\app.py", line 2449, in wsgi_app
    response = self.handle_exception(e)
  ...
    rv = self.dispatch_request()
  File "C:\Programming\Python\Lib\site-packages\flask\app.py", line 1935, in dispatch_request
    return self.view_functions[rule.endpoint](**req.view_args)
  File "C:\Programming\Khimbus\src\client\views\user_views.py", line 27, in create_user
    account_exists = find_user_by_username(username)
  File "C:\Programming\Khimbus\src\services\user_service.py", line 20, in find_all_users
    users = User.objects()
  File "C:\Programming\Python\Lib\site-packages\mongoengine\queryset\manager.py", line 37, in __get__
    queryset = queryset_class(owner, owner._get_collection())
  File "C:\Programming\Python\Lib\site-packages\mongoengine\document.py", line 207, in _get_collection
    db.client.is_primary:
  File "C:\Programming\Python\Lib\site-packages\pymongo\mongo_client.py", line 1006, in is_primary
    return self._server_property('is_writable')
  File "C:\Programming\Python\Lib\site-packages\pymongo\mongo_client.py", line 830, in _server_property
    server = self._topology.select_server(
  File "C:\Programming\Python\Lib\site-packages\pymongo\topology.py", line 229, in select_server
    return random.choice(self.select_servers(selector,
  File "C:\Programming\Python\Lib\site-packages\pymongo\topology.py", line 188, in select_servers
    server_descriptions = self._select_servers_loop(
  File "C:\Programming\Python\Lib\site-packages\pymongo\topology.py", line 204, in _select_servers_loop

The REST endpoint:

    @user_views.route('/create-user', methods=['GET', 'POST'])
    def create_user():
    if request.method == 'POST':
        print('Creating user...')
        username = request.form['username']
        password = request.form['password']

        account_exists = find_user_by_username(username)
        if account_exists:
            print(f'Error: Account with {username} already exists.')
            return render_template('error_page.html')

        hashpass = generate_password_hash(password)
        user_state.active_account = create_user(username, hashpass)
        print(user_state.active_account.username)
        session['username'] = user_state.active_account.username
        resp = jsonify('Created new account!')
        resp.status_code = 200
        return resp

    return render_template('create_user.html')

Find user method:

def find_user_by_username(username: str) -> User:
    print('Finding user...')
    user = User.objects(username=username)
    print('Found user' + user)
    return user

I'm not sure what's going on here, and other related questions cover a different error code or are too outdated to help me with MongoDB Atlas. I would appreciate any and all information!

Update: Solved

When I installed MongoDB, I didn't install it as a Windows service. I reinstalled it as such and user creation is now working fine.

Community
  • 1
  • 1
Eli
  • 51
  • 2
  • 7

3 Answers3

2

examinate mongodb is running or not

  1. please execute netstat -tlnp in your local machine
  2. make sure port 27017 is existing from the result

install mongodb in your local machine

please check below: mongodb installation

start mongodb

systemctl start mongod

sadpepe
  • 168
  • 10
  • The 27017 port was indeed missing from the list, however `http://127.0.0.1:5000/` is in the list, and that's the localhost address that Flask is supposedly running on (https://i.gyazo.com/5737728781ffeac5f757fe9484894f68.png). So I'm not sure why it's trying to make a connection to localhost:27017 in the first place... – Eli Dec 04 '19 at 17:16
  • I should also mention that I already installed mongodb using that link and did the default installation and added the appropriate PATH variable for mongodb. But for some reason running `systemctl start mongod` doesn't do anything, `systemctl` is not even recognized. – Eli Dec 04 '19 at 20:04
  • it looks like function `find_user_by_username` in your code requires you to connect mongodb – sadpepe Dec 05 '19 at 06:52
  • 1
    if you are using window, you should take a look into mongodb manunal [here](https://docs.mongodb.com/manual/tutorial/install-mongodb-on-windows/), `systemctl` is only for linux system – sadpepe Dec 05 '19 at 06:53
  • Wow, good call. I didn't install MongoDB as a Windows service. I installed it and got it up and running. Now I just need to figure out why the user I create isn't actually saved to the database... – Eli Dec 05 '19 at 20:19
1

You mentioned you are using atlas but the error is connecting to localhost. Somewhere you need to configure the atlas connection string in the MongoClient object.

Belly Buster
  • 8,224
  • 2
  • 7
  • 20
  • I do this in my app.py: `app.config["MONGO_URI"] = "mongodb+srv://" + username + ":" + pwd + "@khimbus-fphpr.gcp.mongodb.net/test?retryWrites=true&w=majority"` This is the server connection string atlas provided for me, with username & password replaced by the obvious. – Eli Dec 04 '19 at 17:10
  • Well for some reason those settings are not being picked up. The setup you mentions refers to flask but the error is coming from mongoengine. Are you sure mongoengire has the correct config? – Belly Buster Dec 04 '19 at 23:54
0

from pythonexamples! We have seen what could cause this error. Cross check the following things to make a connection to the MongoDB instance.

Make sure that your MongoDB instance is running. Go to processes and check if mongod.exe is running.

Windows: Check in Task Manager Ubuntu: Run the command “ps -aef” and look for mongod process Check if the URL that you provided is correct. Check for the correctness of IP address and PORT at which Mongo Daemon is running.

to install MongoDB on windows: Check: from pythonexamples!

Amgad
  • 33
  • 6