python - django用通用视图以后如何生成静态页面?
高洛峰
高洛峰 2017-04-18 09:06:00
0
2
407

我的需求

用户访问index的时候,需要生成一个静态文件,比如index.html

强调一下,我要生成的是静态文件!不要建议我用缓存或是其他什么的,我就是要生成一个静态网站!!!

我的代码

views.py 是这样的:

class IndexView(BaseMixin, ListView):
    template_name = 'index.html'
    context_object_name = 'article_list'
    paginate_by = settings.PAGE_NUM  # 分页--每页的数目


    def get_queryset(self):
        article_list = Article.objects.filter(status=0)
        return article_list

    def get_context_data(self, **kwargs):
        # 轮播
        kwargs['carousel_page_list'] = Carousel.objects.all()
        kwargs['home']= True
        return super(IndexView, self).get_context_data(**kwargs)

我的思路:

用户访问index,打开指定路径的文件,然后写入渲染出来的模板的代码

比如这样,在视图中加这样一段代码:

class IndexView(BaseMixin, ListView):
    ......
    with open("index.html", 'w') as static_file:
        static_file.write("123")
    ......

这样是可以的,访问首页的时候,会在根目录生成一个index.html的文件,但是不知道怎么渲染模板和变量!!!,还有我用的是jinjia2

扩展思路:

实在不行,就用下策,自己写个url的构造器,把django的所有链接给构造出来!
然后自己写个爬虫去爬自己的网站.
但是这样真的很低效!!

可能的思路:

感觉应该会有现成的模块来解决这个问题!
比如dedecms,zblog等都支持静态文件生成.
针对不支持动态的空间,生成静态页面我感觉还是很有必要的!


最后强调!

目标是生成一个静态网站!!!
目标是生成一个静态网站!!!
目标是生成一个静态网站!!!

高洛峰
高洛峰

拥有18年软件开发和IT教学经验。曾任多家上市公司技术总监、架构师、项目经理、高级软件工程师等职务。 网络人气名人讲师,...

reply all(2)
巴扎黑

Hahahahaha, using a crawler to crawl my own website is the same as when I used it = =, you can imagine it.

Usually the first thing that comes to mind is ajax interaction, but ajax seems to be dynamic? Okay (∩_∩), I think so, I don’t know if it’s right:

If each index has a relatively standardized style, then just assemble it as you said. You can use shell scripts or some python libraries. Anyway, it is enough to be able to operate files, as long as the files are there and the variables are etc. After everything has been replaced, is there a problem with rendering? You can add a thread waiting time to trigger something

But you don’t have to do this. In fact, wouldn’t it be better if you just render it directly and then convert it into a pure static web page and then output it? I haven't tried it, but when I was learning unittest and selenium, I came across Django's test web page output results, and I remembered a lot of built-in functions that convert them into pure HTML, and they can also render variables. On the contrary, if you add a token to protect it, it may not be transferred, but it is actually very troublesome if you assemble it with the first idea.

小葫芦

If you just want to generate a static page, you can do this
But there are many things to consider for a static website. Take paging as an example, you have to generate a static page for each page of data

template_name = 'index.html'
vm = {
    'key': 'value'
}
html =  render(request, template_name, vm).content

with open('index.html', 'w') as f:
    f.write(html)
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template