我有一个Django视图,在执行某些自定义逻辑之前,我希望重用而不是复制和粘贴加载和验证的内容。
我正在评估三种使这个视图可重用的方法:
你会推荐什么?为什么?
我提供了以下视图的一个片段:
try:
data = json.loads(request.body)
except:
resp = generate_json_response(False, 'validation', 'JSON data cannot be parsed. Please check your data format.')
return HttpResponse(resp, mimetype="application/json")
# Validation
location = data.get('location', None)
if location:
{custom logic}
else:
# No Location
resp = generate_json_response(False, 'validation', 'Missing location id')
return HttpResponse(resp, mimetype="application/json")
resp = generate_json_response(True, None, None)
return HttpResponse(json.dumps(resp), mimetype="application/json")发布于 2013-06-21 01:10:32
您是否考虑将基于类的泛型视图与混合器一起使用?就像这样:
class JSONResponseMixin(object):
def render_to_response(self, context):
return self.get_json_response(json.dumps(context))
def get_json_response(self, content, **httpresponse_kwargs):
return http.HttpResponse(content,
content_type='application/json',
**httpresponse_kwargs)
class MyView(JSONResponseMixin, SomeView(BaseDetail, BaseUpdate etc..)):
pass也许为您的目的使用一些json实现会更好。看一看:
http://json-rpc.org/
http://www.jsonrpc.org/specification
http://en.wikipedia.org/wiki/JSON-RPC#Implementations
https://stackoverflow.com/questions/17224169
复制相似问题