Source

django-rest-api / rest_api / serializers / __init__.py

The default branch has multiple heads

from django.http import QueryDict

import json, xml, post

serializers = {
    'json': json,
    'xml': xml,
    None: json
}

INVALID_CHARS = (
    ('\x96', '-'),
    ('\x97', '--'),
    ('\x91', "'"),
    ('\x92', "'"),
    ("\x93", '\\"'),
    ("\x94", '\\"'),
    ("\xa0", ' '),      # Non-breaking space, I think
)

def serialize(queryset, format=None, **kwargs):
    return serializers.get(format).serialize(queryset, **kwargs)

deserializers = {
    'application/json': json,
    'application/xml': xml,
    'application/x-www-form-urlencoded': post,
    'multipart/form-data': post,
}

def remove_invalid_chars(data):
    for (search, replace) in INVALID_CHARS:
        data = data.replace(search, replace)
    return data

def inspect_content(data):
    if data:
        if data[0] == "<":
            return xml
        if data[0] in ["[", "{"]:
            return json
    return None
    
def deserialize(request):
    # Need to do this before accessing raw_post_data!
    request._load_post_and_files()
    
    content_type = request.META.get('CONTENT_TYPE')
    if content_type and ";" in content_type:
        content_type = content_type.split(';')[0]
    serializer = deserializers.get(content_type, None)
    
    if serializer == post:
        try:
            inspected = inspect_content(request.raw_post_data)
            if inspected:
                return inspected
        except:
            pass
        if len(request.POST):
            return serializer.deserialize(request.POST)
        return serializer.deserialize(QueryDict(request.raw_post_data))
    
    if not serializer:
        # Inspect the data, in case the headers are incorrect.
        serializer = inspect_content(request.raw_post_data)
    if serializer:
        raw_post_data = remove_invalid_chars(request.raw_post_data)
        if len(raw_post_data):
            return serializer.deserialize(raw_post_data)
    
    if request.method in ["POST", "PUT"]:
        raw_post_data = request.raw_post_data
        
        if raw_post_data:
            raw_post_data = remove_invalid_chars(raw_post_data)
            
            if serializer:
                return serializer.deserialize(raw_post_data)