Chapter 10. Function Decorators: Wrapping Functions

image with no caption

When it comes to augmenting your code, Chapter 9’s context management protocol is not the only game in town.

Python also lets you use function decorators, a technique whereby you can add code to an existing function without having to change any of the existing function’s code. If you think this sounds like some sort of black art, don’t despair: it’s nothing of the sort. However, as coding techniques go, creating a function decorator is often considered to be on the harder side by many Python programmers, and thus is not used as often as it should be. In this chapter, our plan is to show you that, despite being an advanced technique, creating and using your own decorators is not that hard.

Your Webapp Is Working Well, But...

You’ve shown the latest version of your webapp to a colleague, and they’re impressed by what you’ve done. However, they pose an interesting question: is it wise to let any web user view the log page?

The point they’re making is that anybody who is aware of the /viewlog URL can use it to view the logged data whether they have your permission or not. In fact, at the moment, every one of your webapp’s URLs are public, so any web user can access any of them.

Depending on what you’re trying to do with your webapp, this may or may not be an issue. However, it is common for websites to require users to authenticate before ...

Get Head First Python, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.