如果您使用的是django 1.3,则可以使用基于类的视图来抽象该函数。您只需从基本视图扩展视图,该视图将返回传入的任何json。您可以将该类保存在某个常见位置(如Ignacio评论中链接的答案中所述)。
事实上,这是在documentation for class based views的例子类型之一:
from django import http
from django.utils import simplejson as json
class JSONResponseMixin(object):
def render_to_response(self, context):
"Returns a JSON response containing 'context' as payload"
return self.get_json_response(self.convert_context_to_json(context))
def get_json_response(self, content, **httpresponse_kwargs):
"Construct an `HttpResponse` object."
return http.HttpResponse(content,
content_type='application/json',
**httpresponse_kwargs)
def convert_context_to_json(self, context):
"Convert the context dictionary into a JSON object"
# Note: This is *EXTREMELY* naive; in reality, you'll need
# to do much more complex handling to ensure that arbitrary
# objects -- such as Django model instances or querysets
# -- can be serialized as JSON.
return json.dumps(context)
这是你将如何使用它(也从文档):
class HybridDetailView(JSONResponseMixin,
SingleObjectTemplateResponseMixin, BaseDetailView):
def render_to_response(self, context):
# Look for a 'format=json' GET argument
if self.request.GET.get('format','html') == 'json':
return JSONResponseMixin.render_to_response(self, context)
else:
return SingleObjectTemplateResponseMixin.render_to_response(self, context)
可能的重复[如何在Django应用中包含自定义模块](http://stackoverflow.com/questions/2576060/how-can-i-include-custom-modules-in-a-django-app ) – 2012-03-06 05:42:48