Skip to Content
Flask Web Development, 2nd Edition
book

Flask Web Development, 2nd Edition

by Miguel Grinberg
March 2018
Intermediate to advanced
312 pages
7h 22m
English
O'Reilly Media, Inc.
Book available
Content preview from Flask Web Development, 2nd Edition

Chapter 9. User Roles

Not all users of web applications are created equal. In most applications, a small percentage of users are trusted with extra powers to help keep the application running smoothly. Administrators are the best example, but in many cases middle-level power users such as content moderators exist as well. To implement this, all users are assigned a role.

There are several ways to implement roles in an application. The appropriate method largely depends on how many roles need to be supported and how elaborate they are. For example, a simple application may need just two roles, one for regular users and one for administrators. In this case, having an is_administrator Boolean field in the User model may be all that is necessary. A more complex application may need additional roles with varying levels of power in between regular users and administrators. In some applications it may not even make sense to talk about discrete roles, and instead giving users a set of individual permissions may be the right approach.

The user role implementation presented in this chapter is a hybrid between discrete roles and permissions. Users are assigned a discrete role, but each role defines what actions it allows its users to perform through a list of permissions.

Database Representation of Roles

A simple roles table was created in Chapter 5 as a vehicle to demonstrate one-to-many relationships. Example 9-1 shows an improved Role model with some additions.

Example 9-1. app/models.py ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Mastering Flask Web Development - Second Edition

Mastering Flask Web Development - Second Edition

Daniel Gaspar, Jack Stouffer

Publisher Resources

ISBN: 9781491991725Errata Page