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:
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.