tony tony - 12 days ago 4
Python Question

Creating new task in database using id with POST

I'm trying to create a new task in my database according to the todo_ID which I will put in the url. I can post a new task in the database entirely but I want the server to choose the todo_ID so if a person types /1 in the url it would create a new task with todo_ID = 1 and fill in the UserID and details depending on what the user puts in. Problem is I have no idea how to do it based on the todo_ID so can someone tell me how :D

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

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


class User(db.Model, JsonModel): #Class which is a model for the User table in the database
User_ID = db.Column(db.Integer, primary_key = True)
FirstName = db.Column(db.String(20))
LastName = db.Column(db.String(20))

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

class Todo(db.Model, JsonModel): #Class which is a model for the Todo table in the database
todo_ID = db.Column(db.Integer, primary_key = True)
UserID = db.Column(db.Integer, db.ForeignKey("user.User_ID"))
details = db.Column(db.String(30))

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


@app.route('/<int:todo_ID>', methods = ['POST']) #Uses POST method with same URL as GET method to add new information to Todo table.
def create_dev(todo_ID):
id = Todo.query.create(todo_ID)
dev = request.json["UserID"],request.json["details"]
db.session.add(id,dev)
db.session.commit()
return "New task has been created.", 201


@app.before_first_request #Creates everything before the first request.
def startup():
db.create_all()

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

Answer

Try

dev.UserID = request.POST["UserID"]

For request.json to work, set content type to application/json. From Flask documentation

If the mimetype is application/json this will contain the parsed JSON data. Otherwise this will be None.

For more details: http://stackoverflow.com/a/20001283/3930114

Edit 1: Solution based on discussion in comments

@app.route('/<int:todo_ID>', methods = ['POST'])  #Uses POST method    with same URL as GET method to add new information to Todo table.
# Setting todo_ID default to None
def create_dev(todo_ID=None):
    # This if will allow you to not pass id via url and handle in backend. Frankly, first integer field will automatically become autoincrement field in Flask, so I am not even sure why you want to send todo_ID via url but I dont have enough information about your app :)
    if todo_ID is None:
        # write logic to create a todo_ID
        pass
    # Instance of model task
    dev.UserID = request.json["UserID"]
    dev.details = request.json["details"]
    t = Task(todo_ID, dev.UserID, dev.details)
    db.session.add(t)
    db.session.commit()
    return "New task has been created with todo_ID: " + todo_ID, 201

Edit 2: Solution based on additional information in comments

@app.route('/', methods = ['POST'])  #Uses POST method    with same URL as GET method to add new information to Todo table.
# Setting todo_ID default to None
def create_dev():
    # Instance of model task
    t = Todo(UserID=request.json["UserID"], details=request.json["details"])
    db.session.add(t)
    db.session.commit()
    return "New task has been created with todo_ID: " + todo_ID, 201

PS: I have not tested this code.

References:

Comments