请求烧瓶API

时间:2016-03-07 15:51:47

标签: python rest flask

为什么我无法查看变量名称?

当我进入时:

curl --data "name=value1" http://127.0.0.1:5000/echo 

输出结果为:

ECHO : POST

我也期待着:

value1

这是代码:

from flask import Flask, request
app = Flask(__name__)

@app.route('/echo', methods = ['POST'] )
def api_echo():
    if request.method == 'POST':
        print "ECHO : POST\n"
        print request.args['name']
if __name__ == '__main__':
    app.run()

3 个答案:

答案 0 :(得分:1)

from flask import Flask, request
app = Flask(__name__)

@app.route('/echo', methods = ['POST'] )
def api_echo():
    if request.method == 'POST':
        #changing "args" to "form" did the trick
        print request.form['name']
if __name__ == '__main__':
    app.run()

答案 1 :(得分:0)

您要查找的数据位于request.form而不是request.args

def api_echo():
    if request.method == 'POST':
        print "ECHO : POST\n"
        print request.form['name']

打印:

ECHO : POST

val1

您不会从api_echo终点返回任何内容。尽管在python日志中出现了print语句,但Curl仍然抛出错误。您应该为函数添加return值。

答案 2 :(得分:0)

要从request.args获取数据,请发出以下请求:

curl -X POST http://127.0.0.1:5000/echo?name=value1