带有Python Flask POST请求405的Web API不允许

时间:2020-09-04 18:00:18

标签: python-3.x api web request

我正在为我编写的python程序制作Web API,我正在复制教程

这是API代码

#!flask/bin/python
from flask import Flask
from flask import make_response
from flask import request
import requests
import json

app = Flask(__name__)

@app.route('/')
def index():
    return "Hello, World!"

if __name__ == '__main__':
    app.run(debug=True)
    
@app.errorhandler(404)
def not_found(error):
    return make_response(jsonify({'error': 'Not found'}), 404)
  
@app.route('/5492946838458/index.html', methods=['POST'])
def create_task():
    if not request.json or not 'key' in request.json or not 'name' in request.json or not 'text' in request.json or not 'pack' in request.json:
        abort(400)
    if 'title' in request.json and type(request.json['title']) != unicode:
        abort(400)
    if 'description' in request.json and type(request.json['description']) is not unicode:
        abort(400)
    task = {
      'key': request.json['key'],
      'name': request.json['name'],
      'text': request.json['text'],
      'pack': request.json['pack']
    }
    return (200)

这是我发送给的URL

https://my.websites.url.here/5492946838458/

和我正在发送的json数据

{
"key": "key",
"name": "name",
"text": "text",
"pack": "pack"
}

我得到的标题也得到

date: Fri, 04 Sep 2020 17:48:30 GMT
content-length: 0
vary: Origin
accept-ranges: bytes
allow: GET, HEAD, OPTIONS

为什么会这样,我该如何解决

1 个答案:

答案 0 :(得分:1)

我可以看到两个问题...

此行不应浮在代码中间。它应该在最后:

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

在当前位置,如果您使用python app.py执行应用程序,则该应用程序将在此时运行。在它之前的路由(index可用,但是在它之后声明的路由(create_task则不会(直到您杀死服务器-添加后一个路由时,在python之前)过程停止)。

如果使用flask run作为if子句为False,则不会出现此问题。


@app.route('/5492946838458/index.html', methods=['POST'])

您可能想要这个:

@app.route('/5492946838458/', methods=['POST'])

这将声明该路由的URL。

现在,对https://my.websites.url.here/5492946838458/的请求应返回成功的响应。对/5492946838458的请求将返回308重定向到带有斜杠的那个。

我不确定您为什么之前获得405。也许代码中的某条路径接受了请求,但方法没有接受。