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
Related
Hello everyone I have this issue I am not able to correct:
KeyError: 'A secret key is required to use CSRF.'
I am now using Flask with Blueprint.
I am not using CSRF at all but I think the LoginForm is.
I structured my project with Blueprint.
Before that, everything was find.
Here is my init.py file:
from flask import Flask
from flask_login import LoginManager
from flask_bcrypt import Bcrypt
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
from flask_admin import Admin
from flask_admin.contrib.sqla import ModelView
from flask.config import Config
from flask_wtf.csrf import CSRFProtect
db = SQLAlchemy()
migrate = Migrate(db)
bcrypt = Bcrypt()
csrf = CSRFProtect()
login_manager = LoginManager()
login_manager.login_view = "login"
login_manager.login_message_category = "info"
from Flask import models
from Flask.models import User
admin = Admin(name='Admin')
def create_app(config_class=Config):
app = Flask(__name__)
app.config.from_object(Config)
admin.init_app(app)
db.init_app(app)
csrf.init_app(app)
login_manager.init_app(app)
migrate.init_app(app)
bcrypt.init_app(app)
db.init_app(app)
from Flask.users.routes import users
app.register_blueprint(users)
return app
This is my config.py file:
import os
class Config:
SECRET_KEY = "ef2006629e09b70e55a6fb95c4e3a538"
SQLALCHEMY_DATABASE_URI = "sqlite:///site.db"
# WTF_CSRF_SECRET_KEY= "bjk567nvhbvj63vg363vghvghv3768vgfbkijvr784"
# CSRF_ENABLED = True
Thank you for your help !
You should create a SECRET_KEY=<Your secret key here> property in your configuration. It must be a difficult string.
I found the problem
I was not calling properly my config.py file
In my init.py file I change the line:
from flask.config import Config
with the line:
from Flask.config import Config
Flask is the name of my file, which is different from flask.
I should have found another name
I have the following structure:
app_dir/
| myapi/
| __init__.py
| myapi_app.py
where myapi_app.py is
from myapi import create_app, db
app = create_app()
and myapi/__init__.py is
import logging
import os
from logging.handlers import RotatingFileHandler
from flask import Flask, request, current_app
from flask_sqlalchemy import SQLAlchemy
from myapi.config import Config
db = SQLAlchemy()
def create_app(config_class=Config):
app = Flask(__name__)
app.config.from_object(config_class)
db.init_app(app)
...
return app
When I set FLASK_APP=myapi_app.py and run flask run from the app_dir directory, the flask service starts. However, when I make a request, I get the following error: flask.cli.NoAppException: Could not import "myapi_app". Where am I going wrong?
Your problem is that you are setting $FLASK_APP to the file in which the app variable is stored, you should instead set it to the python object path, e.g.
FLASK_APP=myapi_app:app
However, this is not necessary, as you could also just do:
FLASK_APP=myapi
as Flask will look for a create_app function in the package on its own.
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)
Following this tutorial on how to structure a Flask app, I have:
project/
__init__.py
app.py
models/
__init__.py
base.py
base.py
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
models/__init__.py
from .base import db
def init_app(app):
db.init_app(app)
project/__init__.py
from flask import Flask
def create_app()
from . import models, routes, services
app = Flask(__name__)
models.init_app(app)
# routes.init_app(app)
# services.init_app(app)
return app
finally, in app.py, I try to run it:
from . import create_app
app = create_app()
if __name__ == '__main__':
app.run(use_reloader=True, threaded=True, debug=True)
but I'm getting the error:
from . import create_app
ValueError: Attempted relative import in non-package
Am I building it right, what am I doing wrong?
I guess you are running your program by:
python project/app.py
In this case, you are not treat your "project" as a python package, which will raise the error you got. Instead, you can run your project with:
FLASK_APP=project.app flask run
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()
...