Reworked ErrorDict.as_json() to prevent unnecessary serialization/deserialization step.

Thanks @apollo13 for the suggestion. Refs #17413.
This commit is contained in:
Loic Bistuer 2014-03-01 01:53:32 +07:00 committed by Florian Apolloner
parent 9b729ddd8f
commit 34236efc5e
1 changed files with 13 additions and 11 deletions

View File

@ -4,6 +4,11 @@ import json
import sys import sys
import warnings import warnings
try:
from collections import UserList
except ImportError: # Python 2
from UserList import UserList
from django.conf import settings from django.conf import settings
from django.utils.html import format_html, format_html_join, escape from django.utils.html import format_html, format_html_join, escape
from django.utils.encoding import force_text, python_2_unicode_compatible from django.utils.encoding import force_text, python_2_unicode_compatible
@ -15,11 +20,6 @@ from django.utils import six
# module to maintain backwards compatibility. # module to maintain backwards compatibility.
from django.core.exceptions import ValidationError from django.core.exceptions import ValidationError
try:
from collections import UserList
except ImportError: # Python 2
from UserList import UserList
def flatatt(attrs): def flatatt(attrs):
""" """
@ -56,8 +56,7 @@ class ErrorDict(dict):
return {f: e.as_data() for f, e in self.items()} return {f: e.as_data() for f, e in self.items()}
def as_json(self, escape_html=False): def as_json(self, escape_html=False):
errors = {f: json.loads(e.as_json(escape_html=escape_html)) for f, e in self.items()} return json.dumps({f: e.get_json_data(escape_html) for f, e in self.items()})
return json.dumps(errors)
def as_ul(self): def as_ul(self):
if not self: if not self:
@ -84,17 +83,20 @@ class ErrorList(UserList, list):
A collection of errors that knows how to display itself in various formats. A collection of errors that knows how to display itself in various formats.
""" """
def as_data(self): def as_data(self):
return self.data return ValidationError(self.data).error_list
def as_json(self, escape_html=False): def get_json_data(self, escape_html=False):
errors = [] errors = []
for error in ValidationError(self.data).error_list: for error in self.as_data():
message = list(error)[0] message = list(error)[0]
errors.append({ errors.append({
'message': escape(message) if escape_html else message, 'message': escape(message) if escape_html else message,
'code': error.code or '', 'code': error.code or '',
}) })
return json.dumps(errors) return errors
def as_json(self, escape_html=False):
return json.dumps(self.get_json_data(escape_html))
def as_ul(self): def as_ul(self):
if not self.data: if not self.data: