Showing posts with label Performance Optimization. Show all posts
Showing posts with label Performance Optimization. Show all posts

Sunday, October 13, 2024

How to Store Session Information in Django: File, Database, or Cache


Django Session Storage Methods Explained

Django Session Storage Methods Explained


Introduction

Sessions are critical in web applications to maintain user state across multiple requests. Without sessions, every request would be stateless, making authentication and personalization impossible.

Django provides three powerful session storage mechanisms:

  • File-based storage
  • Database storage
  • Cache storage

1. File-Based Sessions

๐Ÿ“– How It Works

Django stores session data as files on disk. Each session = one file.

⚙️ Configuration
SESSION_ENGINE = 'django.contrib.sessions.backends.file'
SESSION_FILE_PATH = '/path/to/session/files'
๐Ÿ’ป Example Code
# Saving session data
request.session['user_id'] = 101

# Accessing session
user_id = request.session.get('user_id')
๐Ÿ–ฅ️ CLI Output
$ ls /tmp/django_sessions/
sess_abc123
sess_xyz456

$ cat sess_abc123
{"user_id":101,"_auth_user_id":"1"}
✅ Pros & ❌ Cons
  • ✅ Easy setup
  • ❌ Poor scalability
  • ❌ Disk I/O overhead

2. Database Sessions

๐Ÿ“– How It Works

Session data is stored in a database table called django_session.

⚙️ Configuration
SESSION_ENGINE = 'django.contrib.sessions.backends.db'
๐Ÿ’ป Example Code
# Store session
request.session['cart'] = {'item': 'book', 'qty': 2}

# Retrieve session
cart = request.session.get('cart')
๐Ÿ–ฅ️ CLI Output
$ python manage.py migrate

Operations to perform:
Apply all migrations: sessions

Running migrations:
Applying sessions.0001_initial... OK
๐Ÿ“Š Database View
SELECT * FROM django_session;

session_key | session_data | expire_date
--------------------------------------------------
abc123      | encoded_data | 2026-03-30
✅ Pros & ❌ Cons
  • ✅ Scalable
  • ✅ Centralized
  • ❌ Adds DB load

3. Cache-Based Sessions

๐Ÿ“– How It Works

Sessions are stored in memory (Redis/Memcached), making them extremely fast.

⚙️ Configuration
SESSION_ENGINE = 'django.contrib.sessions.backends.cache'

CACHES = {
 'default': {
   'BACKEND': 'django_redis.cache.RedisCache',
   'LOCATION': 'redis://127.0.0.1:6379/1',
 }
}
๐Ÿ’ป Example Code
request.session['token'] = 'abc123xyz'
token = request.session.get('token')
๐Ÿ–ฅ️ CLI Output
127.0.0.1:6379> KEYS *
1) "django_session:abc123"

127.0.0.1:6379> GET django_session:abc123
"{'token': 'abc123xyz'}"
⚡ Cached DB Hybrid
SESSION_ENGINE = 'django.contrib.sessions.backends.cached_db'
✅ Pros & ❌ Cons
  • ✅ Fastest
  • ✅ Scales well
  • ❌ Data loss risk

Which One Should You Choose?

Use Case Recommended
Development File-based
Small to Medium Apps Database
High Traffic Cache (Redis)

๐Ÿ’ก Key Takeaways

  • Sessions maintain user state across requests
  • File storage is simple but not scalable
  • Database storage is reliable and structured
  • Cache storage offers best performance
  • Use cached_db for balanced performance


Conclusion

Django’s session framework provides flexible and powerful ways to manage user data. Choosing the right backend depends on your scalability, performance, and reliability needs.

Start simple, and evolve your session strategy as your application grows.

Friday, August 16, 2024

Comparison of np.zeros and np.empty in NumPy: Initialization, Performance, and Use Cases

np.zeros vs np.empty in NumPy

np.zeros vs np.empty in NumPy

Understanding array initialization, performance, and use cases

NumPy provides multiple ways to create arrays. Two commonly used functions are np.zeros and np.empty. While they may look similar, they behave very differently under the hood.

np.zeros

๐Ÿ”ข Purpose & Behavior

np.zeros creates an array of a specified shape and initializes every element to 0.

This provides a clean and predictable starting point for computations.

๐Ÿงช Example
import numpy as np

array = np.zeros((3, 3))
print(array)

Output:

[[0. 0. 0.]
 [0. 0. 0.]
 [0. 0. 0.]]

Here, a 3×3 array is created and every element is explicitly set to zero.

np.empty

⚠️ Purpose & Behavior

np.empty creates an array of a specified shape without initializing its values.

The array contains whatever data already exists in memory at the time of allocation—often referred to as “garbage values.”

๐Ÿงช Example
import numpy as np

array = np.empty((3, 3))
print(array)

Output (example):

[[6.94843117e-310 6.94843117e-310 0.00000000e+000]
 [0.00000000e+000 6.94843113e-310 6.94843113e-310]
 [6.94843113e-310 6.94843113e-310 6.94843113e-310]]

The values appear random because NumPy does not overwrite memory when using np.empty.

Key Differences

Aspect np.zeros np.empty
Initialization All values set to 0 Uninitialized (random memory values)
Predictability Fully predictable Unpredictable
Performance Slightly slower Faster
Typical Use Clean starting state Immediate overwrite

When Should You Use Each?

  • Use np.zeros when you need a safe, known baseline for calculations.
  • Use np.empty when performance matters and you plan to assign all values immediately.

๐Ÿ’ก Key Takeaways

  • np.zeros guarantees clean initialization
  • np.empty skips initialization for speed
  • Uninitialized arrays may contain garbage values
  • Choose based on safety vs performance needs
  • Never rely on values from np.empty without overwriting them
NumPy array initialization: np.zeros vs np.empty

Featured Post

How HMT Watches Lost the Time: A Deep Dive into Disruptive Innovation Blindness in Indian Manufacturing

The Rise and Fall of HMT Watches: A Story of Brand Dominance and Disruptive Innovation Blindness The Rise and Fal...

Popular Posts