0

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
  • Partial import will be the likely cause. docs.python.org/2.5/whatsnew/pep-328.html. Please accept and upvote my solution if it helps – Shankar Oct 18 '18 at 18:57

2 Answers2

1

Add an empty __init__.py file to your resources and models directory.

https://docs.python.org/3/tutorial/modules.html#packages

vimalloc
  • 3,869
  • 4
  • 32
  • 45
1

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

Shankar
  • 846
  • 8
  • 24
  • I forgot to say, the file `__init__.py` exists in resources and models and the error still continues – Luciano Amaro Oct 18 '18 at 12:29
  • @LucianoAmaro Partial import will be the likely cause. https://docs.python.org/2.5/whatsnew/pep-328.html. Please accept and upvote my solution if it helps – Shankar Oct 18 '18 at 18:57