0

我正在为我编写的 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

为什么会发生这种情况,我该如何解决

4

1 回答 1

1

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

这条线不应该在你的代码中间浮动。它应该在最后:

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

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

flask run如果用asif子句执行为 False,则不会出现此问题。


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

对于这个你可能想要的:

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

这声明了该路由的 URL。

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

我不知道你为什么405之前得到。也许您的代码中某处有另一条路线接受请求,但不是方法。

于 2020-09-04T20:25:51.767 回答