I am having lot of problem in importing modules.
The content in my files is above:
run.py:
from erp import app
if __name__ == '__main__':
app.run(debug=True)
all_blueprints.py:
from flask import Flask
from flask_restful import Api
from flask_sqlalchemy import SQLAlchemy
from flask_marshmallow import Marshmallow
from blueprint_finance.all_resources import api_finance
app = Flask(__name__)
app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:////tmp/test.db"
db = SQLAlchemy(app)
ma = Marshmallow(app)
app.register_blueprint(api_finance)
erp/init.py
from .all_blueprints import app, db, ma
database1.py
from erp import app
class Author(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(255))
I keep getting import errors, the current one is
Traceback (most recent call last):
File "/home/arsalan/python_practise/MY_WORK_FILES/React_works/React_Container_Mount/backend/run.py", line 25, in
from erp import app
File "/home/arsalan/python_practise/MY_WORK_FILES/React_works/React_Container_Mount/backend/erp/init.py", line 1, in
from .all_blueprints import app, db, ma
File "/home/arsalan/python_practise/MY_WORK_FILES/React_works/React_Container_Mount/backend/erp/all_blueprints.py", line 12, in
from blueprint_finance.all_resources import api_finance
ModuleNotFoundError: No module named 'blueprint_finance'
If anyone can point out the mistake's' that will be great favor because I am lost since yesterday. Thanks a lot!
I think the way you create your blueprints is not the right way (See this link for a detailed explanation).
If we refer to the way you have structured your code,
erp/
blueprint_finance ---> is your blueprint package
__init__.py ---> is where you create your blueprint
all_blueprints.py ---> is where you register your blueprint
let's start with the erp/blueprint_finance/__init__.py file:
from flask import Blueprint
bp = Blueprint('blueprint_finance', __name__)
from erp.blueprint_finance import all_resources
from erp.blueprint_finance.finances_resources import resource1
erp/all_blueprints.py
from flask import Flask
from flask_restful import Api
from flask_sqlalchemy import SQLAlchemy
from flask_marshmallow import Marshmallow
app = Flask(__name__)
app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:////tmp/test.db"
db = SQLAlchemy(app)
ma = Marshmallow(app)
from erp.blueprint_finance import bp as blueprint_finance_bp
app.register_blueprint(blueprint_finance_bp)
Related
#market package
from flask import Flask, render_template
from flask_sqlalchemy import SQLAlchemy
from market import routes
app = Flask(__name__)
app.config\['SQLALCHEMY_DATABASE_URI'\] = 'sqlite:///market.db'
db = SQLAlchemy(app)
----------
from market import db #(models)
----------
from market import app #(routes)
from flask import render_template
from market.models import Item
----------#run
from market import app
if __name__ == '__main__':
app.run(debug=True)
Structuring the code into packages then importing modules but then getting the above error
How to add MySQL config to Flask app and create cursor and use in other classes?
I have 2 files:
app.py:
from flask import Flask
from flask_restful import Api
from Query import Query
from flask_mysqldb impoty MySQL
app= Flask(__name__)
api = Api(app)
api.add_resouce(Query,'/')
app.config['MYSQL_HOST'] = 'host'
#(same for user, password, db)
mysql = MySQL(app)
Query.py:
I am trying to import mysql FROM app.py so I can execute SQL on my DB.
from flask_restfull import Resource
from app import mysql
class Query(Resource):
def get(self):
pass
Error is caused by circular import. How to fix it?
"cannot import name 'Query'
Initialize mysql in another file, and reference it from both query.py and app.py. Inject it into the app using MySQL.init_app method
https://flask-mysqldb.readthedocs.io/en/latest/#flask_mysqldb.MySQL
# database.py
from flask_mysqldb import MySQL
mysql = MySQL()
# query.py
from database import mysql # <--!!!
from flask_restfull import Resource
class Query(Resource):
def get(self):
pass
# app.py
from flask import Flask
from flask_restful import Api
from database import mysql # <--!!!
from query import Query
app = Flask(__name__)
api = Api(app)
api.add_resouce(Query,'/')
app.config['MYSQL_HOST'] = 'host'
mysql.init_app(app) # <--!!!
I'm trying to build a CRUD API with product and user and JWT authentication. When I try to run it shows the error -> "ImportError:cannot import name 'Item'" Could you help me. Thank you
from flask import Flask
from flask_jwt import JWT
from flask_restful import Api
from flask_sqlalchemy import SQLAlchemy
from resources.item import Item, ItemList
from resources.user import UserRegister
from security import authenticate, identity
app = Flask(__name__)
api = Api(app)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///data.db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.config['PROPAGATE_EXCEPTIONS'] = True
app.config['SECRET_KEY'] = 'luciano'
db = SQLAlchemy(app)
#app.before_first_request
def create_tables():
db.create_all()
jwt = JWT(app, authenticate, identity)
api.add_resource(Item, "/item/<string:nome>")
api.add_resource(ItemList, "/items")
api.add_resource(UserRegister, "/register")
if __name__ == '__main__':
from db import db
db.init_app(app)
app.run(debug=True)
In the terminal I get the following error
Traceback (most recent call last):
File "/home/luciano/Documentos/Api/app.py", line 5, in <module>
from resources.item import Item, ItemList
ImportError: cannot import name 'Item'
My folder structure
Api
/models
item.py
user.py
/resources
item.py
user.py
app.py
security.py
Add init.py which is missing in your directories
Why it is required
In addition to labeling a directory as a Python package and defining __all__, __init__.py allows you to define any variable at the package level. Doing so is often convenient if a package defines something that will be imported frequently, in an API-like fashion. This pattern promotes adherence to the Pythonic "flat is better than nested" philosophy.
What is __init__.py for?
https://docs.python.org/3/tutorial/modules.html
Add an empty __init__.py file to your resources and models directory.
https://docs.python.org/3/tutorial/modules.html#packages
I'm trying to use Data Tables with Flask and SQLAchemy and I'm facing the
ImportError: cannot import name 'db'
in module Models.py
My project tree:
app
/common
__init__.py
models.py
toutes.py
/mod_tables
---
__init__
config.py
__init__.py
from flask import Flask, redirect, session
from app.mod_tables.models import TableBuilder
from app.config import Config
from flask_sqlalchemy import SQLAlchemy
#from flask_migrate import Migrate
app = Flask(__name__)
table_builder = TableBuilder()
app.config.from_object(Config)
db = SQLAlchemy(app)
db.init_app(app)
#migrate = Migrate(app, db)
from app.common.routes import main
from app.common import models
from app.mod_tables.controllers import tables
# Register the different blueprints
app.register_blueprint(main)
app.register_blueprint(tables)
config.py
import os
basedir = os.path.abspath(os.path.dirname(__file__))
class Config(object):
SQLALCHEMY_DATABASE_URI = os.environ.get('DATABASE_URL') or \
'sqlite:///' + os.path.join(basedir, 'spbData-V3560-FRANCO.db')
SQLALCHEMY_TRACK_MODIFICATIONS = False
\common.models.py
from app import db
class TipoPoste(db.Model):
tp_tipo = db.Column(db.String(35), primary_key=True)
tp_descricao = db.Column(db.String(255))
def __repr__(self):
return '<Tipo Poste {} - {}>'.format(self.tp_tipo,
self.tp_descricao)
Thos code gives me the following error:
flask.cli.NoAppException flask.cli.NoAppException: While importing
"app", an ImportError was raised:
Traceback (most recent call last): File
"c:\users\rfran.v3560-franco\appdata\local\programs\python\python36-32\lib\site-packages\flask\cli.py",
line 235, in locate_app
__import__(module_name) File "C:\Users\rfran.V3560-FRANCO\OneDrive\ArquivosLocais\gepoc\app\__init__.py",
line 2, in <module>
from app.mod_tables.models import TableBuilder File "C:\Users\rfran.V3560-FRANCO\OneDrive\ArquivosLocais\gepoc\app\mod_tables\models.py",
line 3, in <module>
from app.common.models import TipoPoste File "C:\Users\rfran.V3560-FRANCO\OneDrive\ArquivosLocais\gepoc\app\common\models.py",
line 1, in <module>
from app import db ImportError: cannot import name 'db'
Any hint? Thanks in advance.
Your error is caused by a circular import.
db is imported from app/init.py into the app/common/models.py module then the entire models.py module, including the db object, is imported into the app/init.py module. This is a circular import of the db object.
Instead, import the specific objects from the models.py file that you need:
init.py
...
from app.common.routes import main
from app.common.models import TipoPoste
from app.mod_tables.controllers import tables
...
That should fix it.
A good practice is not importing entire modules as you've done here. This could cause conflicts in some names that you may not be obvious at first. It'll save you lots of debugging time.
Try move db object into models.py. I omitted some unnecessary code.
__init__.py
...
from app.common.models import db
...
app = Flask(__name__)
db.init_app(app)
...
models.py
...
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
...
I've a question related to Flask-migrate.
I'm creating a set of web services with Flask. I've split each web service in his own package in a python application.
The application structure look like this:
MyApp
WS1
models.py
WS2
models.py
CommonPackage
models.py
How can I import all the modules and init the db? I've tried to import them all manually but is not working.
I know that it works if I import the "app" from WS1 or Ws2 separately, but I would like to do this in a single operation, is this possible?
Here you can find the code for Flask-migrate:
#!virtualenv/bin/python
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate, MigrateCommand
from flask_script import Manager
from config import SQLALCHEMY_DATABASE_URI
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = SQLALCHEMY_DATABASE_URI
db = SQLAlchemy(app)
migrate = Migrate(app, db)
manager = Manager(app)
manager.add_command('db', MigrateCommand)
from WS1.models import Class1, Class2, Class3 <--- This is not importing
from WS2.models import Class4, Class5, Class6 <--- This is not importing
if __name__=='__main__':
manager.run()
This is the modules where I initialize SQLAlchemy session:
from sqlalchemy import create_engine
from sqlalchemy.orm import scoped_session, sessionmaker
from sqlalchemy.ext.declarative import declarative_base
from config import SQLALCHEMY_DATABASE_URI
engine = create_engine(SQLALCHEMY_DATABASE_URI, convert_unicode = True)
db_session = scoped_session(sessionmaker(autocommit=False,
autoflush=False,
bind=engine))
Base = declarative_base()
Base.query = db_session.query_property()
All the models import this module and inherit from Base.
Thanks a lot,
Enrico
When you are defining a custom declarative base you're not really using Flask-SQLAlchemy anymore—and Flask-Migrate reads the models from Flask-SQLAlchemy's internal declarative base. (That is why you have to initialize Migrate with both app and db).
Flask has an answer to the import cycle problem: Most Flask extensions have an .init_app() method to defer initializing the extension where necessary.
In the module where you currently create Base by hand, just do db = SQLAlchemy() and then in your models import db and use db.Models as your declarative base instead of Base. In your app.py, do the following:
from dbpackagename import db
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = SQLALCHEMY_DATABASE_URI
db.init_app(app)