Debug with Flask/Python

Asked

Viewed 286 times

-1

I’m studying the Flask framework. I happen to need thresh an object request with form data. I also need to stop at a certain point, like the die() in PHP.

How do I do that? I’ve tried os.exit(1), but the Flask server automatically stops.

Note: in PHP it would be

debug(object);  
die();

2 answers

3

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

Data from a form is stored within the property form of request, with the exception of files, which are assigned to the property files

Example of access to 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 in its standard library the package pdb for debug. To add breakpoint just type: import pdb; pdb.set_trace(). The execution will stop at the line where you set this command.

Despite the package pdb be sufficient for many cases, it is common to use the package ipdb for debug, on account of some improvements and facilities it provides due to the integration with ipython, such as: highligh syntax, auto-complete, better traceback, etc.

To install the ipdb: pip install ipdb

Using ipdb for Flask form debug

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)

-1

perhaps so:

print(object)
return
  • i did as per your reply and put a testo in Return just to test, but in the browser appears the return text, but no debug appears. print() should print something in the python console, but since the answer is in the browser, I don’t know if print() has an output somewhere, which I don’t think.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.