Set break points in Tornado app

2019-05-18 04:16发布

问题:

How could I set a break point in my tornado app?
I tried pdb, but Tornado app seams to be ignoring my pdb.set_trace() command in my app.

回答1:

If you are running your app using foreman you would set you environment variable in .env file in root project folder. Setting the below env variable in my .env file did the tick form me.

PYTHONUNBUFFERED=true

Now I can set code breakpoints in my app, and also print output to server logs while running the app using foreman.



回答2:

Where did you put pdb.set_trace()...? This works for me:

#!/usr/bin/python
# -*- coding: utf-8 -*-

import tornado.httpserver
import tornado.ioloop
import tornado.options
import tornado.web
import pdb 

from tornado.options import define, options
define("port", default=8000, help="run on the given port", type=int)

class IndexHandler(tornado.web.RequestHandler):
    def get(self):
        greeting = self.get_argument('greeting', 'Hello')
        reself.write(greeting + ', friendly user!')

if __name__ == "__main__":
    tornado.options.parse_command_line()
    app = tornado.web.Application(handlers=[(r"/", IndexHandler)])
    http_server = tornado.httpserver.HTTPServer(app)
    http_server.listen(options.port)
    pdb.set_trace()
    tornado.ioloop.IOLoop.instance().start()

Session:

$ python test.py
> /home/mariusz/Dokumenty/Projekty/Testy/test.py(24)<module>()
-> tornado.ioloop.IOLoop.instance().start()
(Pdb) break 16
Breakpoint 1 at /home/mariusz/Dokumenty/Projekty/Testy/test.py:16
(Pdb) continue
> /home/mariusz/Dokumenty/Projekty/Testy/test.py(16)get()
-> self.write(greeting + ', friendly user!')
(Pdb) step
--Call--
> /usr/local/lib/python2.7/dist-packages/tornado/web.py(497)write()
-> def write(self, chunk):
(Pdb) step
> /usr/local/lib/python2.7/dist-packages/tornado/web.py(512)write()
-> if self._finished:
(Pdb) step
> /usr/local/lib/python2.7/dist-packages/tornado/web.py(516)write()
-> if isinstance(chunk, dict):
(Pdb) 

After putting continue in above code debugger stopped, because I had to poll http://localhost:8000/ in browser to have RequestHandler function actually called.