頁面靜態化的作用:
1. 避免每次訪問都要查詢資料庫的⼤大量量資料
2. 採用主⻚頁靜態的方式是為了提公升主頁的訪問效率,因為主頁是**訪問量最大的頁面
1. 準備主⻚頁靜態化工具方法(contents.crons.py)
2.準備主頁模板檔案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 =
# 讀取templates中的index.html檔案
# get_template : 缺省會去settings檔案中找到templates指定的html檔案
template = loader.get_template('index.html')
# 使用查詢出來的上下文資料,渲染index.html
html_text = template.render(context)
# 將渲染好的靜態的index.html檔案寫入到front_end_pc資料夾中
file_path = os.path.join(settings.generated_static_html_files_dir, 'index.html')
with open(file_path, 'w') as f:
f.write(html_text)
在templates中新增index.html模板檔案
在配置中修改配置檔案的路徑
'dirs': [os.path.join(base_dir, 'templates')],
還需要新增index.js檔案
3.準備靜態檔案存放的位置
4. shell 命令測試主⻚頁靜態化# 靜態化主⻚頁儲存路路徑
generated_static_html_files_dir = os.path.join(os.path.dirname(os.path.dirname(base_dir)), 'front_end_pc')
python manage.py shell
from contents.crons import generate_static_index_html
generate_static_index_html()
頁面靜態化
隨著 的內容的增多和使用者訪問量的增多,無可避免的是 載入會越來越慢,受限於頻寬和伺服器同一時間的請求次數的限制,我們往往需要在此時對我們的 進行 優化和伺服器配置的優化。一般情況下會從以下方面來做優化 什麼是靜態化?純靜態 將php程式生成靜態的html檔案,儲存到伺服器的磁碟中。客戶端訪問的時候...
頁面靜態化
header content type text html charset utf8 set time limit 0 url str file get contents url var dump str die reg isu preg match all reg,str,arr var dump...
頁面靜態化
隨著 的內容的增多和使用者訪問量的增多,無可避免的是 載入會越來越慢,受限於頻寬和伺服器同一時間的請求次數的限制,我們往往需要在此時對我們的 進行 優化和伺服器配置的優化。一般情況下會從以下方面來做優化 1.為什麼要靜態化?一 加快頁面開啟瀏覽速度,因為無需連線資料庫 二 有利於搜尋引擎優化seo ...