new programmmmmer new programmmmmer - 1 month ago 12
reST (reStructuredText) Question

Can't use POST method to add new information to database

I managed to figure out how to use curl to POST information to the database from help but there is something wrong with my actual code and I have no idea how to fix it. In my POST method when I try to request json information from my class it doesn't work when I use curl and it says. The error is in the line

dev = Todo(request.json.details)
AttributeError: 'dict' object has no attribute 'details'


I'm trying to add the todo_ID, UserID, details to the Todo table in the database. I can't POST anything yet because of the error, whenever I try to put like todo_ID or CustID as well I get the same error messages for them.

I put the information that I want to be used in a json file. looks like this.

{
"todo_ID": 13,
"UserID": 8,
"details": "Clean up your room."
}


This is my code.

from flask import Flask, jsonify,json, request, abort
from flask_sqlalchemy import SQLAlchemy
import requests

app = Flask(__name__)
app.config.from_pyfile('Config.py')
db = SQLAlchemy(app)

class JsonModel(object):
def as_dict(self):
return {c.name: getattr(self, c.name) for c in self.__table__.columns}

class User(db.Model, JsonModel):
User_ID = db.Column(db.Integer, primary_key = True)
FirstName = db.Column(db.String(20))
LastName = db.Column(db.String(20))


def __init__(self,FirstName, LastName):
self.FirstName = FirstName
self.LastName = LastName


class Todo(db.Model, JsonModel):
todo_ID = db.Column(db.Integer, primary_key = True)
UserID = db.Column(db.Integer, db.ForeignKey('User_ID'))
details = db.Column(db.String(30))

def __init__(self,details):
self.details = details

app.route('/', methods = ['GET'])
def index():
return json.dumps([u.as_dict() for u in User.query.all()+Todo.query.all()])


@app.route('/', methods = ['POST'])
def create_dev():
dev = Todo(request.json.details)
db.session.add(dev)
db.session.commit()
return json.dumps([{'dev': dev}]), 201


@app.before_first_request
def startup():
db.create_all()

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

Answer

Python is not JavaScript. Instead of

dev = Todo(request.json.details)

try this:

dev = Todo(request.json["details"])