我编写了一个装饰器,试图检查我们是否有 Flask POST 路由的发布数据:
这是我的装饰器:
def require_post_data(required_fields=None):
def decorator(f):
@wraps(f)
def decorated_function(*args, **kwargs):
for required_field in required_fields:
if not request.form.get(required_field, None):
return jsonify({"error": "Missing %s from post data." %
required_field}), 400
else:
if not request.form:
return jsonify({"error": "No post data, aborting."}), 400
return f(*args, **kwargs)
return decorated_function
return decorator
我有两条路线,有一个 URL 参数,另一个没有:
from flask import Blueprint, jsonify, request
mod = Blueprint('contacts', __name__, url_prefix='/contacts')
@mod.route('/', methods=['POST'])
@require_post_data(['customer_id', 'some_other_required_field'])
def create_contact():
# Do some business
@mod.route('/<int:contact_id>', methods=['POST'])
@require_post_data
def update_contact(contact_id):
# Do some business
当我运行命中的测试时update_contact
,我收到以下异常:
TypeError: decorator() got an unexpected keyword argument 'contact_id'
但它看起来像create_contact
预期的那样工作。
为什么contact_id
被传入decorator()
?