【问题标题】:Problems while making requests to a flask restful app向烧瓶宁静的应用程序发出请求时出现问题
【发布时间】:2019-05-25 23:33:28
【问题描述】:

我有以下烧瓶 api,它只返回其输入的回声:

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"}

【问题讨论】:

    标签: python python-3.x flask-restful


    【解决方案1】:

    但是向 / 发送有效载荷为 {"echo":whatever} 的 POST 与向 /echo/whatever 发送 GET 完全不同。您的 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, '/')
    

    【讨论】:

    • 你能改进你的答案吗?有一些语法错误感谢您的帮助
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-04-16
    • 2023-03-08
    • 2019-09-07
    • 2019-08-08
    • 2022-08-18
    • 2014-07-23
    • 2014-04-15
    相关资源
    最近更新 更多