Django1.9 Development Blog-Redis Cache

Source: Internet
Author: User

Redis is a high-performance Key-value database. The emergence of Redis, to a large extent, compensates for the lack of memcached such keyvalue storage, in some cases can be a good complement to the relational database. It provides the python,ruby,erlang,php client, which is very convenient to use.

Now Redis has released the 3.0 version, formally supporting the distribution, this feature is so powerful that you don't have to sorry yourself again.

Performance testing

Server configuration: Linux 2.6, Xeon X3320 2.5Ghz

Set operation 110,000 times per second, get operation 81,000 times per second

The StackOverflow website uses Redis as a cache server.

Installing Redis

Server Installation Chapter I've written a special article, see Getting Started with Redis and installing

Configuration in Django

We hope that in this blog system, for the article hits, views and other data to achieve caching, improve efficiency.

Requirements.txt

Add the following to make it easy to install software dependencies later, because the Redis service is not installed on Pythonanywhere, so this chapter can only be tested locally.

redis==2.10.5
django-redis==4.4.2
apscheduler==3.1.0

settings.py Configuration

What's new

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21st
22
23
24
25
26
27
From Urllib.parseImport Urlparse
Import Dj_database_url

Redis_url = Urlparse (Os.environ.get (' Redistogo_url ',' redis://localhost:6959 '))
CACHES = {
' Default ': {
' Backend ':' Redis_cache.cache.RedisCache ',
' Location ':' {0}:{1} '. Format (Redis_url.hostname, Redis_url.port),
' OPTIONS ': {
' DB ':0,
' PASSWORD ': Redis_url.password,
' Client_class ':' Redis_cache.client.DefaultClient ',
' Pickle_version ':-1,# Use the latest protocol version
' Socket_timeout ':# in seconds
' ignore_exceptions ': True,
}
}
}

Session_engine = ' Django.contrib.sessions.backends.cache '
Session_cache_alias = ' Default '

# Local Development configuration placed in local_settings.py
Try
From . local_settings Import *
Except Importerror:
Pass

local_settings.py Configuration

This is the configuration file used in the local development time

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
DEBUG =True

CACHES = {
' Default ': {
' Backend ':' Redis_cache.cache.RedisCache ',
' location ': ' 192.168.203.95:6379:1 ',
' OPTIONS ': {
' client_class ': ' redis_cache.client.DefaultClient ',
# ' PASSWORD ': ' Secretpassword ',
' pickle_version ': -1, # Use the latest protocol VERSION
' socket_timeout ': Max , # in seconds
' ignore_exceptions ': True,
}
}
}

How to use the cache_manager.py cache Manager

We create a new cache manager cache_manager.py, which reads as follows

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
#!/usr/bin/env python
#-*-Encoding:utf-8-*-
"""
Topic:redis Cache Manager
"""
From.. ModelsImport Post
From Redis_cacheImport Get_redis_connection
From Apscheduler.schedulers.backgroundImport Backgroundscheduler

Running_timer =False
redis_db = Get_redis_connection (' Default ')


DefUpdate_click(POST):
"" "Update number of hits" ""
If Redis_db.hexists ("CLICKS", post.id):
Print' Redis_db.hexists ' + str (post.id))
Redis_db.hincrby (' CLICKS ', post.id)
Else
Print' Redis_db.not_hexists ' + str (post.id))
Redis_db.hset (' CLICKS ', post.id, Post.click +1)
Run_timer ()


DefGet_click(POST):
"" Gets the number of hits "" "
If Redis_db.hexists ("CLICKS", post.id):
Return Redis_db.hget (' CLICKS ', post.id)
Else
Redis_db.hset (' CLICKS ', Post.id, Post.click)
Return Post.click

DefSync_click():
"" "Sync article Hits" ""
print ( for k in redis_db.hkeys ( Span class= "string" > ' CLICKS '):
try:
P = Post.objects.get (k)
print ( ' db_click={0} '. Format (p.click))
print ( ' cache_click={0} '. Format (Cache_click))
if cache_click! = P.click:
P.click = Get_click (p.id)
except:
pass

views.py modification

Then we modify the view.py and use the Cache_manager in the corresponding action:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
From. CommonsImport Cache_manager

DefPost_list(Request):
"" All published articles ""
Posts = Post.objects.annotate (Num_comment=count (' Comment '). Filter (
Published_date__isnull=False). prefetch_related (
' Category '). prefetch_related (' tags '). order_by ('-published_date ')
For Pin posts:
return render (Request,
def Span class= "title" >post_detail (request, PK):
Try:
pass
except:
Span class= "line" > raise Http404 ()
if Post.published_date:
Cache_manager.update_click (post)
Post.click = Cache_manager.get_click (POST)

I don't have much to show for the rest.

Django1.9 Development Blog-Redis Cache

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.