Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access MongoDB instance in Flask

I have a very simple Flask RESTful app and want to split up my logic so that it's maintainable. I can't work out how to access my mongoDB connection from another file without having circular import issues. I'm sure there must be a way to have a database file which can create and/or return the instance but I haven't been able to crack it yet.

FYI. I've removed bits from my actual code so this sample may not actually run but hopefully provides an example of my basic setup.

Structure

app.py
api
    __init__.py
    foo.py

app.py

from flask import Flask, request, abort, json, Response
from flask_restful import Resource, Api
from flask_pymongo import PyMongo

from api.foo import Foo


app = Flask(__name__)
api = Api(app)

app.config['MONGO_DBNAME'] = 'mydb'
app.config['MONGO_URI'] = 'mongodb://localhost:27017/mydb'

mongo = PyMongo(app)

# Routes
api.add_resource(Foo, '/foo', '/foo/<id>')

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

api/foo.py

import json

from flask import request, Response, g
from flask_restful import Resource

from app import mongo # Circular import fails

class Foo(Resource):
    def get(self, id):
        doc = mongo.db.users.find({...})
        return {'get': 'Sample data'}

like image 839
Jonathan Lockley Avatar asked Jan 29 '26 22:01

Jonathan Lockley


1 Answers

app.py

from flask import Flask
from flask_restful import Api
from flask_pymongo import PyMongo


app = Flask(__name__)
api = Api(app)

app.config['MONGO_DBNAME'] = 'mydb'
app.config['MONGO_URI'] = 'mongodb://localhost:27017/mydb'

mongo = PyMongo(app)

# Routes
from foo import Foo  # noqa
api.add_resource(Foo, '/foo', '/foo/<id>')

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

foo.py

from flask_restful import Resource


class Foo(Resource):
    def get(self, id):
        print(mongo)
        return {'get': 'Sample data'}


from app import mongo  # noqa

In my minimal code example I imported the dependencies at the end of the file. That way you can avoid the circular dependency. I hope that works for you.

like image 113
Developer Avatar answered Feb 01 '26 10:02

Developer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!