[Django] page static and crontab timing tasks

A web page has a lot of data that does not need to be changed frequently. For example, the homepage has a low frequency of change and a large amount of visits. We can make it static, so that there is no need to query the database and return every time there is a request, which can reduce the number of servers. pressure

The so-called static page is to render a complete html page in advance and save it in the form of a static file, then the next time the browser visits it, it can directly return the static file.

We can use Django's template rendering function to complete page rendering

1. Page static

We create a new py file in the Django project and write a method for rendering the home page

from django.template import loader

def generate_static_index_html():
    # 先获取首页模版文件
    template = loader.get_template('index.html')
    # 要渲染的数据(动态数据)
    context = {
    
    
        'categories': None, 
        'contents': None
    }
    # 得到渲染后的完整页面
    page = template.render(context)
	# 把渲染后的文件保存起来
    with open('XXXXXXX/front_end_pc/index.html', 'w') as f:
        f.write(page)

We open the shell provided by Django, cd to the directory where the py file is located and execute the file to get the static page

2. crontab timing task

Although the page is not updated frequently, it is impossible to artificially execute the program to render a new page every time it needs to be updated. We can use timed tasks to automate

2.1 install crontab
pip install django-crontab -i https://pypi.tuna.tsinghua.edu.cn/simple
2.2 Register in the configuration file

We open the Django configuration file (dev.py here) and register crontab in the INSTALLED_APPS list

INSTALLED_APPS = [
  	.....
    'django_crontab', # 定时任务
]
3.3 Develop timing rules

When will crontab be executed, and what is the time interval, these need to be set in the Django configuration file (here, dev.py). Create a new CRONJOBS list

# 指定定时任务规则
CRONJOBS = [
	# 写法是:(时间规则,要执行的任务,">>",日志文件位置)
    # 每1分钟生成一次首页静态文件
    # 分 时 日 月 周
    ('*/1 * * * *', 'apps.contents.crons.generate_static_index_html', '>> ' + os.path.join(BASE_DIR, 'logs/crontab.log'))
    # 每月的23日12点1分0秒执行一次
    # ('1 12 23 * *', 'apps.contents.crons.generate_static_index_html', '>> ' + os.path.join(BASE_DIR, 'logs/crontab.log'))
]

If you encounter character exceptions caused by non-English characters during execution, you can add the following configuration

# ubuntu
CRONTAB_COMMAND_PREFIX = 'LANG_ALL=zh_cn.UTF-8'
# mac
CRONTAB_COMMAND_PREFIX = 'LANG=zh_cn.UTF-8'
3.4 Management tasks

Open the shell provided by Django and execute the following command management tasks

# 添加定时任务
python manage.py crontab add

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

# 移除定时任务
python manage.py crontab remove

Guess you like

Origin blog.csdn.net/qq_39147299/article/details/108533977
Recommended