'make every function of a file start with the same call to an external function
I'll give a bit of context but I don't think you need to know about flask to understand my question.
I have a file (flask_app.py) and I would like all the functions (except the one handling the welcome page) to start with the call to the function verify(), more precisely those four lines (but it doesn't really matter what those lines are):
if verify():
pass
else:
return redirect("/")
redirect("/") should redirect the user to the welcome page if verify returns False. Again, it's not central.
It's however a little bit awkward to copy and paste these 4 lines everywhere in my code. I know I can make a one-liner out of it but this is still repeating one line in every function of my code. So my question is: is there any way to do this automatically? (a magic something I could write in Python at the beginning of the file to make all functions (except one, but I could just put it in another file to be fair) defined in this given file start by those 4 lines).
Solution 1:[1]
This runs either myfunc or redirect depending on the return value of verified. Note: To test this, change verified return value to True or False.
def verified():
print('verified')
return False
def redirect():
print('redirect')
def verify(func):
if verified():
return func
else:
return redirect
@verify
def myfunc():
print('myfunc')
myfunc()
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | lmielke |
