I am having a dilemma where two modules import each other.
In this Flask-restplus application, app.py is the entry point which Flask app and SQLAlchemy db instance are initialized.
import settings
from apis.rest import api
from apis.audio_namespace import ns as audio_namespace
log = logging.getLogger(__name__)
app = Flask(__name__)
app.config["SQLALCHEMY_DATABASE_URI"] = settings.DATABASE
db = SQLAlchemy(app)
def configure_app(flask_app):
flask_app.config['SERVER_NAME'] = settings.FLASK_SERVER_NAME
def initialize_app(flask_app):
configure_app(flask_app)
blueprint = Blueprint('api', __name__, url_prefix='/api')
api.init_app(blueprint)
api.add_namespace(audio_namespace)
flask_app.register_blueprint(blueprint)
def main():
initialize_app(app)
app.run(debug=settings.FLASK_DEBUG)
if __name__ == "__main__":
main()
The namespace audio_namespace
from folder apis
is added to api
. api
is defined in rest
from folder apis
too.
#rest.py
api = Api(version='1.0', title='SoundAPI',
description='API for audio processing with TensorFlow')
audio_namespace.py
handles all the requests and hence db operations.
ns = api.namespace('audio', description='Audio processing with TensorFlow')
class AudioDAO(object):
@property
def audios(self):
return AudioModel.query.all()
def get(self, id):
audio = AudioModel.query.filter_by(id=id).first()
if audio:
return {"id": audio.id, "filename": audio.file_name}
api.abort(404, "Audio {} doesn't exist".format(id))
def create(self, file_name):
audio = AudioModel(file_name)
audio.insert_ts = datetime.now()
db.session.add(audio)
db.session.commit()
return audio
@ns.route('/upload')
class AudioUpload(Resource):
def put(self):
...........
def post(self):
...........
But since db
is defined in app.py
, I would have to import db
from app
. Therefore I got error saying ns
from audio_namespace
can't be imported in app.py
because the two modules cannot import each other.
Where should I define db
then?