dj-inmemorystorage

2.1.0 · active · verified Thu Apr 16

dj-inmemorystorage is a non-persistent in-memory data storage backend for Django, providing compatibility with Django's storage API. It is primarily used for testing purposes to avoid disk access and speed up test suites. The library is currently at version 2.1.0 and has an irregular release cadence, often tied to updates in Django and Python version support, as well as feature additions.

Common errors

Warnings

Install

Imports

Quickstart

To use dj-inmemorystorage, configure your Django settings (typically in `settings.py` or a test settings file) by setting `DEFAULT_FILE_STORAGE` to `'inmemorystorage.InMemoryStorage'`. By default, the storage is non-persistent; enable `INMEMORYSTORAGE_PERSIST = True` if you need writes to be retained across operations within the same storage instance. The example demonstrates saving, checking existence, reading, and deleting a file using the configured default storage.

import os
from django.conf import settings
from django.core.files.storage import default_storage

# Minimal Django settings for demonstration
if not settings.configured:
    settings.configure(
        DEFAULT_FILE_STORAGE='inmemorystorage.InMemoryStorage',
        INMEMORYSTORAGE_PERSIST=True, # Optional: Set to True for persistence within a single storage instance
        SECRET_KEY='a-very-secret-key',
        DEBUG=True
    )

# Use the default storage to save and retrieve a file
file_name = 'test_file.txt'
file_content = b'Hello, in-memory storage!'

# Save the file
default_storage.save(file_name, file_content)
print(f"File '{file_name}' saved to in-memory storage.")

# Check if the file exists
if default_storage.exists(file_name):
    print(f"File '{file_name}' exists.")

    # Read the file content
    with default_storage.open(file_name, 'rb') as f:
        content_read = f.read()
    print(f"Content of '{file_name}': {content_read.decode()}")

    # Delete the file
    default_storage.delete(file_name)
    print(f"File '{file_name}' deleted.")
else:
    print(f"File '{file_name}' does not exist after saving, check persistence settings.")

view raw JSON →