Debug with Flask / Python

0

I'm studying the Flask framework. It happens that I need debugar a request object with form data. I also need to stop at a certain point, like die() in PHP.

How do I do this? I've already tried to os.exit(1) , but the Flask server stops automatically.

Note: in PHP it would be

debug(object);  
die();
    
asked by anonymous 17.03.2018 / 22:11

2 answers

2

In Flask, to access the request information it is only necessary to import the default object request which is automatically populated in all requests of your application. But for this you need to be in the context of a request, like in a view, for example.

The data in a form is stored inside the form property of request , with the exception of the files, which are assigned to the files property

Example of accessing form data

from flask import Flask, request, jsonify

app = Flask(__name__)

@app.route('/')
def hello_world():
   # Print dos campos e valores passados pelo formulário
   print(request.form)

   # retorna os dados do formulário em formato JSON
   return jsonify(request.form)

Python has the pdb package for debugging in its default library. To add the breakpoint just type: import pdb; pdb.set_trace() . The execution will stop at the line where you defined this command.

Although the pdb package is sufficient for many cases, it is common to use the ipdb package for debugging, for account of some improvements and facilities that it offers due to integration with iPython, such as syntax highligh, auto-complete, better traceback, etc.

To install ipdb : pip install ipdb

Using ipdb to debug the Flask form

from flask import Flask, request, jsonify

app = Flask(__name__)

@app.route('/')
def hello_world():
   # Print dos campos e valores passados pelo formulário
   print(request.form)

   # Execução da aplicação irá parar nesse ponto
   # Aqui você tem acesso a todas as váriaveis definidas no escopo.
   # É possível acessar, caso exista, o campo 'nome' passado pelo formulário, por meio da linha de comando
   # >>> request.form['nome']
   import ipdb; ipdb.set_trace()

   # retorna os dados do formulário em formato JSON
   return jsonify(request.form)
    
19.03.2018 / 14:55
-1

maybe like this:

print(object)
return
    
18.03.2018 / 15:59