Commits

Matthew Schinckel committed 9da1fdc

Added logging middleware.
Added better handling of audit [who] fields.

Comments (0)

Files changed (2)

rest_api/middleware.py

                     request.real_user, request.user, request.META['REMOTE_ADDR']
                 ))
 
+class SerializationMiddleware(object):
+    """
+    """
+    def process_request(self, request):
+        """
+        Deserialize raw_post_data according to Content-Type
+        """
+        if request.META.get('HTTP_CONTENT_TYPE', False):
+            request.data = serializers.get(request.META.get('HTTP_CONTENT_TYPE')).deserialize(request.raw_post_data)
+    
+    def process_response(self, request, response):
+        """
+        Serialize attached objects into the HTTP Response
+        """
+        pass
+
 class HttpContentLoggingMiddleware(object):
     """
     Log all request and response data.
     
     def process_request(self, request):
         self._start_time = datetime.datetime.now()
-        if request.raw_post_data:
-            logging.log(logging.DEBUG - 1, request.raw_post_data)
+        # if request.raw_post_data:
+        # logging.log(logging.DEBUG - 1, request.raw_post_data)
     
     def process_response(self, request, response):
         time_spent = datetime.datetime.now() - self._start_time
             '-',
             (datetime.datetime.now() + datetime.timedelta(hours=9.5)).strftime("%d/%b/%Y %H:%M:%S"),
             request.method,
-            request.path,
+            request.get_full_path(),
             "HTTP/1.1",
             response.status_code,
             len(response.content) or '-',
             time_spent.microseconds / 1000000.0,
         ))
-        logging.log(logging.DEBUG - 1, "\n%s" % response.content)
+        # import pdb; pdb.set_trace()
+        if int(response.status_code) > 404:
+            logging.debug("Request: \n%s" % request.raw_post_data)
+            # logging.debug("Response: \n%s" % response.content)
         return response
     
     def process_exception(self, request, exception):
         import traceback
         output = "%s %s" % (request.method, request.path)
+        # output += "\n%s" % request.META.get('USER_AGENT'),
         output += "\nUser: %s" % request.user
         output += "\nPOST DATA:\n%s\n" % request.raw_post_data
         output += traceback.format_exc()
             instance = self.model(**incoming)
             try:
                 # If there are audit fields, then update the values.
-                if hasattr(instance, 'created_by'):
-                    instance.created_by = request.user
-                if hasattr(instance, 'updated_by'):
-                    instance.updated_by = request.user
+                instance.created_by = request.user
+                instance.updated_by = request.user
                 instance.save()
                 # Examine related fields, as we will need to create
                 # new models, potentially with relations to other models.
         objects = self.model.objects.filter(pk__in=created)
         for obj in objects:
             self.log_addition(request, obj)
-        return http.Created(objects)
+        if len(objects):
+            return http.Created(objects)
+        return http.OK("Nothing created.")
 
     
     def update(self, request, pk):
                 # ignore the passed in value(s)
                 if getattr(field, 'auto_now', False) or getattr(field, 'auto_now_add', False):
                     continue
-                # If this was an audit field, set it if necessary.
-                if field.name == 'updated_by':
-                    instance.updated_by = request.user
-                    continue
-                if field.name == 'created_by':
+                # If this was an audit field, ignore it. We set these according to the user who ran the request.
+                if field.name == 'updated_by' or field.name == 'created_by':
                     continue
                 if field.value_from_object(instance) != field.to_python(value):
                     # Do I need to serialize this?
                     except AttributeError:
                         # Could not set this attribute: read-only?
                         pass
+        
+        instance.updated_by = request.user
         try:
             instance.save()
         except IntegrityError: