user1590420
user1590420

Reputation: 291

Debug python flask application in vim

Does anybody debug flask application in vim using this one for example. What I want: I want to set break point in controller method for example

def login():
(breakpoint)>> some code
...
...

Somehow run flask app and when I send for example login form stop on this breakpoint and debug source code.

Thanks.

Upvotes: 2

Views: 2044

Answers (2)

Walter
Walter

Reputation: 7981

Below is the relevant parts of my setup that allows me to press F7 on a line and get a pdb.set_trace() line inserted. Shift+F7 removes it again. The debugging itself happens outside of vim (on the command-line where the program is executed), but has never let me down.

This implementation requires the brilliant ipdb, but should be easy enough to modify if/as necessary.

~/.vim/ftplugin/python/python.vim:

...
map <S-F7> :py RemoveBreakpoints()<CR>
map <F7> :py SetBreakpoint()<CR>
...

~/.vim/ftplugin/python/custom.py:

...
def SetBreakpoint():
    nLine = int( vim.eval('line(".")') )

    strLine = vim.current.line
    strWhite = re.search('^(\s*)', strLine).group(1)

    vim.current.buffer.append(
        (
            "%(space)spdb.set_trace() %(mark)s Breakpoint %(mark)s" %
            {'space': strWhite, 'mark': '#' * 30}
        ),
        nLine - 1
    )

    for strLine in vim.current.buffer:
        if strLine == "import ipdb as pdb":
            break
    else:
        vim.current.buffer.append('import ipdb as pdb', 2)
        vim.command('normal j1')
    vim.command('write')

def RemoveBreakpoints():
    nCurrentLine = int( vim.eval('line(".")') )

    nLines = []
    nLine = 1
    for strLine in vim.current.buffer:
        if strLine == 'import ipdb as pdb' or strLine.lstrip().startswith('pdb.set_trace()'):
            nLines.append(nLine)
        nLine += 1

    nLines.reverse()

    for nLine in nLines:
        vim.command('normal %dG' % nLine)
        vim.command('normal dd')
        if nLine < nCurrentLine:
            nCurrentLine -= 1

    vim.command('normal %dG' % nCurrentLine)
    vim.command('write')
...

Upvotes: 3

davekr
davekr

Reputation: 2276

Do you know about Python debbuger? You can set breakpoints anywhere in your code using this line:

import pdb; pdb.set_trace()

If you're using vim, you might like this shortcut as well:

:ia pdb import pdb; pdb.set_trace()<ESC>

Upvotes: 3

Related Questions