将静态JSON传递给Django模板-最佳做法? [英] Passing static JSON to Django Template - best practices?

查看:29
本文介绍了将静态JSON传递给Django模板-最佳做法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个JSON数据文件,该文件是我的应用程序的一部分(受版本控制等),我们的一些模板需要此文件中的数据才能正确呈现.

I have a JSON data file that is part of my application (version controlled, etc.), and several of our templates need the data in this file to render properly.

使此JSON数据可用于模板的各种方式的优缺点是什么?

让我们从一个相当简单的选项开始:将JSON数据存储为模板,要求模板渲染器生成它,将其解析为JSON,然后将其作为模板上下文参数传递给需要它的每个视图:

Let's start with the fairly simple option of storing the JSON data as a template, asking the template renderer to generate it, parsing that as JSON, and passing that as a template context param for each view that needs it:

'mydata': simplejson.loads(render_to_string('data/mydata.json'))

(这似乎在浪费CPU周期,甚至可能浪费磁盘访问.渲染的JSON模板"是否至少会自动缓存?)

(This seems somewhat wasteful of CPU cycles and possibly disk access. Would the rendered JSON "template" at least be cached automatically?)

还有哪些其他选择?我缺少针对这种用例设计的Django内置功能吗?

What are some other options? Is there any built-in feature of Django I'm missing that's designed for this type of use case?

推荐答案

最简单且可能最快的方法是仅在实际视图之外解析views.py中的json:

The simplest and probably fastest thing to do is to just parse the json in your views.py outside of the actual view:

mydata = simplejson.loads(json_file)

def foo(request):
    ...
    return render(request, 'template.html', {"mydata": mydata},
        content_type="application/xhtml+xml")

仅当第一次请求来自views.py文件的视图时,才会解析json,后续请求不会导致再次解析它.您可以按照建议使用上下文处理器.

The json will only be parsed the first time a view from the views.py file is requested, subsequent requests will not cause it to be parsed again. You could alternately use a context processor, as suggested.

这篇关于将静态JSON传递给Django模板-最佳做法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆