P
P
Pavel2020-06-27 00:23:36
MongoDB
Pavel, 2020-06-27 00:23:36

Python how to connect to a remote Mongo base using flask-mongoengine?

Good evening

I can’t connect to the Mongo base for an hour using the flask-mongoengine library, I also tried pure mongoengine, without success. Answer one

mongoengine.connection.ConnectionFailure: You have not defined a default connection

Before that, I tried the same thing with the Flask-PyMongo library and everything works ok!

help me figure out what I'm doing wrong

"VIEW"
from flask import render_template
from app import app
from models import UserProduct

@app.route("/")
def index():
    products = UserProduct.objects
    print(products)


"APP"
from flask import Flask
from flask_mongoengine import MongoEngine
from config import Configuration

app = Flask(__name__)
app.config.from_object(Configuration)

db = MongoEngine()


"CONFIG"
class Configuration(object):
    DEBUG = True
    JSON_AS_ASCII = False
    SECRET_KEY = 'secret_key'
    MONGODB_SETTINGS = "mongodb+srv://"name":"pass"@cluster0-vkzx6.mongodb.net/"base"?retryWrites=true&w=majority"


"MODELS"
from mongoengine import *

class UserProduct(Document):
    description = StringField()
    order_num = IntField()
    link = StringField()


In the mongo admin panel on the page https://cloud.mongodb.com/ Network Access, access to ip is completely open 0.0.0.0/0
Two users with atlas admin rights are open to access the database,

what to do, how to connect correctly, I can’t understand!

Thanks in advance for any help!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
P
Pavel, 2020-06-28
@velllum

Thank you for your help!
Working example

from flask import Flask
from flask_mongoengine import MongoEngine

app = Flask(__name__)


app.config['DEBUG'] = True
app.config['SECRET_KEY'] = "key"
app.config['JSON_AS_ASCII '] = False
app.config['MONGODB_HOST'] = "mongodb+srv://<user_name>:<pass>@cluster0-vkzx6.mongodb.net/<db_name>?retryWrites=true&w=majority"

db = MongoEngine(app)


from mongoengine import *

class User(Document):
    description = StringField()
    order_num = IntField()
    link = StringField()


@app.route("/")
def index():
    user = User.objects
    print(user)

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

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question