O'Reilly logo

Head First Python, 2nd Edition by Paul Barry

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required