Debugging flask with pdb


Question

I'm trying to use pdb to debug flask application. Setting break point is easy; I just use b index to break when index() is invoked or b 44 to set a break point at line 44.

Breakpoint works with b 44 which is the start of the main, but b index doesn't work. In the command line, "Index is called" is printed to indicate that the method is invoked, but it does not stop in the pdb.

@app.route('/', methods=['GET', 'POST'])
def index():
    print "Index is called"
    name = None
    ...
    return render_template('index.html', form=form, name=name)

if __name__ == '__main__':
    manager.run() # line 44

What might be wrong?

1
11
11/8/2014 12:08:42 AM

Accepted Answer

You can do this at the line where you want execution to break:

import pdb; pdb.set_trace()

Just make sure you delete it before you commit :).

19
11/8/2014 12:37:28 AM

I'm trying to use pdb to debug flask application. Setting break point is easy; I just use b index to break when index() is invoked or b 44 to set a break point at line 44.

Yes, that's fine.

Breakpoint works with b 44 which is the start of the main, but b index doesn't work. In the command line, "Index is called" is printed to indicate that the method is invoked, but it does not stop in the pdb.

The "problem" here is that you are telling the debugger to break at the start of the function called main() but that's not the function you think it is, you'll see, what is really going on is that the decorator is replacing your main() function with some other function (flask's route handler) so when you do b index you are telling the debugger to stop on the first line of the function pointed by main, which is in flask's code.

Try setting b index1 in this example:

def deco(fn):
    def _wrapper():
        print "Deco called"
        return fn()
    return _wrapper

@deco
def index1():
    print "Index is called"
    return "hi stranger!"

salva = index1

if __name__ == '__main__':
    import pdb; pdb.set_trace()
    index1()

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon