向烧瓶 restful 应用发出请求时出现问题

Problems while making requests to a flask restful app

我有以下烧瓶 api,它只是 returns 其输入的回显:

from flask import Flask
from flask_restful import Resource, Api

app = Flask(__name__)
api = Api(app)

class query(Resource):

    def get(self, a_string):
        return{
        'original': a_string,
        'echo': a_string
        }

api.add_resource(query,'/echo/<a_string>')

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

然后,当我尝试使用 python 请求对我的 api 进行查询时:

import json
def query(text):    
    payload = {'echo': str(text)}
    headers = {'content-type': 'application/x-www-form-urlencoded'}
    r = requests.request("POST", 'http://127.0.0.1:5000', data=payload, headers=headers)
    print(r)
    #data = json.loads(r.text)
    #return data

query('hi')

我不断得到:

<Response [404]>

知道如何解决这个问题吗?有趣的是,当我打开浏览器并执行以下操作时:

http://127.0.0.1:5000/echo/hi

我得到:

{"original": "hi", "echo": "hi"}

但是发送一个 POST 到 / 负载为 {"echo": whatever} 与发送一个 GET 到 /echo/whatever 完全不同。您的 API 期望后者。

def query(text):
    r = requests.get("http://127.0.0.1:5000/echo/{}".format(text))

或者,更改您的 API,使其确实期望:

class query(Resource):

    def post(self):
        a_string = request.form["echo"]
        return {
            'original': a_string,
            'echo': a_string
        }

api.add_resource(query, '/')