Created
May 5, 2022 19:13
-
-
Save EteimZ/a3661a90af26bd9c6899320694730af2 to your computer and use it in GitHub Desktop.
Understanding python decorators through flask.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # use the app.route with syntactic sugar | |
| from flask import Flask | |
| app = Flask(__name__) | |
| @app.route('/<string:name>') | |
| def hello(name): | |
| return f"Hello {name}" | |
| if __name__ == '__main__': | |
| app.run(debug=True) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # use the app.route decorator without syntactic sugar | |
| from flask import Flask | |
| app = Flask(__name__) | |
| wrapper = app.route('/<int:num>') # return wrapper function from decorator | |
| # define decorated function | |
| def numero(num): | |
| return f"Number {num}" | |
| wrapper(numero) | |
| if __name__ == '__main__': | |
| app.run(debug=True) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # Define view function as a lambda function | |
| from flask import Flask | |
| app = Flask(__name__) | |
| decora = app.route('/anon/<int:num>') # return wrapper function from decorator | |
| anom = lambda num : f"Anonymous view {num}" # create lambda view function | |
| decora(anom) | |
| if __name__ == '__main__': | |
| app.run(debug=True) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # Define your own decorator | |
| from flask import Flask | |
| app = Flask(__name__) | |
| # decorator function | |
| def my_route(rule, **options): | |
| # wrapper function | |
| def wrapper(f): | |
| endpoint = options.pop("endpoint", None) | |
| app.add_url_rule(rule, endpoint, f, **options) | |
| return f | |
| return wrapper | |
| @my_route('/hi') | |
| def hi(): | |
| return "<h1> HI </h1>" | |
| if __name__ == '__main__': | |
| app.run(debug=True) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment