使用 Python 函数签名检查函数参数缺失

Python 的 inspect.Signature 对象有个 bind 方法,它可以把任意个参数绑定到签名中的形参上, 可以使用这个方法在真正调用函数前验证参数是否传递

from flask import Flask, jsonify, request
import inspect

app = Flask(__name__)

# **kwargs 忽略多余的参数
def auth_param_func(username, password, **kwargs): pass

def valid_auth_empty(func, form):
    sig = inspect.signature(func)
    try:
        sig.bind(**form)
    except TypeError as e:
        return 'form data is not full'
    else:
        return None

@app.route('/login', methods=['GET', 'POST'])
def login():
    form = request.get_json() or {}
    err = valid_auth_empty(auth_param_func, form)
    if err is not None:
        res = jsonify({'detail': err})
        res.status_code = 400
    else:
        res = jsonify({'success': 'ok'})
    return res

if __name__ == '__main__':
    app.run(host='0.0.0.0',
            port=5000,
            debug=True)
  1. 参数缺失时,400错误
curl -H "Content-Type: application/json" -d '{"username":"u14e"}' http://192.168.1.195:5000/login

{
  "detail": "form data is not full"
}
  1. 检查通过
curl -H "Content-Type: application/json" -d '{"username":"u14e","password":"123456"}' http://192.168.1.195:5000/login

{
  "success": "ok"
}
  1. 自动忽略多余的参数("code": 675489)
curl -H "Content-Type: application/json" -d '{"username":"u14e","password":"123456","code":675489}' http://192.168.1.195:5000/login

{
  "success": "ok"
}

你可能感兴趣的:(使用 Python 函数签名检查函数参数缺失)