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.
Related
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.
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
Hey I ran the flask basic code as follows -
from flask import Flask
app = Flask(__name__)
#app.route('/')
def hello_world():
return 'Hello, World!'
Then I ran the server as stated in docs and it ran fine.
But now when i got 127.0.0.1:5000/ nothing happens. The browser keeps circling as if refreshing the page but doesn't route.
Its my first python/flask code so I am not sure what I am doing wrong.
EDIT- By docs I mean quickstart documentation of flask. I know its fine cz i get this -
Serving Flask app "hello"
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
Just added app.run() to the same code and executed which is working fine. Can you try it?
from flask import Flask
app = Flask(__name__)
#app.route('/')
def hello_world():
return 'Hello, World!'
app.run()
I'm assuming that you're using this Quickstart - A Minimal Application.
That said let's make some points clear:
When you said
I know its fine cz i get this - Serving Flask app "hello"
You do not use the extension .py, which can cause some problems if you have another file with the same name in this directory. So make sure your FLASK_APP variable is correct.
This should work for you, but if the problem persist enable the Debug Mode adding
FLASK_ENV=development to your environment variable and see which error appears for you.
Hoping this solve your problem.
I'm using flask app factory pattern like and have this helloworld.py file
from flask import Flask
app = Flask(__name__)
#app.route('/')
def index():
return 'This is the home page'
if __name__=="__name__":
app.run(debug=True)
Then I run the app in Terminal :
python helloworld.py
(venv) C:\Users\Jayalakshmi.S1\myproject>python helloworld.py
(venv) C:\Users\Jayalakshmi.S1\myproject>
But when I go to http://localhost:5000 it doesn't work. It says:
Can’t reach this page
Make sure the web address http://127.0.0.1:5000 is correct
What could be wrong?
The problem is that you wrote if __name__=="__name__": instead of if __name__=="__main__":.
Since that will never be true, your app.run never happens. That's why when you run the script, it just returns immediately, instead of printing out something like * Running on http://127.0.0.1:5000/ and then waiting.
You also almost always want to run Flask this way:
set FLASK_APP=helloworld.py
flask run
… instead of:
python helloworld.py
Your if condition is wrong. You should mention the main module which you're running...
if __name__=="__main__":
app.run(debug=True)
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.