Flask App - Local Development Environment - changes not reflecting - python

I have a Flask App that I am running locally and testing. Every time, I make a change in the Application code, the changes would reflect on the dev environment http://127.0.0.1:8000/ with a simple browser refresh.
Now, I have to terminate the Flask App Ctrl X + Ctrl C and then reboot / relaunch the App. I am using gunicorn to launch the Flask App.
Not sure what changed, but how do I configure the App such that the changes take effect on refresh?
I have the following line of code in init.py:
if __name__ == '__main__':
run_simple('0.0.0.0', 80, app, use_reloader=True, use_debugger=True)

Gunicorn has its own system to reload the worker process when the application code changes. You can use the --reload CLI flag to activate the auto-reloading dev mode.
gunicorn --reload app:app
You can add additional files to the watcher via the --reload-extra-file FILES arg.

Try
if __name__ == '__main__':
app.run(debug=True)
Also using Gunicorn
web: gunicorn wsgi:app

Related

Flask - Ports are not updating automatically even when debug=True [duplicate]

I want to change the host and port that my app runs on. I set host and port in app.run, but the flask run command still runs on the default 127.0.0.1:8000. How can I change the host and port that the flask command uses?
if __name__ == '__main__':
app.run(host='0.0.0.0', port=3000)
set FLASK_APP=onlinegame
set FLASK_DEBUG=true
python -m flask run
The flask command is separate from the flask.run method. It doesn't see the app or its configuration. To change the host and port, pass them as options to the command.
flask run -h localhost -p 3000
Pass --help for the full list of options.
Setting the SERVER_NAME config will not affect the command either, as the command can't see the app's config.
Never expose the dev server to the outside (such as binding to 0.0.0.0). Use a production WSGI server such as uWSGI or Gunicorn.
gunicorn -w 2 -b 0.0.0.0:3000 myapp:app
from flask import Flask
app = Flask(__name__)
#app.route("/")
def hello():
return "Hello World!"
if __name__ == '__main__':
app.run(host="localhost", port=8000, debug=True)
Configure host and port like this in the script and run it with
python app.py
You can also use the environment variable FLASK_RUN_PORT, for instance:
export FLASK_RUN_PORT=8000
flask run
* Running on http://127.0.0.1:8000/
Source: The Flask docs.
When you run the application server using the flask run command, the __name__ of the module is not "__main__". So the if block in your code is not executed -- hence the server is not getting bound to 0.0.0.0, as you expect.
For using this command, you can bind a custom host using the --host flag.
flask run --host=0.0.0.0
Source
You can use this 2 environmental variables:
set FLASK_RUN_HOST=0.0.0.0
set FLASK_RUN_PORT=3000
You also can use it:
if __name__ == "__main__":
app.run(host='127.0.0.1', port=5002)
and then in the terminal run this
set FLASK_ENV=development
python app.py

Running Flask by "flask run" vs running from editor (Windows 10)

If I run my Flask app through the command "flask run", not only the arguments in app.run are ignored (making debugger false and choosing the default port 5000), but changes made to the script too, e.g. changing url_prefix to "/views". The cmd prompt won't even respond when I save the script after making alterations. This way, changes are only effective after stopping the script then running again.
This doesn't happen when the app script is ran through VSCode commands (Ctrl+F5 or the play button): through those, the script is executed as written and changes are recognized right after saving a script.
Why is that so?
from flask import Flask
from views import views
app = Flask(__name__)
app.register_blueprint(views, url_prefix="/")
if __name__ == '__main__':
app.run(debug=True, port=8000)
C:\Users\*******\Documents\flask_quick_website>flask run
* 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)
The flask executable works by importing the app object from your code. This is similar to how a WSGI server like gunicorn works (research what this is if you're unsure).
As for when you run the script with VSCode, or in-fact if you launch with the python executable by running python app.py or similar, then anything inside the if __name__ == '__main__': block is executed, in your case the app.run call.
Also note your app.run call is passed the debug=True argument. If you investigate the Flask source code, inside the run function, the use_reloader argument is set to the same value as debug so in this case the auto-reloader runs if debug is True.
So how to make the auto-reloader work with the flask command? Pass the --reload flag:
flask run --reload
You can also set the environment to development to achieve the same. On windows:
> set FLASK_ENV=development
> flask run
See Environment and Debug features for more on this.

Flask auto-reload functionality not working with Pycharm Remote Deployment

It's hard to remember when, but at one point the auto-reload function of Flask started to not work anymore in my project.
This is the output upon starting my app :
FLASK_APP = back/python/app/app.py:app
FLASK_ENV = development
FLASK_DEBUG = 1
In folder C:/path/to/project
ssh://[VirtualMachineIP]:22/root/env/bin/python3.7 -u -m flask run -h 0.0.0.0 -p 1234
* Serving Flask app 'back/python/app/app.py:app' (lazy loading)
* Environment: development
* Debug mode: on
* Running on all addresses.
WARNING: This is a development server. Do not use it in a production deployment.
* Running on http://[VirtualMachineIP]:1234/ (Press CTRL+C to quit)
* Restarting with stat
* Debugger is active!
* Debugger PIN: 106-048-128
The development environment and Debug mode are both on. Thus, upon saving changes in a file (while the app is deployed) I get the usual message :
* Detected change in '/path/to/changed/file.py', reloading
Signaling that the app is reloading with the new code. Except it doesn't reload anything, and the message doesn't appear on any further changes until I'm forced to restart the app.
PyCharms runs on Windows and communicates via ssh to my Virtual Machine, where the code is executed. I have installed the following modules:
flask
flask-socketio
eventlet
flask-cors
Any help is welcomed. Thanks :)
The FLASK_DEBUG environment variable is badly supported, it may not behave as expected if set in code. (Quoted from the source of flask).
It suggest to use flask run in debug mode.
eg: $ flask --app hello --debug run
If it still not work, you can force to use reloader like this:
if __name__ == '__main__':
app.run(host=config.HOST, port=config.PORT, debug=True)
Take care, the app.run() must be wrapped with if __name__ == '__main__'.
doc: https://flask.palletsprojects.com/en/2.2.x/config/#DEBUG

Multiple flask applications served by a single gunicon server

I have a service, which contains 2 Flask-applications - let's name them app and monitoring_app running on different ports. monitoring_app is an utility service which provides metrics collected with prometheus_client. I have faced up with an issue trying run them under the Gunicorn server properly.
I have read through the similar topic:
Multiple Flask Application in single uwsgi
but it seems my problem can't be solved with Dispatcher Middleware.
I can start these applications without Gunicorn like this:
from threading import Thread
import os
from my_project import create_app, create_monitoring_app
def start_app(my_app):
my_app.run(host="localhost",
debug=True,
port=int(os.environ.get("API_PORT", "5000")),
threaded=True,
use_reloader=False)
if __name__ == "__main__":
app = create_app()
app_thread = Thread(target=start_app, daemon=True, args=(app,))
app_thread.start()
monitoring_app = create_monitoring_app()
monitoring_app.run(host="localhost",
port=int(os.environ.get("OPS_PORT", "5001")),
threaded=True,
use_reloader=False,
debug=True)
It works ok for development, but it runs under Flask development server which is not ok for production environment. With Gunicorn I can start them separately:
gunicorn "my_project:create_monitoring_app()" -b "[::]:$OPS_PORT" &
gunicorn "my_project:create_app()" -b "[::]:$API_PORT"
but then they will be in different interpreters and I can't use prometheus_client of app in monitoring_app what is critical for me
What can I do to achieve same behavior as if I run these applications from my development environment? Or may be I am doing something wrong and I should do it in another way?

Warning message while running Flask

While I am running Flask code from my command line, a warning is appearing:
Serving Flask app "hello_flask" (lazy loading)
* Environment: production
WARNING: Do not use the development server in a production environment.
Use a production WSGI server instead.
What does this mean?
As stated in the Flask documentation:
While lightweight and easy to use, Flask’s built-in server is not suitable for production as it doesn’t scale well and by default serves only one request at a time.
Given that a web application is expected to handle multiple concurrent requests from multiple users, Flask is warning you that the development server will not do this (by default). It recommends using a Web Server Gateway Interface (WSGI) server (numerous possibilities are listed in the deployment docs with further instructions for each) that will function as your web/application server and call Flask as it serves requests.
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
As of Flask 1.x, the default environment is set to production.
To use the development environment, create a file called .flaskenv and save it in the top-level (root) of your project directory. Set the FLASK_ENV=development in the .flaskenv file. You can also save the FLASK_APP=myapp.py.
Example:
myproject/.flaskenv:
FLASK_APP=myapp.py
FLASK_ENV=development
Then you just execute this on the command line:
flask run
That should take care of the warning.
To remove the "Do not use the development server in a production environment." warning, run:
export FLASK_ENV=development
before flask run.
I was typing flask run and then saw this message after that I solve this issue with these:
1- Add this text in your myproject/.flaskenv :
FLASK_APP=myapp.py
FLASK_ENV=development
also you should type "pip3 install python-dotenv" for using this file .flaskenv
2-in your project folder type in terminal your flask command which one you use :
flask-3 run
First, try to the following :
set FLASK_ENV=development
then run your app.
I have been using flask for quite some time now, and today, suddenly this warning turned up. I found this.
As mentioned here, as of flask version 1.0 the environment in which a flask app runs is by default set to production. If you run your app in an older flask version, you won't be seeing this warning.
New in version 1.0.
Changelog
The environment in which the Flask app runs is set by the FLASK_ENV environment variable. If not set it defaults to production. The other recognized environment is development. Flask and extensions may choose to enable behaviors based on the environment.
in configurations or config you can add this code :
ENV = ""
same as if you try to add debug set to true like this
DEBUG = True
for more detail you can check this http://flask.pocoo.org/docs/1.0/config/#ENV
It means the programe is run on production mode even in developing environment.so to avoid that warning, you need to define this is development environment.for that,Type and run below command in project directory on terminal(linux).
export FLASK_ENV=development
if you are windows user then run,
set FLASK_ENV=development
To disable the message I use:
app.env = "development"
You have to put this in the Python-Script before you run the app with:
app.run(host="localhost")
If you encounter NoAppException and you see lazy loading the following seemed to fix the issue:
cd <project directory>
export FLASK_APP=.
export FLASK_ENV=development
export FLASK_DEBUG=1
You can begin your main script like this :
import os
if __name__ == '__main__':
os.environ.setdefault('FLASK_ENV', 'development')

Categories

Resources