django 實現定時任務

2021-09-18 07:13:03 字數 2798 閱讀 2356

**的首頁頻繁被訪問,為了提公升訪問速度,除了我們之前已經學過的使用快取技術外,還可以使用頁面靜態化技術。

頁面靜態化即將動態渲染生成的頁面結果儲存成html檔案,放到靜態檔案伺服器中。使用者訪問的時候訪問的直接是處理好之後的html靜態檔案。

對於頁面中屬於每個使用者展示不同資料內容的部分,可以在使用者請求完靜態化之後的頁面後,在頁面中向後端傳送請求,獲取屬於使用者的特殊的資料。

我們現在將首頁進行頁面靜態化處理。

在廣告內容應用contents中,新建crons.py檔案(該檔案會用於後面講解的定時任務),在該檔案中編寫處理頁面靜態化的邏輯。

from collections import ordereddict

from django.conf import settings

from django.template import loader

import os

import time

from goods.models import goodschannel

from .models import contentcategory

def generate_static_index_html():

"""生成靜態的主頁html檔案

"""print('%s: generate_static_index_html' % time.ctime())

# 商品頻道及分類選單

# 使用有序字典儲存類別的順序

# categories = ,{}, {}...],

# 'sub_cats': [,{}]}, {}, {}, ..]

# },

# 2:

# }categories = ordereddict()

channels = goodschannel.objects.order_by('group_id', 'sequence')

for channel in channels:

group_id = channel.group_id # 當前組

if group_id not in categories:

categories[group_id] =

cat1 = channel.category # 當前頻道的類別

# 追加當前頻道

'id': cat1.id,

'name': cat1.name,

'url': channel.url

})# 構建當前類別的子類別

for cat2 in cat1.goodscategory_set.all():

cat2.sub_cats =

for cat3 in cat2.goodscategory_set.all():

# 廣告內容

contents = {}

content_categories = contentcategory.objects.all()

for cat in content_categories:

contents[cat.key] = cat.content_set.filter(status=true).order_by('sequence')

# 渲染模板

context =

template = loader.get_template('index.html')

html_text = template.render(context)

file_path = os.path.join(settings.generated_static_html_files_dir, 'index.html')

with open(file_path, 'w', encoding='utf-8') as f:

f.write(html_text)

對於首頁的靜態化,考慮到頁面的資料可能由多名運營人員維護,並且經常變動,所以將其做成定時任務,即定時執行靜態化。

在django執行定時任務,可以通過django-crontab擴充套件來實現。

pip install django-crontab
...

'django_crontab', # 定時任務

...]在配置檔案中設定定時執行的時間

每個定時任務分為三部分定義:

首頁的定時任務設定如下

# 定時任務

cronjobs = [

# 每5分鐘執行一次生成主頁靜態檔案

('*/5 * * * *', 'contents.crons.generate_static_index_html', '>> /users/delron/desktop/meiduo_mall/logs/crontab.log')

]

在定時任務中,如果出現非英文本元,會出現字元異常錯誤

可以通過在配置檔案中新增定時任務執行的附加命令來實現

# 解決crontab中文問題

crontab_command_prefix = 'lang_all=zh_cn.utf-8'

新增定時任務到系統中

python manage.py crontab add
顯示已經啟用的定時任務

python manage.py crontab show
移除定時任務

python manage.py crontab remove

django實現定時任務

目的 解決執行django專案的時候一起執行自己寫的py檔案 一 類別 linux celery和django crontab外掛程式 windows apscheduler django apscheduler,3.註冊後資料遷移 python manage.py migrateimport ti...

django定時任務

網上很多資料都是比較舊的,不同的版本使用上存在差異,最好的方式是,根據使用的版本檢視官方資料 任務執行結果 安裝 pip install django crontab pip install apscheduler pip install django apscheduler pip install...

Django 定時任務APScheduler

apscheduler官方user guide文件 一開始demo是這麼寫的 from apscheduler.scheduler import scheduler sched scheduler sched.interval schedule seconds 5 defmytask d1 time...