django项目中如何使用celery生成首页静态页面

1. celery概览图:

2. 安装celery:

pip install celery==4.1.1

pip install combu==4.2.0

pip install redis==2.10.6

3. django项目目录下新建一个Python包:celery_tasks,在该包下新建一个python文件:tasks.py

4. tasks.py文件中代码如下:

from celery import Celery
from django.conf import settings
from django.template import loader, RequestContext

# django项目的初始化, 在任务处理者一端加入下面四行
import os
import django
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "dailyfresh.settings")
django.setup()

# 此句必须写在项目初始化下面
from goods.models import GoodsType, IndexGoodsBanner, IndexPromotionBanner, IndexTypeGoodsBanner


# 创建一个Celery类的实例对象
app = Celery("celery_tasks.tasks", broker="redis://127.0.0.1:6379/8")


# 定义任务函数, 并使用celery对象的task方法对发邮件函数进行装饰
@app.task
def generate_static_index_html():
    """生成首页静态页面"""
    # 获取商品的种类信息
    types = GoodsType.objects.all()

    # 获取首页轮播商品信息
    goods_banners = IndexGoodsBanner.objects.all().order_by("index")

    # 获取首页促销活动信息
    promotion_banners = IndexPromotionBanner.objects.all().order_by("index")

    # 获取首页分类商品展示信息
    # type_goods_banners = IndexTypeGoodsBanner.objects.all()  不能这样查,得按照商品种类顺序查

    for type in 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.image_banners = image_banners
        type.title_banners = title_banners

    # 组织模板上下文
    context = {"types": types,
               "goods_banners": goods_banners,
               "promotion_banners": promotion_banners}

    # 1. 加载模板文件,返回模板对象
    temp = loader.get_template("static_index.html")
    # 3. 渲染模板,返会标准的html内容
    static_index_html = temp.render(context)

    # 生成首页对应静态文件
    save_path = os.path.join(settings.BASE_DIR, "static/index.html")
    with open(save_path, "w") as f:
        f.write(static_index_html)

5. 生成静态页面

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

专职

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值