Dajngo19-缓存与静态页面

来源:互联网 发布:mmd姿势数据百度网盘 编辑:程序博客网 时间:2024/06/07 19:24

一般来说我们用 Django 来搭建一个网站,要用到数据库等。

1
2
3
4
5
from django.shortcuts import render
def index(request):
    # 读取数据库等 并渲染到网页
    # 数据库获取的结果保存到 queryset 中
    return render(request, 'index.html', {'queryset':queryset})

像这样每次访问都要读取数据库,一般的小网站没什么问题,当访问量非常大的时候,就会有很多次的数据库查询,肯定会造成访问速度变慢,服务器资源占用较多等问题。

1
2
3
4
5
6
7
from django.shortcuts import render
from django.views.decorators.cache import cache_page
 
@cache_page(60 * 15# 秒数,这里指缓存 15 分钟,不直接写900是为了提高可读性
def index(request):
    # 读取数据库等 并渲染到网页
    return render(request, 'index.html', {'queryset':queryset})

当使用了cache后,访问情况变成了如下:

1
2
3
4
5
6
7
8
9
访问一个网址时, 尝试从 cache 中找有没有缓存内容
如果网页在缓存中显示缓存内容,否则生成访问的页面,保存在缓存中以便下次使用,显示缓存的页面。
given a URL, try finding that page in the cache
if the page is in the cache:
    return the cached page
else:
    generate the page
    save the generated page in the cache (for next time)
    return the generated page

Memcached 是目前 Django 可用的最快的缓存

另外,Django 还可以共享缓存。



Django 生成静态页面

如果网站的流量过大,每次访问时都动态生成,执行SQL语句,消耗大量服务器资源,这时候可以考虑生成静态页面。

生成静态很简单,下面是一个例子:

只要在views.py中这样写就行了

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
from django.shortcuts import render
from django.template.loader import render_to_string
import os
 
 
def my_view(request):
    context = {'some_key''some_value'}
 
    static_html = '/path/to/static.html'
 
    if not os.path.exists(static_html):
        content = render_to_string('template.html', context)
        with open(static_html, 'w') as static_file:
            static_file.write(content)
 
    return render(request, static_html)

上面的例子中,当用户访问时,如果判断没有静态页面就自动生成静态页面,然后返回静态文件,当文件存在的时候就不再次生成。

也可以用一个文件夹,比如在project下建一个 static_html 文件夹,把生成的静态文件都放里面,让用户像访问静态文件那样访问页面。

更佳办法

但是一般情况下都不需要生成静态页面,因为Django 有缓存功能,使用 Django Cache(缓存)就相当于把生成生成静态页面,而且还有自动更新的功能,比如30分钟刷新一下页面内容。

用Django管理静态网站内容

如果服务器上不支持Django环境,你可以在本地上搭建一个Django环境,然后生成静态页面,把这些页面放到不支持 Django 的服务器上去,在本地更新,然后上传到服务器,用Django来管理和更新网站的内容,也是一个不错的做法,还可以更安全,听说有很多黑客都是这么做的。


原创粉丝点击