secrets | Python Standard Library – Real Python

The Python secrets module provides a straightforward and secure way to generate cryptographically strong random numbers suitable for managing sensitive data, such as passwords, account credentials, security tokens, and related secrets.

Here’s a quick example:

Key Features

  • Generates cryptographically secure random numbers
  • Provides functions to generate secure tokens
  • Offers functions to compare secrets in a way that avoids timing attacks

Frequently Used Classes and Functions

Examples

Generate a random byte string:

Generate a random text string in hexadecimal:

Generate a random URL-safe text string:

Common Use Cases

  • Generating secure tokens for session management
  • Creating cryptographically secure passwords
  • Comparing sensitive data in a secure manner

Real-World Example

Suppose you’re building a web application and need to generate secure tokens for user sessions. Here’s how you can use the secrets module to create a token:

In this example, the secrets module generates a secure, random URL-safe token suitable for managing user sessions.