Functions with Decorators and Parameters
When you need a function to accept arguments, while also having a decorator attached to it, the wrap function must take in the same exact arguments as the original function. Let’s try it:
1| # creating a decorator for a function that accepts parameters 3| def birthday(func):
4| def wrap(name, age):
5| func(name, age + 1)
6| return wrap
8| @birthday 9| def celebrate(name, age):
10| print( "Happy birthday { }, you are now { }.".format(name, age) )
12| celebrate("Paul", 43)
Go ahead and run the cell. This will output a nicely formatted string with the information passed in on line 12. When we call celebrate, the decorator takes in celebrate as the argument of func, and the two arguments “Paul” and “43” get passed into wrap. When we call our function within wrap, we pass the same arguments into the function call; however, we increment the age parameter by one.
Restricting Function Access
You’re probably wondering how decorators can serve a purpose, since the last few cells seem meaningless. For each one of them, we could have simply added those lines within the original function. That was just for syntax understanding though. Decorators are used a lot with frameworks and help to add functionality to many functions that you’ll write within them. One example is being able to restrict access of a page or function based on user login credentials. Let’s create a decorator that will help to restrict access if the password doesn’t match:
1| # real world sim, restricting function access 3| def login_required(func):
4| def wrap(user):
5| password = input("What is the password?") 6| if password == user["password"]:
7| func(user) 8| else:
9| print("Access Denied")
10| return wrap
12| @login_required 13| def restrictedFunc(user): 14| print( "Access granted, welcome { }".format(user[ "name" ]) )
16| user = { "name" : "Jess", "password" : "ilywpf" }
18| restrictedFunc(user)
Go ahead and run the cell. On line 13 we declared a normal function that would take in a user and output a statement with their name and accessibility. Our decorator was attached on line 12 so that when we call restrictedFunc and pass in our created user, it would run through the decorator. Within the wrap function, we ask the user for a password and check whether the password is correct or not on line 6. If they type in the correct password, then we allow them to access the function and print out “Access Granted”. However, if the password is incorrect, then we output “Access Denied” and never run restrictedFunc. This is a simple example of how Flask handles user restrictions for pages, but it proves the importance of decorators. We can now attach login_required to any of the functions that we feel should be accessed only by users.
Do'stlaringiz bilan baham: |