Complete e-commerce project--(10) Performance optimization (1): Homepage static

Homepage static

Introduction

  • Scenario: When the data defense is very small, you can make the page static. The homepage static is to save the rendered html page of the homepage
  • advantage:
    • No need for Django execution
    • No need for mysql (database) execution
    • Improve performance and improve server execution efficiency

Home frequently used solutions

Timed generation

Where can I find the rendered html page?

Insert picture description here
We know that the render function returns the HttpResponse object , which contains the rendered template page. This is what we need.

  • Then find: HttpSesponse object has a property, you can get a response in response to the body , this is the template rendering we need, the need to save static things.
    Insert picture description here
Save the code of the static page (partial)
  • We create a file and write a method in it to generate the preservation of this static page
	# 构造上下文
    context = {
    
    
        'categories': categories,  # 三级分类
        'contents': contents,  # 轮播图
    }
    response =  render(None, 'index.html', context)
    # 2.拿到html
    html_str = response.content.decode()
    # 写文件
    with open(os.path.join(settings.BASE_DIR, 'static/index1.html'), 'w') as f:
        f.write(html_str)
How to set the timing? Call this method regularly to generate new static pages
Installation package, used to make django call linux timer
# 安装
pip install django-crontab

# 注册
INSTALLED_APPS = [    
    'django_crontab', # 定时任务
]

# 设置定时任务
定时时间基本格式 :

*  *  *  *  *

分 时 日 月 周    命令

M: 分钟(0-59)。每分钟用 * 或者 */1 表示
H:小时(0-23)。(0表示0点)
D:天(1-31)。
m: 月(1-12)。
d: 一星期内的天(0~60为星期天)。

# 例子
CRONJOBS = [
    # 每5分钟生成一次首页静态文件
    ('*/5 * * * *', 'contents.crons.generate_index_html', '>> ' + os.path.join(os.path.dirname(BASE_DIR), 'logs/crontab.log'))
]

# 解决中文问题
# 在定时任务中,如果出现非英文字符,会出现字符异常错误
CRONTAB_COMMAND_PREFIX = 'LANG_ALL=zh_cn.UTF-8'

# 管理定时任务
# 添加定时任务到系统中
$ python manage.py crontab add

# 显示已激活的定时任务
$ python manage.py crontab show

# 移除定时任务
$ python manage.py crontab remove
  • Now you can use these commands to manage the timer.
    Insert picture description here
    After that, our static method will be automatically run every 5 minutes.

Guess you like

Origin blog.csdn.net/pythonstrat/article/details/108215503