-1

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()
Muba
  • 40
  • 1
  • 13
  • Are you sure a record with the id in your URL exists? – dirn Nov 20 '16 at 02:29
  • ohh... i thought i was supposed to add an id that I didn't have before ... ugh am i not supposed to have that part of the code there? now that I think about it, It looks like something that i'd need if i am updating – Muba Nov 20 '16 at 02:32

1 Answers1

0

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: https://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:

Community
  • 1
  • 1
Aditya
  • 610
  • 4
  • 11
  • oh i think i messed up my code because i can't look for the new id that I'm trying to make because it hasn't been made yet. Main problem now is that I don't know how to post data according to the todo_ID. Also in my curl statement, I put in application/json and it worked when i tried to enter a new todo_ID but I want the server to pick the todo_ID so it doesn't have to be entered. – Muba Nov 20 '16 at 05:06
  • It looks like you have a couple of separate questions that are not represented in the original question if that is a right understanding, can you please edit the original question? > Main problem now is that I don't know how to post data according to the todo_ID. You seem to be doing the right thing. For the second question, are your trying to edit a task or create a new one? If editing, what criteria can the server use to get the todo_ID? Otherwise, server should pick up auto value or try using `defaults` from `route` – Aditya Nov 20 '16 at 17:01
  • my main question is being able to post data according to the todo_ID. I'm trying to create a new task. I figured out how to edit a existing task already. – Muba Nov 20 '16 at 22:08
  • So I read two questions: 1. you want to post data according to a todo_ID: In this case, you are saying you are not editing a task so are you creating a new task based on a todo_id that you created somewhere? 2. Create a new task: No self-created todo_ID and want the backend to figure out what the todo_ID should be so that you can create the task... Does this make sense? – Aditya Nov 21 '16 at 00:53
  • I want to do the second one that you mentioned, so the if the url has /30 then the todo_ID should be created with todo_ID = 30. – Muba Nov 21 '16 at 01:11
  • problem is i don't know how to create the new id. I also changed my code a bit now. – Muba Nov 21 '16 at 02:39
  • Awesome! The fact is, you dont need to. Based on http://stackoverflow.com/a/20861531/3930114 `Task()` will auto create a todo_ID. Adding edit 2 to my code – Aditya Nov 21 '16 at 02:45
  • umm what exactly is task()? it says unresolved reference for Task – Muba Nov 21 '16 at 02:51
  • Sorry, it should be `Todo`. Create instance of model class `Todo()`. Include the right things to make sure it can be created. This is the reference: http://flask-sqlalchemy-plus.readthedocs.io/en/latest/api/#flask_sqlalchemy_booster.queryable_mixin.QueryableMixin.create – Aditya Nov 21 '16 at 02:54
  • emm r u sure i need to remove the todo_ID from the post method. Because it says i have an unexpected keyword argument"todo_ID" I changed it up a bit and added. db.session.add(t,todo_ID) but it doesn't give me the todo_ID that I want to put. it just gives me the next one like its auto incrememnted – Muba Nov 21 '16 at 03:01
  • Yes, sure that it should work. There some be some other bug, do some debugging :) http://flask.pocoo.org/docs/0.11/quickstart/#http-methods – Aditya Nov 21 '16 at 03:05
  • oh wait by the server choosing the id does it mean that I shouldn't enter anything in the url with todo_ID? – Muba Nov 21 '16 at 03:20
  • Right. It should be empty, as indicated by the `@app.route('/', methods= ['POST'])` url. – Aditya Nov 21 '16 at 03:25