【问题标题】:getting location header in flask to return an id在烧瓶中获取位置标头以返回 id
【发布时间】:2017-05-09 18:20:57
【问题描述】:

我知道如何返回一个带有 url 的位置标头,比如“todo/1”,我必须在我的标头位置键入一个,这样我的代码在 POST 方法中将如下所示。但是我不知道如何根据 todo_ID 返回它,所以我不必手动输入它。例如,它看起来像

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

但这会返回单词 todo_ID。无论如何我可以返回在 url 中创建的实际 todo_ID 吗?

我看了这个问题,但不确定答案是否对我有帮助。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

【问题讨论】:

  • 你检查过todo 中的内容吗?
  • 不确定您的意思。如果您在 url 中谈论 /todo 它只是 url 的一部分。
  • 我在todo = Todo(..)中要求todo

标签: python python-2.7 python-3.x url flask


【解决方案1】:

您需要的几个步骤。

  1. db.session.commit() 将删除对象,请先使用刷新
  2. response.headers['location'] = '/todo/{}'.format(todo.todo_ID)
  3. 然后是 db.session.commit()

这是完整的代码:

@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

【讨论】:

    猜你喜欢
    • 2015-06-05
    • 1970-01-01
    • 2013-08-13
    • 2019-02-09
    • 2019-03-23
    • 1970-01-01
    • 2020-08-09
    • 2020-08-21
    • 2021-01-02
    相关资源
    最近更新 更多