flask api 路由请求获取参数丢失错误

时间:2021-06-01 14:26:35

标签: python flask postman

在我的烧瓶项目中,我有一条路线:

@app.route('/api/d/u', methods=['POST'])
def update(name, domain_list, pem_key, pem_cert, origin_ips):  # name, domain_list, pem_key, pem_cert, origin_ips
    return "update"

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

但在我的邮递员中,我想测试 api,

You see the params

当我发送请求但收到 TypeError 时:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
  "http://www.w3.org/TR/html4/loose.dtd">
<html>
    <head>
        <title>TypeError: update() missing 5 required positional arguments: 'name', 'domain_list', 'pem_key', 'pem_cert', and 'origin_ips' // Werkzeug Debugger</title>
        <link rel="stylesheet" href="?__debugger__=yes&amp;cmd=resource&amp;f=style.css"
        type="text/css">
        <!-- We need to make sure this has a favicon so that the debugger does
         not by accident trigger a request to /favicon.ico which might
         change the application state. -->
     ......
  File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/flask/app.py", line 1598, in dispatch_request
    return self.view_functions[rule.endpoint](**req.view_args)
TypeError: update() missing 5 required positional arguments: 'name', 'domain_list', 'pem_key', 'pem_cert', and 'origin_ips'

-->

2 个答案:

答案 0 :(得分:0)

路由函数的参数只填充了一个 GET 请求。示例:

@app.route('/api/d/u/<name>', methods=['GET'])
def update(name):
    return "update"

#Example Call would be GET http://127.0.0.1:5000/api/d/u/myname

对于您的 POST 示例,您可能需要从 Flask 导入 request,并且由于您正在检索表单数据,因此您可以像这样提取它:

from flask import Flask, request

app = Flask(__name__)

@app.route('/api/d/u', methods=['POST'])
def update():
    formdata = request.form
    # Extract form-data: name = formdata['name']
    return "update"

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

答案 1 :(得分:-1)

因为您使用参数定义了函数,所以flask 期望从路由中获取它们。如果您想使用当前的实现,您应该执行类似

from flask import app, request

@app.route('/api/d/u', methods=['POST'])
def update():  # name, domain_list, pem_key, pem_cert, origin_ips
    # data = request.get_json() # use if you send data as json
    data = request.form # use if you send data as a form
    name = data["name"]
    domain_list = data["domain_list"]
    # ... continue with other fields
    return "update"

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