[英]AssertionError: expected view func if endpoint is not provided - python
trying to decorate end point with requires_fields decorator.试图用requires_fields装饰器装饰端点。 this is the implementation.这是实施。
import functools
from flask import request, jsonify
def requires_fields(fields):
required_fields = set(fields)
def wrapper(func):
@functools.wraps(func)
def decorated(*args, **kwargs):
current_fields = set(request.get_json().keys())
missing_fields = required_fields - current_fields
if missing_fields:
return jsonify({'error': 'missing fields', 'fields': list(missing_fields)}), 400 # Bad Request
resp = func(*args, **kwargs)
return resp
return wrapper
@app.route('/is_registered', methods=['POST'])
@requires_fields(['mobile'])
def is_registered():
_json = request.get_json()
keys = _json.keys()
customer = Customer()
registered = False
response = verify_required_params(['mobile'], keys)
if response:
return response
_mobile = _json['mobile']
validated = validate_mobile(_mobile)
cust, response_code = customer.get(_mobile)
if cust is not None and cust['id']:
registered = True
if not validated:
response = responses.get(MOBILE_NUMBER_NOT_VALID)
return jsonify(response)
if not registered:
response = responses.get(MOBILE_NUMBER_NOT_REGISTERED)
return jsonify(response)
response = responses.get(MOBILE_NUMBER_REGISTERED)
return jsonify(response)
It is giving me this error:它给了我这个错误:
assert view_func is not None, "expected view func if endpoint is not provided."
AssertionError: expected view func if endpoint is not provided.
What is causing this issue?是什么导致了这个问题? How can we fix this?我们如何解决这个问题?
You forgot to return the decorated
function from the wrapper
function.您忘记从wrapper
function 中返回decorated
的 function。
When you do @wrapper
on top of a function test
for instance, you are basically writing test = wrapper(test)
.例如,当您在 function test
之上执行@wrapper
时,您基本上是在编写test = wrapper(test)
。
Since wrapper
does not return anything, you get an error.由于wrapper
不返回任何内容,因此您会收到错误消息。
So basically you need to do:所以基本上你需要做:
def requires_fields(fields):
required_fields = set(fields)
def wrapper(func):
@functools.wraps(func)
def decorated(*args, **kwargs):
# ...
return decorated # you are missing this
return wrapper
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.