Flask python - POST没有按预期工作

时间:2016-05-20 08:38:19

标签: python rest flask

我正在学习RESTFUL API,而我遇到的问题是只发出GET请求但POST请求失败。代码在这里:

from flask import Flask, request
app = Flask(__name__)
#Make an app.route() decorator here
@app.route("/puppies", methods = ['GET', 'POST'])
def puppiesFunction():
    if request.method == 'GET':
    #Call the method to Get all of the puppies
        return getAllPuppies()

    elif request.method == 'POST':
    #Call the method to make a new puppy
        return makeANewPuppy()

def getAllPuppies():
    return "Getting All the puppies!"

def makeANewPuppy():
    return "Creating A New Puppy!"

if __name__ == '__main__':
app.debug = True
app.run(host='0.0.0.0', port=5000)

GET请求正常但POST请求中出现错误。错误是:

 127.0.0.1 - - [20/May/2016 01:39:34] "POST /puppies/ HTTP/1.1" 404 -

提前致谢

2 个答案:

答案 0 :(得分:5)

您的POST请求在URL末尾有一个额外的斜杠。以下是curl命令:

127.0.0.1 - - [20/May/2016 11:17:12] "POST /puppies HTTP/1.1" 200 -
127.0.0.1 - - [20/May/2016 11:17:20] "POST /puppies/ HTTP/1.1" 404 -

以下是Flask日志:

/puppies/

确实在您的问题中,您使用了enter code here \\ Formvalidation code } }).on('success.form.fv', function (e) { //e.preventDefault(); //fv = $(e.target).data('formValidation'); // FormValidation instance\ //fv.disableSubmitButtons(false); //InternaryTicketInvoiceSave(); var $form = $(e.target), $button = $form.data('formValidation').getSubmitButton(), $statusField = $form.find('[name="status"]'); switch ($button.attr('id')) { case 'btnTicketSave': InternaryTicketInvoiceSave(); break; case 'UpdateStatus': InternaryTicketInvoiceSave(); chnageSatatus(); break; } }); } //view code <form id="Iform" name="Iform" method="post"> \\view code here </form>

答案 1 :(得分:1)

您的代码运行正常,不确定问题所在。我复制粘贴你的代码如下:

from flask import Flask, render_template, request

app = Flask(__name__)

@app.route("/puppies", methods = ['GET', 'POST'])
def puppiesFunction():
    if request.method == 'GET':
    #Call the method to Get all of the puppies
        return getAllPuppies()

    elif request.method == 'POST':
    #Call the method to make a new puppy
        return makeANewPuppy()

def getAllPuppies():
    return "Getting All the puppies!"

def makeANewPuppy():
    return "Creating A New Puppy!"

if __name__ == '__main__':

    app.run(debug=True)

enter image description here

并且帖子请求按预期工作。这是我用fiddler做的事情: enter image description here