Search code examples
mongodbpython-3.6flask-restfulevemongodb-atlas

How to set Python EVE REST API serving settings for the database on MongoDB Atlas


Problem Summary

I'm trying to setup a python eve REST API server with mongodb at localhost 5000 (http://127.0.0.1:5000/). In the beginning, my mongodb was hosted at localhost 27017, and the API connection worked perfectly. But I want to change the database to a cloud server, so I dumped my db to MongoDB Atlas and tried to revise the MONGO_HOST and add the user credentials in the settings.py file. But it didn't work. Here's the code I've tried to revise.

Before change

settings.py

MONGO_HOST = 'localhost'
MONGO_PORT = 27017
MONGO_DBNAME = 'mydb'
...
SERVER_NAME = '127.0.0.1:5000'
URL_PREFIX = 'api'

After change

settings.py

MONGO_HOST = '<clustername>-mz123.gcp.mongodb.net'
MONGO_USERNAME = 'user'
MONGO_PASSWORD = 'user'
MONGO_DBNAME = 'mydb'
...
SERVER_NAME = '127.0.0.1:5000'
URL_PREFIX = 'api'

I've also tried to follow the instruction from official to access the mongoDB Atlas with pymongo and it worked successfully as below. So I think the problem may exactly be how to set the eve settings.py file for connecting to MongoDB Atlas in the correct way.

from pymongo import MongoClient
client = MongoClient("mongodb+srv://user:password@<clustername>-mz123.gcp.mongodb.net/test?retryWrites=true&w=majority")
db = client['db']
col = db['collection']

My questions and thoughts

  1. Is there any setting parameter I just missed? I'm not sure if the name of MONGO_HOST is wrong, but I just got it from the instruction on Atlas website. Or do I need to change the setting to the form like MONGO_URI instead? But I've tried and failed, too. LOL

  2. Does the eve REST API serve only for localhost DB (27017) when serving at localhost 5000?

  3. Any suggestions? Thanks!


Solution

  • In your settings.py, define your MONGO_URI with the param you've used in your MongoClient example. See MONGO_URI here in the documentation (https://docs.python-eve.org/en/stable/config.html#global-configuration)