3

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'}

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for your answer, moving the mongo database import to the bottom of the file has fixed my circular import issue. How does that work though, I assumed it would need to be imported before it's called. Is it possibly because the code inside my RESTful methods are not read until they're invoked later on.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.