-1

I have a very simple Flask RESTful API that I have built following the Packt book "Python API Development Fundamentals". I can successfully get data from the DB but I'm having trouble posting data.

I am using Flask, SQLAlchemy, and flask_restful, and a Microsoft Server Management Studio local database.

I am currently getting an error when trying to insert an entry into the Users table. A user is only an ID, Name, Age. I am following the books example which you can find here: https://github.com/TrainingByPackt/Python-API-Development-Fundamentals/tree/master/Lesson03/Exercise19

If you do take a look at the example, you can see that the example code they used for the get method also did not work for me, and I came up with my own strategy. But I'm having some trouble figuring out a strategy for the post method.

I am getting this error in the users.py resource when I try this httpie command: http POST localhost:5000/users Name="Kyle" Age="22"

error

[2021-03-29 15:40:58,891] ERROR in app: Exception on /users [POST]
Traceback (most recent call last):
  File "c:\users\e096752\documents\cole's projects\flask projects\testproj\venv\lib\site-packages\flask\app.py", line 1950, in full_dispatch_request
    rv = self.dispatch_request()
  File "c:\users\e096752\documents\cole's projects\flask projects\testproj\venv\lib\site-packages\flask\app.py", line 1936, in dispatch_request
    return self.view_functions[rule.endpoint](**req.view_args)
  File "c:\users\e096752\documents\cole's projects\flask projects\testproj\venv\lib\site-packages\flask_restful\__init__.py", line 468, in wrapper
    resp = resource(*args, **kwargs)
  File "c:\users\e096752\documents\cole's projects\flask projects\testproj\venv\lib\site-packages\flask\views.py", line 89, in view
    return self.dispatch_request(*args, **kwargs)
  File "c:\users\e096752\documents\cole's projects\flask projects\testproj\venv\lib\site-packages\flask_restful\__init__.py", line 583, in dispatch_request   
    resp = meth(*args, **kwargs)
  File "C:\Users\e096752\Documents\Cole's Projects\Flask Projects\testProj\resources\users.py", line 27, in post
    return user.data, HTTPStatus.CREATED
AttributeError: 'User' object has no attribute 'data'

That said, and this is one of the reasons I didn't use the books example, I have no idea what the userList list in the model does or why I would add the newly created user to it. I don't see anywhere where that actually gets pushed to the database. It just gets put in a list.

users resource

from flask import request
from flask_restful import Resource
from http import HTTPStatus
from flask import jsonify
from sqlToJson import convert_sqlaLchamy_to_json
from models.Users import User, userList

class User_List_Resource(Resource):

    def get(self):
        
        users = User.query.all()

        data = jsonify(convert_sqlaLchamy_to_json(users))
        
        return data

    def post(self):

        data = request.get_json()

        user = User(Name=data['Name'],
                        Age=data['Age'])
        
        userList.append(user)

        return user.data, HTTPStatus.CREATED

And by the way, the sqlToJson is a file that I wrote because I couldn't get the example in the book to work.

Users model

from extensions import db

userList = []

def get_last_id():
    if userList:
        lastUser = userList[-1]
    else:
        return 1
    return lastUser.id + 1

class User(db.Model):
    __tablename__ = 'Users'
    ID = db.Column(db.Integer, primary_key=True)
    Name = db.Column(db.String(50))
    Age = db.Column(db.Integer)

app.py

from flask import Flask, render_template
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy import create_engine
from flask_restful import Resource, Api
from flask import jsonify
import json
from sqlToJson import convert_sqlaLchamy_to_json
import datetime
from flask_restful import Api

from config import Config
from extensions import db
from models.Case_Log import Case_Log
from resources.case_log import Case_Log_List_Resource
from models.Users import User
from resources.users import User_List_Resource
from resources.home import Home_Resource

def create_app():
    app = Flask(__name__)
    app.config.from_object(Config)

    register_extensions(app)
    register_resources(app)

    return app


def register_extensions(app):
    db.init_app(app)

def register_resources(app):
    api = Api(app)

    #Add all resources as routes
    api.add_resource(Home_Resource, '/')
    api.add_resource(Case_Log_List_Resource, '/case_logs')
    api.add_resource(User_List_Resource, '/users')

if __name__ == '__main__':
    app = create_app()
    app.run()

Any help would be greatly appreciated.

ColeDOT
  • 107
  • 1
  • 1
  • 9

1 Answers1

0

return user.data, HTTPStatus.CREATED - remove .data since you want to return a user

balderman
  • 22,927
  • 7
  • 34
  • 52
  • Ok well that worked but I got a new error, ````TypeError: Object of type User is not JSON serializable```` . I tried to solve this with jsonify(user) instead of just user but that didn't seem to change anything. Any ideas? – ColeDOT Mar 29 '21 at 20:01
  • See https://stackoverflow.com/questions/5022066/how-to-serialize-sqlalchemy-result-to-json – balderman Mar 29 '21 at 20:07