How to fix circular import in Flask project using blueprints MySQL w/o SQLAlchemy?
flask, mysql, python
Solution
A fairly typical pattern here is to use a third module where you initialize mysql and any other resources you want to share among your blueprints.
I've noticed that people tend to call it extensions.py. So you might do something like this in extension.py:
from flaskext.mysql import MySQL
mysql = MySQL()
And in your main.py, something like this:
from extensions import mysql
app.config['MYSQL_DATABASE_USER'] = 'root'
app.config['MYSQL_DATABASE_PASSWORD'] = 'root'
app.config['MYSQL_DATABASE_DB'] = 'EmpData'
app.config['MYSQL_DATABASE_HOST'] = 'localhost'
mysql.init_app(app)
You'd access the initialized mysql instance from all your blueprints like so:
from extensions import mysql
mysql....
There are other solutions, but this is what I see done most often. It's what I usually do as well.
Problem
So I have main `.py` file where Flask app object is created and configured, and MySQL is initialized. Then I want to register some blueprint. ``` from flask import Flask from flaskext.mysql import MySQL app = Flask(__name__) mysql = MySQL() app.config['MYSQL_DATABASE_USER'] = 'root' app.config['MYSQL_DATABASE_PASSWORD'] = 'root' app.config['MYSQL_DATABASE_DB'] = 'EmpData' app.config['MYSQL_DATABASE_HOST'] = 'localhost' mysql.init_app(app) from views1 import views1_blprnt app.register_blueprint(views1_blprnt) ``` But in `views1.py` I need MySQL object to get connection and cursor objects to execute queries. And, of course, when I try to import it I get the `ImportError`. I've read some similar questions and workarounds, but all of them were using SQLAlchemy. Does someone have any ideas how to resolve it? Thank you for your help and sorry for my english.