Skip to main content
 首页 » 编程设计

python之Flask python之POST 未按预期工作

2025年05月04日15lyj

我正在学习 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 请求在 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/。