Muba
Muba

Reputation: 40

getting location header in flask to return an id

I know how to return a location header with a url for say "todo/1" where i have to type the one in my header location so my code will look like this in the POST method. However I don't know how to return it based on the todo_ID so i don't have to enter it manually. So for example it would look like

response.headers['location'] = '/todo/todo_ID'

But this would return the word todo_ID. Is there anyway I can return the actual todo_ID that has been created in the url?

I looked at this question but wasn't sure if the answer would help me.How to return a relative URI Location header with Flask?

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

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

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('/todo', methods = ['POST'])  #Uses POST method with same URL as GET method to add new information to Todo table.
def create_todo():
    if not request.json:
        abort(400)
    response= jsonify()
    todo = Todo(UserID = request.json["UserID"],details = request.json["details"])
    db.session.add(todo)
    db.session.commit()
    response.status_code = 201
    response.headers['location'] = '/todo/1'
    return response

Upvotes: 1

Views: 1440

Answers (1)

Aleksandar Varicak
Aleksandar Varicak

Reputation: 1068

Few steps that you need.

  1. db.session.commit() will remove object, use flush first
  2. response.headers['location'] = '/todo/{}'.format(todo.todo_ID)
  3. and then db.session.commit()

Here is whole code:

@app.route('/todo', methods = ['POST'])  
def create_todo():
    if not request.json:
        abort(400)
    response= jsonify()
    todo = Todo(UserID = request.json["UserID"],details = request.json["details"])
    db.session.add(todo)
    #db.session.commit()
    db.session.flush() # will get id from database
    response.status_code = 201
    response.headers['location'] = '/todo/{}'.format(todo.todo_ID)
    db.session.commit() # write to database
    return response

Upvotes: 1

Related Questions