Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Breakpoints inside Flask-RESTful class methods aren't hit on PTVS

I'm using Python Tools for Visual Studio, and I've set up a project with a virtual environment and installed Flask-RESTful there.

Then, I just copied their hello world example

from flask import Flask
from flask.ext.restful import reqparse, abort, Api, Resource

app = Flask(__name__)
app.debug = True
api = Api(app)

TODOS = {
    'todo1': {'task': 'build an API'},
    'todo2': {'task': '?????'},
    'todo3': {'task': 'profit!'},
}


def abort_if_todo_doesnt_exist(todo_id):
    if todo_id not in TODOS:
        abort(404, message="Todo {} doesn't exist".format(todo_id))

parser = reqparse.RequestParser()
parser.add_argument('task', type=str)


# Todo
#   show a single todo item and lets you delete them
class Todo(Resource):
    def get(self, todo_id):
        abort_if_todo_doesnt_exist(todo_id)
        return TODOS[todo_id]

    def delete(self, todo_id):
        abort_if_todo_doesnt_exist(todo_id)
        del TODOS[todo_id]
        return '', 204

    def put(self, todo_id):
        args = parser.parse_args()
        task = {'task': args['task']}
        TODOS[todo_id] = task
        return task, 201


# TodoList
#   shows a list of all todos, and lets you POST to add new tasks
class TodoList(Resource):
    def get(self):
        return TODOS

    def post(self):
        args = parser.parse_args()
        todo_id = 'todo%d' % (len(TODOS) + 1)
        TODOS[todo_id] = {'task': args['task']}
        return TODOS[todo_id], 201

##
## Actually setup the Api resource routing here
##
api.add_resource(TodoList, '/todos')
api.add_resource(Todo, '/todos/<string:todo_id>')

if __name__ == '__main__':
    app.run(debug=True)

Everything works fine, and if I put breakpoints on the lines that are executed before starting the app.run(debug=True) they're hit (with F10 and F11 working great, and local variables being updated as expected)

However, I'd love to debug what happens when a request is processed, but if I add breakpoints to the methods of the Todo or TodoList classes, they're never hit. I added code (like print('here')) to see if they're being processed and they are... also, they're returning what I expect when opened from a browser.

Is there something I'm missing from the setup?

Thanks!

UPDATE: I found out that if I attach VS to the python.exe process that's running my code, I'm able to debug those methods... so I guess that the question is now: can I force VS to attach to the process once it's launched as it does with regular .NET apps?

like image 823
g3rv4 Avatar asked Dec 07 '22 03:12

g3rv4


1 Answers

I had the same exact problem (but with PyCharm on Mac).

I believe this has something to do with the way Flask reloads itself when debug=True. Setting debug to False allowed me to break inside the view methods.

like image 71
Evan Cordell Avatar answered Dec 28 '22 07:12

Evan Cordell