I'm running a Flask app in Cloud9. Whenever I start my Flask app, it says this message:
* Serving Flask app "app" (lazy loading)
* Environment: production
WARNING: This is a development server. Do not use it in a production deployment.
Use a production WSGI server instead.
* Debug mode: off
* Running on http://0.0.0.0:80/ (Press CTRL+C to quit)
Is there a way to change this message? I'd like it to say something like this:
Connect to me at http://0.0.0.0:80/!
I've searched stack overflow and the web but couldn't find anything. I'm starting my app with app.run().
Also, is it possible to make the URL cyan?
You can change everything besides Running on http://0.0.0.0:80/ (Press CTRL+C to quit) by changing show_server_banner of flask.cli:
from flask import Flask
import sys
cli = sys.modules['flask.cli']
# put your own message here
cli.show_server_banner = lambda *x: click.echo("My nice message")
app = Flask(__name__)
app.run(host='0.0.0.0', port='80')
To get rid of the Running on http://0.0.0.0:80/ ... message, you can use unittest.mock:
from unittest import mock
from werkzeug._internal import _log
def my_startup_log(*args):
# log all messages except for the * Running on message
if not args[1].startswith(" * Running on"):
return _log(*args)
app = Flask(__name__)
with mock.patch('werkzeug.serving._log') as mocked:
# patch the logger object and replace with own logger
mocked.side_effect = my_startup_logger
app.run(host='0.0.0.0', port='8000')
This is very hacky and depends on the internal implementation of flask. Be careful when using this in production code, as this could easily break.
Related
I used Flask command in my program for first time. Following was the bit of code I wrote:
from flask import Flask,jsonify, request
app = Flask(__name__)
#app.route("/")
def hello_world():
return "Hello World!"
if (__name__ == "__main__"):
app.run(debug=True)
This code was written by me in IDLE Shell 3.8-32 bit and the output should had come in a web browser. But it didn't came. I just got the following output from IDLE:
* Serving Flask app "sa" (lazy loading)
* Environment: production
WARNING: This is a development server. Do not use it in a production deployment.
Use a production WSGI server instead.
* Debug mode: on
* Restarting with stat
app.run(host=0.0.0.0, port=5000, debug=True)
You can change your port number to your convenience.
I have a small application built using Flask and Flask-restx. I can run the app using python app.py and the flask server runs on port 8888. I try to run the file using set FLASK_APP=app.py and run using flask run which seems to run, but doesnt open my swagger page. Please advice.
app.py
import logging.config
import os
from flask import Flask, Blueprint
from flask_cors import CORS
from werkzeug.middleware.proxy_fix import ProxyFix
from src.config import default
from src.api.controllers.endpoints.users import ns as users_namespace
from src.api.controllers.endpoints.statuses import ns as status_namespace
from src.api import api
from src.database import db
app = Flask(__name__)
CORS(app)
app.wsgi_app = ProxyFix(app.wsgi_app)
logging_conf_path = os.path.normpath(os.path.join(os.path.dirname(__file__), '../logging.conf'))
logging.config.fileConfig(logging_conf_path)
log = logging.getLogger(__name__)
def configure_app(flask_app):
flask_app.config['SERVER_NAME'] = default.FLASK_SERVER_NAME
flask_app.config['SQLALCHEMY_DATABASE_URI'] = default.SQLALCHEMY_DATABASE_URI
flask_app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = default.SQLALCHEMY_TRACK_MODIFICATIONS
flask_app.config['SWAGGER_UI_DOC_EXPANSION'] = default.RESTPLUS_SWAGGER_UI_DOC_EXPANSION
flask_app.config['RESTPLUS_VALIDATE'] = default.RESTPLUS_VALIDATE
flask_app.config['RESTPLUS_MASK_SWAGGER'] = default.RESTPLUS_MASK_SWAGGER
flask_app.config['ERROR_404_HELP'] = default.RESTPLUS_ERROR_404_HELP
def initialize_app(flask_app):
configure_app(flask_app)
blueprint = Blueprint('CovidAPI', __name__, url_prefix='/')
api.init_app(blueprint)
api.add_namespace(users_namespace)
api.add_namespace(status_namespace)
flask_app.register_blueprint(blueprint)
db.init_app(flask_app)
def main():
initialize_app(app)
log.info('>>>>> Starting development server at http://{}/ <<<<<'.format(app.config['SERVER_NAME']))
app.run(debug=default.FLASK_DEBUG)
if __name__ == "__main__":
main()
Flask Settings:
# Flask settings
FLASK_SERVER_NAME = 'localhost:8888'
FLASK_DEBUG = True # Do not use debug mode in production
# Flask-Restplus settings
RESTPLUS_SWAGGER_UI_DOC_EXPANSION = 'list'
RESTPLUS_VALIDATE = True
RESTPLUS_MASK_SWAGGER = False
RESTPLUS_ERROR_404_HELP = False
Output using python command:
2020-04-29 10:25:42,519 - __main__ - INFO - >>>>> Starting development server at http://localhost:8888/ <<<<<
* Serving Flask app "app" (lazy loading)
* Environment: production
WARNING: This is a development server. Do not use it in a production deployment.
Use a production WSGI server instead.
* Debug mode: on
2020-04-29 10:25:42,610 - werkzeug - INFO - * Restarting with stat
2020-04-29 10:25:45,398 - __main__ - INFO - >>>>> Starting development server at http://localhost:8888/ <<<<<
2020-04-29 10:25:45,426 - werkzeug - WARNING - * Debugger is active!
2020-04-29 10:25:45,458 - werkzeug - INFO - * Debugger PIN: 258-749-652
2020-04-29 10:25:45,530 - werkzeug - INFO - * Running on http://localhost:8888/ (Press CTRL+C to quit)
Running through flask run:
* Serving Flask app "src\app.py" (lazy loading)
* Environment: production
WARNING: This is a development server. Do not use it in a production deployment.
Use a production WSGI server instead.
* Debug mode: on
* Restarting with stat
* Debugger is active!
* Debugger PIN: 313-115-045
* Running on http://localhost:6000/ (Press CTRL+C to quit)
The flask run command works by importing an app object from your app.py module.
Therefor the stuff in this function is never executed in that case:
def main():
initialize_app(app)
log.info('>>>>> Starting development server at http://{}/ <<<<<'.format(app.config['SERVER_NAME']))
app.run(debug=default.FLASK_DEBUG)
When running with the python app.py command it is, because this gets executed:
if __name__ == "__main__":
main()
I'm not sure how it runs fully in your case with python, as neither the configure_app or initialize_app functions return the app object. However, you may wish to change the code to something like:
# ...
def configure_app(flask_app):
# ...
return flask_app
def initialize_app(flask_app):
# ...
return flask_app
app = initialize_app(app)
Now that (fully configured) app object is avaialable to flask run. You shouldn't need to set the FLASK_ENV environment variable, as it looks for an object called app by default.
If you still want the ability to run with the interpreter, then add this block to the end, although this is kinda defunct if using the flask command.
if __name__ == "__main__":
log.info('>>>>> Starting development server at http://{}/ <<<<<'.format(app.config['SERVER_NAME']))
app.run(debug=default.FLASK_DEBUG)
The issue should be reproducible with the following two minimal examples:
Minimal example with app.run()
from flask import Flask
app = Flask(__name__)
#app.route('/')
def hello():
return 'Hello'
app.run()
Minimal example with gevent.pywsgi.WSGIServer
from flask import Flask
app = Flask(__name__)
#app.route('/')
def hello():
return 'Hello'
from gevent import pywsgi
from geventwebsocket.handler import WebSocketHandler
server = pywsgi.WSGIServer(('127.0.0.1', 5000), app, handler_class=WebSocketHandler)
server.serve_forever()
The first 5 lines are identical, so both examples only differ in the way they start the server. Both servers do work, I get "Hello" in the browser. The first example prints:
* Serving Flask app "1" (lazy loading)
* Environment: production
WARNING: This is a development server. Do not use it in a production deployment.
Use a production WSGI server instead.
* Debug mode: off
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
127.0.0.1 - - [20/Jun/2019 23:43:15] "GET / HTTP/1.1" 200 -
127.0.0.1 - - [20/Jun/2019 23:43:19] "GET / HTTP/1.1" 200 -
So the console output shows some information about every request which is handled by the server.
However, with the second example, I don't get any logging output in the console anymore. How do I enable logging for gevent.pywsgi.WSGIServer and WebSocketHandler?
Background (which doesn't matter regarding the issue, I think)
I'm running a Flask app which uses flask_sockets. Because
Werkzeug development server cannot provide the WSGI environ with a websocket interface
I am not able to use the server with app.run() and I'm using gevent.pywsgi.WSGIServer instead. The code of my example above is taken directly from the module's examples at https://github.com/heroku-python/flask-sockets without any modifications.
Logging works differently with gevent.pywsgi.WSGIServer. It uses python logging and is much more sophisticated and flexible.
Here's an example:
from gevent import pywsgi
from geventwebsocket.handler import WebSocketHandler
import logging
logging.basicConfig(level=logging.INFO)
server = pywsgi.WSGIServer(('127.0.0.1', 5000), app, handler_class=WebSocketHandler)
server.serve_forever()
And now wherever you want output, you can do:
logging.info("You can see me now...")
If you want to see startup info from WSGIServer, then set the log level to DEBUG and you can see tons of output.
It should work like that, but it's a bug in WebSocketHandler from the geventwebsocket module which has already been reported: https://gitlab.com/noppo/gevent-websocket/issues/16
I ran the following Flask app and tried to post to /, but I got a 404 response. The / route is defined, why doesn't it get handled?
from flask import Flask, request
app = Flask(__name__)
app.run()
#app.route('/', methods=['POST'])
def handle_post_request():
return str(request.form)
C:\Python35\python.exe D:/Dropbox/dev/contact.py
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
127.0.0.1 - - [03/Apr/2017 20:46:01] "POST / HTTP/1.1" 404 -
Calling app.run blocks, no code is executed after it until the server is stopped. Make sure your app is completely set up before calling run. In this case, move the route definition above the call to run.
Flask 0.11 introduced a more robust way to start applications to avoid this and other common mistakes. Completely remove app.run(). Set the FLASK_APP environment variable to your app's entry point, and call flask run.
FLASK_APP=contact.py flask run
You can also set FLASK_DEBUG=1 to enable debug mode.
In Windows, use set FLASK_APP=contact.py to set environment variables instead.
I have below setup in my Python application
server.py
from bots.flask_app import app
from bots.flask_app.api import api
from bots.flask_app.public import public
from bots import db
from bots.commons.helpers.flask.json.serializer import make_alternative_encoder
from flask_debugtoolbar import DebugToolbarExtension
import logging
import bots.commons.managers.configuration as ConfigurationManager
logger = logging.getLogger()
#######
# Public functions
#######
def setup_db_and_app():
# Flask application bootstrap
config = ConfigurationManager.get_flask_rest_config()
app.config.update(config)
logger.debug('Flask configuration object: %s', app.config)
# MongoDB connection initialization
db.init_app(app)
# Debug toolbar enabled only if Flask in debug mode
if ConfigurationManager.get_raw_flask_rest_config()['flask']['debug']:
DebugToolbarExtension(app)
# Replace the serializer with the custom one (for ObjectId and DateTime serialization)
app.json_encoder = make_alternative_encoder(app.json_encoder)
# Register the components
app.register_blueprint(api)
app.register_blueprint(public)
def start_server():
setup_db_and_app()
logger.debug('Registered routes: %s', app.url_map)
app.run(host='0.0.0.0')
main.py
import bots.flask_app.server as FlaskApp
import bots.commons.managers.log as LogManager
# Logging initialization
LogManager.init_logging()
# Defined in server.py
FlaskApp.start_server()
I am trying to see whether this applicator can bed served by uwsgi as below
uwsgi --socket 0.0.0.0:8080 --protocol=http -w main
The output is as follows
INFO:werkzeug: * Running on http://0.0.0.0:5000/ (Press CTRL+C to quit)
INFO:werkzeug: * Restarting with stat
unable to load configuration from uwsgi
My questions
1. Where can I find the configurations which are causing this issue?
2. Can main.py be defined as a callable and used as a parameter for -w?
This is an app which is already written by someone and I am trying make this application served through uwsgi.
Any suggestions would be helpful
Thanks
I had the 'unable to load configuration from uwsgi' error too. According to flask uwsgi docs:
Please make sure in advance that any app.run() calls you might have in your application file are inside an if __name__ == '__main__': block or moved to a separate file. Just make sure it’s not called because this will always start a local WSGI server which we do not want if we deploy that application to uWSGI.
I move app.run() to if __name__ == '__main__':, and the problem solved. Maybe you can try to put FlaskApp.start_server() under if __name__ == '__main__':.
I'm a bit late to the party, I've encountered this error when I forgot to remove debug=True from app.run(). It makes sense that you can't run the debug server with uwsgi.