Flask Deploy on Heroku - Error R10 - python

I successfully deployed the app and ran the url its shows application error.
Checked the Log, it states:
* Running on http://127.0.0.1:5000/
Web process failed to bind to $PORT within 60 seconds of launch
Procfile
web: python run.py ${PORT}
run.py
from app import app
app.run(debug=False)
I also tried with
from os import environ
from app import app
app.run(debug=False, port=environ.get("PORT", 5000), processes=2)
In both the case the error still persist
views.py
#app.route('/')
#app.route('/login', methods=["GET","POST"])
def login():
....

That's really not how you run a Flask application in production. You need an actual server, such as gunicorn, and you point that to your app object:
web: gunicorn app:app
This is all fully explained in the Heroku tutorial.

Related

serving flask app with waitress and docker

I am serving a flask app with docker but the docker logs command shows that the app is running on a development server. I want to serve this app with waitress.
The project is structured like this below. A docker-compose.yml file to build the image, expose the port and run the manage.py file
docker-compose.yml
web:
build: .
image: web
container_name: web
ports:
- 8080:5000
command: python manage.py run -h 0.0.0.0
manage.py file imports the create_app and provides it into FLaskGroup
from flask.cli import FlaskGroup
from project.server import create_app
app = create_app()
cli = FlaskGroup(create_app=create_app)
if __name__ == "__main__":
cli()
project/server/__init__.py file imports the main_blueprint and registers it.
from project.server.main.views import main_blueprint
from flask import Flask
import os
def create_app(script_info=None):
app = Flask(
__name__,
template_folder="../client/templates",
static_folder="../client/static",
)
app_settings = os.getenv("APP_SETTINGS")
app.config.from_object(app_settings)
app.register_blueprint(main_blueprint)
app.shell_context_processor({"app": app})
return app
project/server/main/views.py
from flask import render_template, Blueprint, jsonify, request
main_blueprint = Blueprint("main", __name__,)
#main_blueprint.route("/", methods=["GET"])
def home():
return render_template("pages/home.html")
#main_blueprint.route("/test", methods=["GET"])
def parse():
return jsonify({"result": "test"}), 202
How can I modify the existing code to serve the flask app with waitress? Thank you.
I got it running by changing the docker-compose.yml file:
command
python manage.py run -h 0.0.0.0 to waitress-serve --call "project.server:create_app"
port
8080:5000 to 8080:8080
docker-compose.yml file looks like below now:
web:
build: .
image: web
container_name: web
ports:
- 8080:8080
command: waitress-serve --call "project.server:create_app"
You run using python manage.py run -h 0.0.0.0, which uses the classic flask run. You should use waitress commands to run your app.
This doc might help you.

Heroku Flask App: Where to place wsgi.py?

Trying to follow best practices for a Flask app running in Heroku so I'm moving things from app.py to working with blueprints.
The current directory structure is as follows:
--root
--application
--admin_blueprint
--another_blueprint
--wsgi.py (app = create_app())
--__init__.py (this has def create_app, which handles creating my app)
--migration
--Procfile
--requirements.txt
--runtime.txt
--config.py
--manage.py
This is init.py
from flask import Flask
...
def create_app():
app = Flask(...)
...
return app
and this is wsgi.py
from application import create_app
app = create_app()
if __name__ == '__main__':
app.run(host='0.0.0.0')
I cannot for the life of me figure out how to do the Procfile correctly, this is what I previously had when I had app.py and wsgi.py in my root directory and it was working fine on Heroku:
web: gunicorn app:wsgi
I've tried some of these:
web: gunicorn application:wsgi
web: gunicorn application.wsgi
web: gunicorn --pythonpath application application:wsgi
web: gunicorn application.wsgi.py
web: gunicorn "application.wsgi.py"
web: gunicorn "application/wsgi.py"
flask run works because I've exported FLASK_APP=application.wsgi.py
Thank you.
Use application.wsgi:app
application.wsgi (the part before the colon) instructs gunicorn how to resolve the module.
and app (the part after the colon) gives the name of the WSGI application declared in the resolved module.
:app can be omitted and gunicorn defaults to looking in the module for a WSGI application with the name application.

Flask at first run: Do not use the development server in a production environment

I installed the Flask plugin in PyCharm Community Edition and I just have this simple code in my flask app:
from flask import Flask
app = Flask(__name__)
#app.route('/')
def index():
return '<h1>Hello!</h1>'
if __name__ == "__main__":
app.run(debug=True)
And I get this message:
WARNING: This is a development server. Do not use it in a production deployment.
Use a production WSGI server instead
* Restarting with stat
* Debugger is active!
* Debugger PIN: 123-456-789
* Running on http://127.0.0.1:5000/
Why am I getting this error when I run Flask?
A previous version of the message read "Do not use the development server in a production environment."
For deploying an application to production, one option is to use Waitress, a production WSGI server.
Here is an example of using waitress in the code.
from flask import Flask
app = Flask(__name__)
#app.route("/")
def index():
return "<h1>Hello!</h1>"
if __name__ == "__main__":
from waitress import serve
serve(app, host="0.0.0.0", port=8080)
Running the application:
$ python hello.py
Waitress also provides a command line utility waitress-serve. To use that, you can modify the code to the following:
from flask import Flask
app = Flask(__name__)
#app.route("/")
def index():
return "<h1>Hello!</h1>"
def create_app():
return app
Then we can use waitress-serve as the following:
waitress-serve --port=8080 --call hello:create_app
And BTW, 8080 is the default port.
To validate the deployment, open a separate window:
% curl localhost:8080
<h1>Hello!</h1>%
Or directly in your browser http://localhost:8080/.
Other alternatives to deploy your app include Gunicorn and uWSGI. For more details, please refer to the flask deploy doc.
As of Flask 2.2, the development server always shows this warning, it is not possible to disable it. The development server is not intended for use in production. It is not designed to be particularly efficient, stable, or secure. Use a production WSGI server instead. See the deployment docs from Flask for more information.
That warning is just a warning though, it's not an error preventing your app from running. If your app isn't working, there's something else wrong with your code.
That warning applies to the development server, not Flask itself. The Flask framework is appropriate for any type of application and deployment.
To avoid these messsages, inside the CLI (Command Line Interface), run these commands.
export FLASK_APP=app.py
export FLASK_ENV=development
export FLASK_DEBUG=0
flask run
If for some people (like me earlier) the above answers don't work, I think the following answer would work (for Mac users I think)
Enter the following commands to do flask run
$ export FLASK_APP=hello.py
$ export FLASK_ENV=development
$ flask run
Alternatively you can do the following (I haven't tried this but one resource online talks about it)
$ export FLASK_APP=hello.py
$ python -m flask run
source: For more
Try gevent:
from flask import Flask
from gevent.pywsgi import WSGIServer
app = Flask(__name__)
#app.route('/api', methods=['GET'])
def index():
return "Hello, World!"
if __name__ == '__main__':
# Debug/Development
# app.run(debug=True, host="0.0.0.0", port="5000")
# Production
http_server = WSGIServer(('', 5000), app)
http_server.serve_forever()
Note: Install gevent using pip install gevent
This worked for me on windows:
$env:FLASK_APP="flask_project.py"
$env:FLASK_ENV="development"
flask run
flask_project.py is on the same path as my virtual environment.

Why heroku fails to find the python/flask module or application?

my heroku app runs into application error with the following logs:
Starting process with command `gunicorn run:app`
Failed to find application: run
here is my Procfile
web: gunicorn run:flask_app
run.py file
from app import create_app, db
from app.auth.models import User
if __name__ == '__main__':
flask_app = create_app('prod')
with flask_app.app_context():
db.create_all()
if not User.query.filter_by(user_name='harry').first():
User.create_user(user='harry', email='harry#potters.com', password='secret')
flask_app.run()
Your main-method does not get executed (AFAIK) because Gunicorn is calling your script, you are not executing it as the main-file. Try moving the flask_app out of your main-method to the top of the file so Gunicorn can actually find it when importing your run.py!

gunicorn Connection in use for python flask

I recently changed my Heroku Python Flask app from the 'small application' format to the 'simple package' format based from flask documentation (De-coupling everything in app.py into separate subdirectories)
The application runs correctly using
> python runserver.py
However, executing
gunicorn runserver:app --log-file=-
outputs:
"Starting gunicorn .... connection in use error" (loops forever)
My runserver.py configuration is:
from re3 import app
app.run(debug=True)
__init__.py configuration:
import os
from flask import Flask
from flask import render_template
app = Flask(__name__)
import views
view.py configuration:
from re3 import app
#app.route('/')
def index():
return 'Hello World!'
What is changing in the two executions?
The problem is that you run your application anytime runserver is imported. You only want that to happen when it's executed directly.
from re3 import app
if __name__ == '__main__':
app.run(debug=True)
Edit:
The usage for gunicorn is
$ gunicorn [OPTIONS] APP_MODULE
When you run gunicorn, it imports APP_MODULE. In your case, you've specified runserver. So while you don't import it yourself, gunicorn does. And before gunicorn can run app, runserver runs it.

Categories

Resources