Commits

Matthew Schinckel committed ebe3954

Handle client connections with incorrect content-type set.

  • Participants
  • Parent commits 1edb8c7

Comments (0)

Files changed (1)

rest_api/serializers/__init__.py

     'application/x-www-form-urlencoded': 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[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()
     
+    # 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)
+        return serializer.deserialize(raw_post_data)
+        
     content_type = request.META.get('CONTENT_TYPE')
     if content_type and ";" in content_type:
         content_type = content_type.split(';')[0]
     
     if serializer == post:
         if len(request.POST):
-            return post.deserialize(request.POST)
-        return post.deserialize(QueryDict(request.raw_post_data))
+            return serializer.deserialize(request.POST)
+        return serializer.deserialize(QueryDict(request.raw_post_data))
     
     if request.method in ["POST", "PUT"]:
         raw_post_data = request.raw_post_data
         
         if raw_post_data:
-            for (search, replace) in INVALID_CHARS:
-                raw_post_data = raw_post_data.replace(search, replace)
+            raw_post_data = remove_invalid_chars(raw_post_data)
             
             if serializer:
                 return serializer.deserialize(raw_post_data)
-            elif raw_post_data[0] == "<":
-                return xml.deserialize(raw_post_data)
-            elif raw_post_data[0] in ["[", "{"]:
-                return json.deserialize(raw_post_data)