烧瓶使用POST,PUT,DELETE

时间:2016-11-02 06:59:17

标签: python post sql-delete put flash-message

当我尝试在API中实现POST时,我在网址上一直出现错误。我一直在URL中收到错误,指出此URL不允许使用METHOD。我错过了什么吗?当你试图打开服务器时,POST不能直接工作吗?我太丢了。

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)
db.create_all()

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('/todo/<int:UserID>', methods = ['GET'])
def get(UserID):
    return (list[Todo.query.get(UserID)])

@app.route('/p/', methods = ['POST'])
def create_dev():
    if not request.json or not 'name' in request.json:
    abort(400)
    dev = Todo(request.json.details,request.json.get('details',''))
    db.session.add(dev)
    db.session.commit()
    return json.dumps([{'dev': dev}]), 201

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

1 个答案:

答案 0 :(得分:1)

您应该将GET方法添加到允许的方法列表中。当您尝试加载页面时,首先需要使用GET方法获取页面本身。然后,在页面上填充内容后,使用POST方法将一些数据传递给应用程序。在应用程序中,您应该检查调用哪个方法函数。像这样:

@app.route('/p', methods=['GET', 'POST'])
def create_dev():
    if request.method == 'GET':
        return render_template('p_page.html')

    # If You get to this line, it means it is POST method
    do_something_here()