Problem
Flask app running pymongo
on PythonAnywhere fails in certain circumstances giving error similar to:
No replica set members match selector Primary(), Timeout: 30s, Topology Description: topology_type: ReplicaSetNoPrimary, servers: [ 27017) server_type: RSSecondary, rtt: 0.026010908652096987>, (xx-xxxxxxx-shard-00-01.xxxxxxx.mongodb.net, 27017) server_type: Unknown, rtt: None, error=AutoReconnect(xx-xxxxxxx-shard-00-01.xxxxxxx.mongodb.net:27017: connection pool paused)>, 27017) server_type: RSSecondary, rtt: 0.026285539381206036>]>
Root Cause
Importing an established/connected pymongo.MongoClient
from a module outside of flask_app.py
Resolution
Create MongoClient instance inside flask_app.py
itself using PythonAnywhere recommended settings e.g.
client = MongoClient(
MONGO_URI,
connectTimeoutMS=30000,
socketTimeoutMS=None,
connect=False,
maxPoolsize=1,
)
Then move any imported functions/classes/methods that use MongoDB inside flask_app.py
(or write them in other modules in such a way that they take 'client' as an injected argument)