Search code examples
pythonflaskflask-restful

Getting the database connection from application context with Flask-Restful


I have an app using Flask-Restful and I don't know how to get the database connection info from the application context.

Here is what I have so far:

app.py:

....
from flask.ext.restful import reqparse, abort, Api, Resource
app = Flask(__name__)
app.config['DATABASE'] = 'my.db'
api = Api(app) 
api.add_resource(Foo, '/')

foo.py

...
from flask.ext.restful import Resource

class Foo(Resource):
    def __init__(self):
        self.db = get_db()
    def post(self):
        do_stuff_with_db()

I'd like the get_db method to look something like:

def get_db():
    return database.connect(app.config['DATABASE'])

The problem is in order to get app.config into foo.py, I create a circular reference. Is there a clean, and hopefully idomatic way to get this?

I have seen this question, but the solution given doesn't actually resolve the circular import problem.


Solution

  • Well, for my project I use this kind of structure:

    application/__init__.py

    ...
    app = Flask(__name__)
    ...
    db  = SQLAlchemy(app) #because I use sqlalchemy
    ...
    import application.core 
    

    application/core.py

    from application.api import resource
    ...
    # api definition
    

    application/api/resource.py

    from application import db
    ...
    db.doWhatEverYouWant()
    ...
    

    It's certainly not perfect but I don't have such kind of circular import problems.