Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to debug Django request "POST /url/ HTTP/1.1" 400

I am using django + django-rest-framework

I am sending POST request from ios app to the python server locally and got 400 error code. I got that the problem is in the json body that I send and I want to output somewhere the full POST request but I have no luck.

[13/Jan/2016 22:48:45] "POST /url/ HTTP/1.1" 400 75

I don't understand how to print anything after I runserver (the simplest way). Is it even possible?

I've tried to enable logging in the settings but also had no luck.

LOGGING = {
    'version': 1,
    'handlers': {
        'console':{
            'level':'DEBUG',
            'class':'logging.StreamHandler',
        },
    },
    'loggers': {
        'django.request': {
            'handlers':['console'],
            'propagate': True,
            'level':'DEBUG',
        }
    },
}

import logging.config
logging.config.dictConfig(LOGGING)

I also installed django debug toolbar but it also doesn't show requests that I send. Also I've tried to return HttpResponse but still hadn't got POST request data.

What is the way to output somewhere requests data (console, file or anything else) in the django or django-rest-framework?

FIXED:

I've added Middleware in views.py that extends my console output like this:

class ExceptionLoggingMiddleware(object):
def process_request(self, request):
    print request.body
    print request.scheme
    print request.method
    print request.META
    return None

and don't forget to add this Middleware to your settings file like this

MIDDLEWARE_CLASSES = [
'movie.views.ExceptionLoggingMiddleware']

Also as I understand LOGGING that I've created through the settings file worked but it was outputting not a large amount of info, just some sql warnings.

like image 941
Roberto Avatar asked Jan 14 '16 14:01

Roberto


People also ask

What is request method == post in Django?

The result of request. method == "POST" is a boolean value - True if the current request from a user was performed using the HTTP "POST" method, of False otherwise (usually that means HTTP "GET", but there are also other methods).

What is request post return Django?

When a page is requested, Django creates an HttpRequest object that contains metadata about the request. Then Django loads the appropriate view, passing the HttpRequest as the first argument to the view function. Each view is responsible for returning an HttpResponse object.


2 Answers

The quick'n'dirty way of doing this is adding debugging to the entry point of the request handler. In In DjangoRestFramework classes, as well as in Django class based views this entry point is the dispatch() method.

You can do something like:

class MyView(View):
    def dispatch(self, request, *args, **kwargs):
        import pdb; pdb.set_trace() # or print debug statements
        super(MyView, self).dispatch(request, *args, **kwargs)
like image 98
Andrei Avram Avatar answered Oct 27 '22 11:10

Andrei Avram


This was my solution, inspired by this blog post on error handling in django rest framework (https://commitcode.com/custom-error-handler-in-django-rest-framework)

Personally, I use Sentry (https://sentry.com) to capture my exceptions. But you can follow the logic and put in anything you want.

First, I create a custom exception handler which I then wire-up using Django Rest Framework's settings.

settings.py

REST_FRAMEWORK = {
    ..settings...
    'EXCEPTION_HANDLER': 'myapp.exception_handler_400.custom_exception_handler'
}

Next, I created the file which will handle the actual exception. It simply fires any existing logic, then checks if the error was 400. If so, then it fires the exception up to Sentry.

myapp.exception_handler_400

from rest_framework.views import exception_handler
from raven.contrib.django.raven_compat.models import client

def custom_exception_handler(exc, context):
    # Call REST framework's default exception handler first,
    # to get the standard error response.
    response = exception_handler(exc, context)

    if response is not None:

        if response.status_code == 400:
            client.captureException()

    return response
like image 35
Sam Texas Avatar answered Oct 27 '22 10:10

Sam Texas