1

Im kinda new in api creations and trying to make one in Flask from zero. I have a issue making the model. Here is the code.

main.py :

from flask import Flask
from flask_restful import Api, Resource, reqparse #Reqparse sobra (?)
from controllers.attribute_controller import Attribute
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)
api = Api(app)

app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///database.db'

db = SQLAlchemy(app)



Attribute()
api.add_resource(Attribute, "/attribute/<int:attribute_id>")




if __name__ == "__main__":
    app.run(debug=True)

attribute_controller.py

from flask_restful import Api, Resource, reqparse
from models.attribute_model import AttibuteModel
attribute_put_args = reqparse.RequestParser()
attribute_put_args.add_argument("name", type=str, help="Name is required", required=True )

attributes = {}

class Attribute(Resource):

    def get(self, attribute_id):
        return attributes[attribute_id]
    
    def put(self, attribute_id):
        args = attribute_put_args.parse_args()
        attributes[attribute_id] = args
        return attributes[attribute_id],201

attribute_model.py

from main import db

class AttibuteModel(db.Model):

    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(100), nullable=False)

    def __repr__(self):

        return f"Attribute(name={name})"

test.py

import requests

BASE = "http://127.0.0.1:5000/"

response = requests.put(BASE + "attribute/1", {"name": "red"})
print(response.json())

I got this error:

enter image description here

I know why i got the error, but i dont know any other solution to acced the model in my controllers. I need the attribute_model in my attribute_controller to change it but i dont know how to solve the error. I've tried to follow this instructions: How to avoid circular imports in a Flask app with Flask SQLAlchemy models? But I didn't understand it at all so I don't know how to continue :(. Thx for your time.

ChalsBP
  • 68
  • 2
  • 8

1 Answers1

1

Your problem is a circular import.

In attribute_controller.py you're importing AttibuteModel (missing an 'r' there by the way).

In attribute_model.py you're importing db from main.

In main.py you're importing Attribute from attribute_controller.py (which imports AttibuteModel which imports db) on line 3, before db has been created on line 11.

Move the import statement to after db initialisation:

db = SQLAlchemy(app)

from controllers.attribute_controller import Attribute
half of a glazier
  • 1,864
  • 2
  • 15
  • 45
  • Still doesn't work... Same error: File "E:\Usuario\Escritorio\newApi - Migglo\main.py", line 13, in from controllers.attribute_controller import Attribute ImportError: cannot import name 'Attribute' from partially initialized module 'controllers.attribute_controller' (most likely due to a circular import) (E:\Usuario\Escritorio\newApi - Migglo\controllers\attribute_controller.py) – ChalsBP Mar 25 '21 at 13:36
  • Thought that would work but apparently not... I can't tell exactly how to solve it since I don't have your code to mess around in, but there are lots of SO questions on circular import errors, check out [this question](https://stackoverflow.com/questions/22187279/python-circular-importing) or [this one](https://stackoverflow.com/questions/7336802/how-to-avoid-circular-imports-in-python) – half of a glazier Mar 25 '21 at 13:42