Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to print from Flask @app.route to python console

Tags:

python

flask

I would like to simply print a "hello world" to the python console after /button is called by the user.

This is my naive approach:

@app.route('/button/') def button_clicked():     print 'Hello world!'     return redirect('/') 

Background: I would like to execute other python commands from flask (not shell). "print" should be the easiest case. I believe I have not understood a basic twist here. Thanks in advance!

like image 232
Robert Filter Avatar asked Sep 13 '15 14:09

Robert Filter


People also ask

How do I use the Flask route app?

Step to run the application: Run the application using the following command. Output: Open the browser and visit 127.0. 0.1:5000/post/13, you will see the following output. The add_url_rule() function – The URL mapping can also be done using the add_url_rule() function.


2 Answers

An easy way to do this is by printing to stderr. You can do that like this:

from __future__ import print_function # In python 2.7 import sys  @app.route('/button/') def button_clicked():     print('Hello world!', file=sys.stderr)     return redirect('/') 

Flask will display things printed to stderr in the console. For other ways of printing to stderr, see this stackoverflow post

like image 88
Gabe Avatar answered Sep 30 '22 13:09

Gabe


We can also use logging to print data on the console.

Example:

import logging from flask import Flask  app = Flask(__name__)  @app.route('/print') def printMsg():     app.logger.warning('testing warning log')     app.logger.error('testing error log')     app.logger.info('testing info log')     return "Check your console"  if __name__ == '__main__':     app.run(debug=True) 
like image 45
Viraj Wadate Avatar answered Sep 30 '22 14:09

Viraj Wadate