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

前端 未结 4 2058
无人及你
无人及你 2021-01-30 06:14

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         


        
相关标签:
4条回答
  • 2021-01-30 06:36

    It seems like you have it worked out, but for others looking for this answer, 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

    0 讨论(0)
  • 2021-01-30 06:45

    I think the core issue with Flask is that stdout gets buffered. I was able to print with print('Hi', flush=True). You can also disable buffering by setting the PYTHONUNBUFFERED environment variable (to any non-empty string).

    0 讨论(0)
  • 2021-01-30 06:46

    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)
    
    0 讨论(0)
  • 2021-01-30 06:57

    I tried running @Viraj Wadate's code, but couldn't get the output from app.logger.info on the console.

    To get INFO, WARNING, and ERROR messages in the console, the dictConfig object can be used to create logging configuration for all logs (source):

    from logging.config import dictConfig
    from flask import Flask
    
    
    dictConfig({
        'version': 1,
        'formatters': {'default': {
            'format': '[%(asctime)s] %(levelname)s in %(module)s: %(message)s',
        }},
        'handlers': {'wsgi': {
            'class': 'logging.StreamHandler',
            'stream': 'ext://flask.logging.wsgi_errors_stream',
            'formatter': 'default'
        }},
        'root': {
            'level': 'INFO',
            'handlers': ['wsgi']
        }
    })
    
    
    app = Flask(__name__)
    
    @app.route('/')
    def index():
        return "Hello from Flask's test environment"
    
    @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)
    
    
    0 讨论(0)
提交回复
热议问题