【问题标题】:Flask python - POST not working as expectedFlask python - POST没有按预期工作
【发布时间】:2016-05-20 08:38:18
【问题描述】:

我正在学习 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 -

提前致谢

【问题讨论】:

  • 您遇到了什么错误?
  • 如何进行 POST 请求? 404 未找到错误。尝试 /puppies 而不是 /puppies/ 并尝试拆分方法,也许它会起作用。
  • 对我来说代码工作正常。试试 curl -X POST 0.0.0.0:5000/puppies

标签: python rest flask


【解决方案1】:

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

$ curl -X POST 0.0.0.0:5000/puppies
Creating A New Puppy
$ curl -X POST 0.0.0.0:5000/puppies/
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<title>404 Not Found</title>
<h1>Not Found</h1>
<p>The requested URL was not found on the server.  If you entered the URL manually please check your spelling and try again.</p>

这里是 Flask 日志:

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 -

确实在你的问题中你使用了/puppies/

【讨论】:

    【解决方案2】:

    您的代码运行良好,但不确定是什么问题。我复制粘贴您的代码如下:

    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)
    

    并且发布请求按预期工作。这是我使用提琴手所做的:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-06-20
      • 1970-01-01
      • 2012-05-09
      • 2014-02-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多