# Use Redis with Django Rest Framework

> *What is considered slow depends on your requirements. But when something becomes slow it's a candidate for caching.* — [High Scalability](http://highscalability.com/bunch-great-strategies-using-memcached-and-mysql-better-together) 

We already know enough about Redis, Django & Django Rest Framework to use them.

Here is a video link to describe  [Redis ](https://youtu.be/G1rOthIU-uo) in 100 seconds in case you don't know about it.


1. First we will install a Redis server to use Redis locally.
2. Then we run the server and learn some basic commands for Redis CLI.
3. We will integrate Redis with Django Rest Framework.

## First
I'm using Debian therefore I'm going to install Redis via apt

```bash
sudo apt install redis
``` 

You can install Redis via .tar file and can use Docker. The instructions are [here](https://redis.io/download).

## Second

After installation finish, we can use `redis-server` in the terminal to start the local server and to access the server via CLI we run `redis-cli` in a different terminal.

Basic Redis commands are:
`SET [key] [value]` to set the string value to a key.
```bash
SET name Sagar
OK
```
`GET [key]` to get the value of a key.
```bash
GET name
"Sagar"
```
`KEYS *` to display the list of all stored keys.
```bash
KEYS *
1) "name"
```
`FLUSHDB` to remove all keys from the current database.

`FLUSHALL` to remove all keys from all the databases.

More commands can be found [here](https://redis.io/commands).


## Third

Install these required packages
```
pip install django djangorestframework django-redis
```

Start the Django project via `django-admin startproject test_project` & open your text editor into that folder. I use Visual Studio Codium so for me `codium test_project`.

Inside `settings.py`:-
```python
INSTALLED_APPS = [
    ....
    'rest_framework',
]

CACHES = {
    "default": {
        "BACKEND": "django_redis.cache.RedisCache",
        "LOCATION": "redis://127.0.0.1:6379/1", # Local Link provided by the redis-server command
        "OPTIONS": {
            "CLIENT_CLASS": "django_redis.client.DefaultClient",
        }
    }
}

```
> Explanation: `rest_framework` to use rest framework package and `CACHES` to connect Redis with Django same as we use to connect databases with Django.


Inside `views.py`:-
```python
from rest_framework.response import Response
from rest_framework.views import APIView
from django.core.cache import cache
from django.conf import settings
from django.core.cache.backends.base import DEFAULT_TIMEOUT
 
# For cache timeout
CACHE_TTL = getattr(settings, 'CACHE_TTL', DEFAULT_TIMEOUT)

class TestView(APIView):
    def get(self, request):
   
        # Locate name in redis database
        if 'name' in cache:
            # get results from cache
            name = cache.get('name')

            print('form cache')
            return Response(name)

        # If not found 
        else:
            result = {
                "name": "Sagar Yadav"
            }

            # store data in cache
            cache.set('name', result, timeout=CACHE_TTL)

            print('not from cache')
            return Response(result)

```

Lastly specify the url inside `urls.py`:-
```python
urlpatterns = [
    path('', TestView.as_view(), name='test-url'),
]
```

Now run the python server via `python3 manage.py runserver` and don't forget to start the redis via `redis-server`.

Visit `localhost:8000` in your browser and `refresh the page twice` where the response will always be the same each time, then check your python terminal. The terminal would look like this.

```bash
not from cache
[datetime] "GET / HTTP/1.1" 200 5110
form cache
[datetime] "GET / HTTP/1.1" 200 5110
form cache
[datetime] "GET / HTTP/1.1" 200 5110
```

Now, you know how you can use Redis with Django Rest Framework. You just have to think about what data you need to cache. You can store serialized data into a cache with a unique key to look upon and much more.

Thanks for reading.
