celery的生成静态文件的任务
@app.task
def generate_static_index_html():
# 先睡两秒,以防数据库更新太慢,数据还没更新就已经生成页面
sleep(5)
# 获取首页商品类型信息
goods_types = GoodsType.objects.all()
# 获取首页商品轮播信息
goods_banner = IndexGoodsBanner.objects.all().order_by('index')
# 获取首页活动轮播信息
promotion_banner = IndexPromotionBanner.objects.all().order_by('index')
# 获取首页分类商品展示信息
# type_goods_banner = IndexTypeGoodsBanner.objects.all()
for type in goods_types:
# 获取type种类首页分类商品的图片展示信息:
image_banners = IndexTypeGoodsBanner.objects.filter(type=type, display_type=1).order_by('index')
# 获取type种类首页分类商品的文字展示信息:
title_banners = IndexTypeGoodsBanner.objects.filter(type=type, display_type=0).order_by('index')
# 动态给type增加属性,分别保存首页分类商品的图片展示信息和文字展示信息
type.type_image = image_banners
type.type_title = title_banners
# 获取购物车商品数目
cart_count = 0
context = {
'goods_types': goods_types,
'goods_banner': goods_banner,
'promotion_banner': promotion_banner,
'cart_count': cart_count,
}
# 使用模板
# 1. 加载模板文件,返回模板对象
temp = loader.get_template('static_index.html')
# 2. 模板渲染
static_index_html = temp.render(context)
# 3. 生成首页对应的静态模板文件
save_path = os.path.join(settings.BASE_DIR, 'templates/generated_static_index.html')
with open(save_path, 'w', encoding='utf-8') as fb:
fb.write(static_index_html)
在admin 后台管理页面更新了数据时,需要使用celery 重新生成首页静态文件
class BaseModelAdmin(admin.ModelAdmin):
def save_model(self, request, obj, form, change):
super().save_model(request, obj, form, change)
# 后台管理页面发生变化后,则需要更新静态首页
from celery_tasks.tasks import generate_static_index_html
generate_static_index_html.delay()
# 后台管理页面发生变化后,首页的缓存数据也需要进行删除
cache.delete('index_page_data')
然后问题就来了:在我使用admin在后台更新完了数据,但是Nginx调用的静态文件并没有更新,而是一般在我第二次使用admin在后台更新数据后,第一次的数据才姗姗来迟,所以意味着Nginx有延迟。
后来想想,是不是celery去数据库查找数据太快了,小于后台admin更新数据库的时间?所以在celery tasks里让它睡了2秒,果不其然,问题解决。