Search code examples
pythondebuggingflaskwerkzeug

Posting JSON and python Flask - any techniques to use the Werkzeug debugger?


Alright, I'm working with a RESTful backend on my project, and submitting data via jquery.

I must say the werkzeug debugger is excellent for debugging specially when you're a terrible python programmer as me. You throw an exception on purpose where you want to investigate, and inspect the code and variables using the html the debugger rendered.

However when you send a post request instead of a get, if you throw an exception on the backend code, of course, the browser won't render the response text.

Is there any technique I can use to render the response text, considering it has javascript and everything?

I'm trying different things such as trying to inject the response text into a popup window, like:

           $.postJSON = function(url, data, callback, error_callback) {
                return jQuery.ajax({
                    'type': 'POST',
                    'url': url,
                    'contentType': 'application/json',
                    'data': JSON.stringify(data),
                    'dataType': 'json',
                    'success': callback,
                    'error': error_callback
                });
            };

            $.postJSON('/the_uri', {'foo': 'bar'}, 
            function(response) {
                var a = 0;
            }, 
            function(response) {
                var html = response.responseText;
                var my_window = window.open('', 'mywindow1', 'width=350,height=150');
                $(my_window.document).find('html').html(html);
            });
        });

But this won't take care of the javascript very well.

Does anyone have any suggestion?


Solution

  • Your approach was nearly correct. I am using the following code to open the response text in a new window (not specific to Werkzeug or Flask at all):

    var w = window.open('', 'debug_stuff', 'width=540,height=150');
    w.document.open();
    w.document.write(response.responseText);
    w.document.close();
    

    The last line is the most important. Without it, the code would behave as yours -- it would not execute any JavaScript, because the browser doesn't know the DOM has been fully loaded.