Luciano Amaro
Luciano Amaro

Reputation: 51

Import Erro Flask Framework

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

Upvotes: 0

Views: 51

Answers (2)

Shankar
Shankar

Reputation: 866

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

Upvotes: 1

vimalloc
vimalloc

Reputation: 4177

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

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

Upvotes: 1

Related Questions