I have a series of view callables that all need to execute a series of functions that perform validations and if one of these validations fails, it will return the output for view callable. If all of these validations pass, then the rest of the logic in the view callable should execute and ultimately produce the appropriate output. This looks like this in pseudo code:
@view_config(...)
def my_view(request):
# perform a validation and return an error dictionary if there was a problem
o = validate_thingy_a(request)
if o: return o
# perform a validation and return an error dictionary if there was a problem
o = validate_thingy_b(request)
if o: return o
# validations were all good, go on to produce sunny day output
return { "result" : "normal view results"}
So although that's not as elegant as a like, it works. But here's my real question: If you have a series of related view callables that all need these same validations done up front, is there a good way to code them so that each of them doesn't have to list those same few validation blocks?
I thought about decorators but the problem is I think if I created multiple decorators (one for each validation) then what I need to happen is if a given validator decorator fails, it should emit an error dictionary on behalf of the view callable and the other decorators shouldn't then run. But I don't think you can wire up decorators to easily skip the "remaining decorators" applied to a function.
Then, I went on consider doing this in a class somehow, like this, maybe:
class ApiStandard(object):
def __init__(self, request)
self.request = request
# would like to do validations here that precede all view callables below
# but can't figure out how to "return" output for the callable if a
# validation fails - then we don't want the view callable to be called.
@view_config(route=...)
def view_callable1(self):
...
@view_config(route=...)
def view_callable2(self):
...
But I don't think that can work because I don't think init can emit a result on behalf of a view and cause the view not to be called.
The last arrangement with a class is adding a validate method to the class and having each view callable call it. This is slightly better than putting all the individual checks in each callable, but not much, you still have to remember to call this method when adding another view callable.
class ApiStandard(object):
def __init__(self, request)
self.request = request
def common_validations():
# perform common validations and return an error dict if there was a problem
@view_config(route=...)
def view_callable1(self):
o = common_validations()
if o: return o
...
enter code here
@view_config(route=...)
def view_callable2(self):
o = common_validations()
if o: return o
...
I don't find any of the above solutions to be very elegant. Is there a good way to handle common bit of code for related view callables??