search
HomeDatabaseRedisHow to use django redis

How to use django redis

Jun 03, 2023 pm 02:53 PM
redisdjango

1. Description

Redis, as a cache database, plays a great role in all aspects. Python supports operating redis. If you use Django, there is a redis library specially designed for Django, namely django- redis

2. Installation

pip install django-redis

3. Configuration

3.1 Configure redis

Open the Django configuration file, such as setting.py, and set CACHES in it Item

CACHES = {
    "default": {
        "BACKEND": "django_redis.cache.RedisCache",
        "LOCATION": "redis://127.0.0.1:6379/1",
        "OPTIONS": {
            "CLIENT_CLASS": "django_redis.client.DefaultClient",
        }
    }
}

Multiple redis connection information can be configured in one CACHES. Each one has its own alias (alias). The "default" above is the alias. At that time, you can connect to different redis databases through different aliases

LOCATION is the connection information, including ip port user password, etc. If the user password is not required, you can omit it. django-redis supports three connection protocols, as follows

##redis://Ordinary TCP suite Interface connectionredis://[[username]:[password]]@localhost:6379/0redissSSL mode TCP socket connectionrediss://[[username]:[password]]@localhost:6379/0rediss://Unix domain socket connectionunix://[[username]:[password]]@/path/to/socket.sock?db=0
Protocol Description Example
3.2 Use redis to store session

Django’s default Session is stored in the sql database, but we all know that ordinary data will be stored on the hard disk, and the speed is not that fast. If you want to To change it to be stored in redis, you only need to configure it in the configuration file

SESSION_ENGINE = "django.contrib.sessions.backends.cache"
SESSION_CACHE_ALIAS = "default"

3.3 redis connection timeout setting

The number of seconds for the connection timeout can be specified in the configuration item, SOCKET_CONNECT_TIMEOUT indicates the connection The timeout of redis, SOCKET_TIMEOUT represents the timeout of read and write operations using redis

CACHES = {
    "default": {
        # ...
        "OPTIONS": {
            "SOCKET_CONNECT_TIMEOUT": 5,  # 连接redis超时时间,单位为秒
            "SOCKET_TIMEOUT": 5,  # redis读写操作超时时间,单位为秒
        }
    }
}

4. Using redis

4.1 Use the default redis

If you want to use the default redis , that is, the redis with the alias "default" set in the configuration file can refer to the cache in django.core.cache

from django.core.cache import cache

cache.set("name", "冰冷的希望", timeout=None)
print(cache.get("name"))

4.2 Use the specified redis (native redis)

When you Multiple redis connections are written in the configuration file. You can specify which redis to use through alias

from django_redis import get_redis_connection

redis_conn = get_redis_connection("chain_info")
redis_conn.set("name", "icy_hope")
print(redis_conn.get("name"))

It should be noted that the client obtained through get_redis_connection() is a native Redis client, although basically all are supported Native redis command, but the data it returns is of byte type, you need to decode it yourself

5. Connection pool

The advantage of using the connection pool is that you don’t need to manage the connection object, it will automatically create some connections Objects and reused as much as possible, so the performance will be relatively better

5.1 Configuring the connection pool

To use the connection pool, first write the maximum connection pool size in the Django configuration file Number of connections

CACHES = {
    "default": {
        "BACKEND": "django_redis.cache.RedisCache",
        ...
        "OPTIONS": {
            "CONNECTION_POOL_KWARGS": {"max_connections": 100}
        }
    }
}

5.2 Using connection pool

We can determine which redis to use through the connection alias, and then just execute the command normally. We don’t need to care about which connection instances it creates, but you can pass The _created_connections attribute of connection_pool checks how many connection instances are currently created

from django_redis import get_redis_connection

redis_conn = get_redis_connection("default")
redis_conn.set("name", "冰冷的希望")
print(redis_conn.get("name"))

# 查看目前已创建的连接数量
connection_pool = redis_conn.connection_pool
print(connection_pool._created_connections)

5.3 Custom connection pool

The default connection class of Django-redis is DefaultClient, if you have higher customization requirements , you can create a new class of your own and inherit ConnectionPool

from redis.connection import ConnectionPool

class MyPool(ConnectionPool):
    pass

After you have this class, you need to specify it in the Django configuration file

"OPTIONS": {
    "CONNECTION_POOL_CLASS": "XXX.XXX.MyPool",
}

The above is the detailed content of How to use django redis. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:亿速云. If there is any infringement, please contact admin@php.cn delete
Redis: Beyond SQL - The NoSQL PerspectiveRedis: Beyond SQL - The NoSQL PerspectiveMay 08, 2025 am 12:25 AM

Redis goes beyond SQL databases because of its high performance and flexibility. 1) Redis achieves extremely fast read and write speed through memory storage. 2) It supports a variety of data structures, such as lists and collections, suitable for complex data processing. 3) Single-threaded model simplifies development, but high concurrency may become a bottleneck.

Redis: A Comparison to Traditional Database ServersRedis: A Comparison to Traditional Database ServersMay 07, 2025 am 12:09 AM

Redis is superior to traditional databases in high concurrency and low latency scenarios, but is not suitable for complex queries and transaction processing. 1.Redis uses memory storage, fast read and write speed, suitable for high concurrency and low latency requirements. 2. Traditional databases are based on disk, support complex queries and transaction processing, and have strong data consistency and persistence. 3. Redis is suitable as a supplement or substitute for traditional databases, but it needs to be selected according to specific business needs.

Redis: Introduction to a Powerful In-Memory Data StoreRedis: Introduction to a Powerful In-Memory Data StoreMay 06, 2025 am 12:08 AM

Redisisahigh-performancein-memorydatastructurestorethatexcelsinspeedandversatility.1)Itsupportsvariousdatastructureslikestrings,lists,andsets.2)Redisisanin-memorydatabasewithpersistenceoptions,ensuringfastperformanceanddatasafety.3)Itoffersatomicoper

Is Redis Primarily a Database?Is Redis Primarily a Database?May 05, 2025 am 12:07 AM

Redis is primarily a database, but it is more than just a database. 1. As a database, Redis supports persistence and is suitable for high-performance needs. 2. As a cache, Redis improves application response speed. 3. As a message broker, Redis supports publish-subscribe mode, suitable for real-time communication.

Redis: Database, Server, or Something Else?Redis: Database, Server, or Something Else?May 04, 2025 am 12:08 AM

Redisisamultifacetedtoolthatservesasadatabase,server,andmore.Itfunctionsasanin-memorydatastructurestore,supportsvariousdatastructures,andcanbeusedasacache,messagebroker,sessionstorage,andfordistributedlocking.

Redis: Unveiling Its Purpose and Key ApplicationsRedis: Unveiling Its Purpose and Key ApplicationsMay 03, 2025 am 12:11 AM

Redisisanopen-source,in-memorydatastructurestoreusedasadatabase,cache,andmessagebroker,excellinginspeedandversatility.Itiswidelyusedforcaching,real-timeanalytics,sessionmanagement,andleaderboardsduetoitssupportforvariousdatastructuresandfastdataacces

Redis: A Guide to Key-Value Data StoresRedis: A Guide to Key-Value Data StoresMay 02, 2025 am 12:10 AM

Redis is an open source memory data structure storage used as a database, cache and message broker, suitable for scenarios where fast response and high concurrency are required. 1.Redis uses memory to store data and provides microsecond read and write speed. 2. It supports a variety of data structures, such as strings, lists, collections, etc. 3. Redis realizes data persistence through RDB and AOF mechanisms. 4. Use single-threaded model and multiplexing technology to handle requests efficiently. 5. Performance optimization strategies include LRU algorithm and cluster mode.

Redis: Caching, Session Management, and MoreRedis: Caching, Session Management, and MoreMay 01, 2025 am 12:03 AM

Redis's functions mainly include cache, session management and other functions: 1) The cache function stores data through memory to improve reading speed, and is suitable for high-frequency access scenarios such as e-commerce websites; 2) The session management function shares session data in a distributed system and automatically cleans it through an expiration time mechanism; 3) Other functions such as publish-subscribe mode, distributed locks and counters, suitable for real-time message push and multi-threaded systems and other scenarios.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment