Forums

MongoDB error when running a web app but not when running normal script

I have a virtualenv set up with all my packages that are needed installed. When I run a test script that simply queries a MongoDB atlas it works perfectly, however when I use a web app and flask it times out and a 500 internal server error pops up.

I've already checked that they are both running off the same virtualenv and I upgraded to hacker as another topic suggested that would help however I'm all out of idea, any point in the right direction would be awesome, thanks!

Can you share the code (anonymized as necessary) that is giving you problems?

.

# A very simple Flask Hello World app for you to get started with...

from flask import Flask, jsonify
from pymongo import MongoClient

client = MongoClient("mongodb+srv://<personal_details>.mongodb.net/test")
db=client.scpDatabase

app = Flask(__name__)

@app.route('/')
def hello_world():
    return 'default page'

@app.route('/<path:dummy>')
def fallback(dummy):
   return jsonify(db.<personal>.find_one({'_id': <personal>}),204)

if __name__ == '__main__':
    app.run()

Is the code that doesnt work when run on the virtualenv and as a web app.

from pymongo import MongoClient
#Step 1: Connect to MongoDB - Note: Change connection string as needed
client = MongoClient("mongodb+srv://<personal_details.mongodb.net/test")
db=client.scpDatabase
print(db.<personal>.find_one({'_id':<personal>}))
dict = db.<personal>.find_one({'_id':<personal>})
for x in dict['body']:
    print(x)

Is the code that works when run from bash under the same virtualenv

pymongo.errors.ServerSelectionTimeoutError: No replica set members found yet

That is the error I'm receiving.

I haven't made any progress on it since yesterday, and nothing I've found has really helped. Thanks for your input but, I should have provided code.

Ah, I think I know what's causing that. We don't support threads in web apps, and by default the MongoClient object tries to create threads. Could you try adding these parameters to the line where you create the client object?

connectTimeoutMS=30000, socketTimeoutMS=None, socketKeepAlive=True, connect=False, maxPoolsize=1

It would be great to know if they help -- we've heard from some people that they fix the problem and from others that they don't, so we're hesitant to put them on a help page without gathering more data.

Awesome it works now Giles, I really appreciate the help. Ive heard that there can be issues with python anywhere and some connection methods but this works perfectly. Loads instantly!

Excellent! Thanks for confirming. I'll put together something in the help pages to cover this.

OK, here's a help page about MongoDB on PythonAnywhere that hopefully will be useful for anyone else with the same problem in the future. Any suggestions for extra stuff we should put on there much appreciated!

This works only in the paid account? Or free account also can use mongodb atlas ?

Only paid accounts can use MongoDB atlas.

Hi. I paid for the account, but I still get this error. what could be wrong? pymongo.errors.ServerSelectionTimeoutError: No replica set members found yet, Timeout: 30s

See the help page posted previously in this thread.

I just added these options to the config and it worked for me. Thanks 'connectTimeoutMS': 30000, 'socketTimeoutMS': None, 'connect': False, 'maxPoolsize': 1

Excellent, thanks for confirming!

I'm having the same issue but mine's not getting solved using 'connectTimeoutMS': 30000, 'socketTimeoutMS': None, 'connect': False, 'maxPoolsize': 1

You will not be able to connect to MongoDB from a free account.

If I get the Hacker plan, do I need to follow any special instructions for it to work or will it auto work?

My error log can pls help understand and resolve this - https://www.pythonanywhere.com/user/Jahnvi371/files/var/log/jahnvi371.pythonanywhere.com.error.log. I've purchased the Hacker plan already.

That looks like pymongo requires a specific version of the OpenSSL package. Check the pymongo documentation and make sure that you have the correct version of the required libraries installed.

Its working thanks a lot!!

I just upgraded to a paying plan. Followed the above instructions for the connection parameter but the connection fails nonetheless when I run it from Pythonanywhere ("SSL handshake failed" see details below). I whitelisted pythonanywhere ip address with MONGO DB Atlas. Any suggestion what I should do/try? thank you

pymongo.errors.ServerSelectionTimeoutError: SSL handshake failed: ac-0qdd9aa-shard-00-01.t7ljuzh.mongodb.net:27017: [('SSL routines', '', 'tlsv1 alert internal error')],SSL handshake failed: ac-0qdd9aa-shard-
00-00.t7ljuzh.mongodb.net:27017: [('SSL routines', '', 'tlsv1 alert internal error')],SSL handshake failed: ac-0qdd9aa-shard-00-02.t7ljuzh.mongodb.net:27017: [('SSL routines', '', 'tlsv1 alert internal error'
)], Timeout: 30s, Topology Description: <TopologyDescription id: 6627fd5d065f2a63461f9b73, topology_type: ReplicaSetNoPrimary, servers: [<ServerDescription ('ac-0qdd9aa-shard-00-00.t7ljuzh.mongodb.net', 27017
) server_type: Unknown, rtt: None, error=AutoReconnect("SSL handshake failed: ac-0qdd9aa-shard-00-00.t7ljuzh.mongodb.net:27017: [('SSL routines', '', 'tlsv1 alert internal error')]")>, <ServerDescription ('ac
-0qdd9aa-shard-00-01.t7ljuzh.mongodb.net', 27017) server_type: Unknown, rtt: None, error=AutoReconnect("SSL handshake failed: ac-0qdd9aa-shard-00-01.t7ljuzh.mongodb.net:27017: [('SSL routines', '', 'tlsv1 ale
rt internal error')]")>, <ServerDescription ('ac-0qdd9aa-shard-00-02.t7ljuzh.mongodb.net', 27017) server_type: Unknown, rtt: None, error=AutoReconnect("SSL handshake failed: ac-0qdd9aa-shard-00-02.t7ljuzh.mon
godb.net:27017: [('SSL routines', '', 'tlsv1 alert internal error')]")>]>

[edit by admin: formatting]

Are you able to ssh into a pythonanywhere console normally? https://help.pythonanywhere.com/pages/SSHAccess/

Yes, I can ssh pythonanywhere from my local Macbook Pro.

Is there anything else I should try?

What was the IP address that you whitelisted on Atlas?

See below. Thanks.

2024-04-23 22:12:50,328 - db_access - INFO - MongoDB Atlas accessList request successful. Address 10.0.5.116 registered

2024-04-24 01:53:47,696 - db_access - INFO - MongoDB Atlas accessList request successful. Address 10.0.5.76 registered

2024-04-24 13:31:41,274 - db_access - INFO - MongoDB Atlas accessList request successful. Address 10.0.4.31 registered

2024-04-24 15:37:23,128 - db_access - INFO - MongoDB Atlas accessList request successful. Address 10.0.4.165 registered