The flask host adress in docker run - python

I want to run a flask application in Docker, with the flask simple http server. (Not gunicorn)
I got a host setting problem.
In the flask app.py, it should be work as the official tutorial, but it doesn't work:
if __name__ == '__main__':
app.run(host='0.0.0.0')
So I did it after an answer of a similar post, it suddenly works!:
https://stackoverflow.com/a/43015007/3279996
$> flask run --host=0.0.0.0
My question is why this first method doesn't work, but second works?

In the first solution, when you run the code with the python3 app.py command, it runs on 0.0.0.0 on the host.
But the flask run command executes the flask app directly from the code and does not include the condition if name == 'main':.
On the other hand, when you run the code with python3 app.py, name equals 'main'. But when you run the code with flask run, name is equal to the FLASK_APP variable that becomes an app in your code, and the FLASK_APP variable must be the same as the file name that flask app contains.
app.py
print("__name__ is :", __name__)
python3 app.py
__name__ is : __main__
app.py
$> export FLASK_APP=app.py
$> flask run
...
__name__ is : 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

Env. Variables do not set FLASK_APP - Windows Error [duplicate]

I want to know the correct way to start a flask application. The docs show two different commands:
$ flask -a sample run
and
$ python3.4 sample.py
produce the same result and run the application correctly.
What is the difference between the two and which should be used to run a Flask application?
The flask command is a CLI for interacting with Flask apps. The docs describe how to use CLI commands and add custom commands. The flask run command is the preferred way to start the development server.
Never use this command to deploy publicly, use a production WSGI server such as Gunicorn, uWSGI, Waitress, or mod_wsgi.
As of Flask 2.2, use the --app option to point the command at your app. It can point to an import name or file name. It will automatically detect an app instance or an app factory called create_app. Use the --debug option to run in debug mode with the debugger and reloader.
$ flask --app sample --debug run
Prior to Flask 2.2, the FLASK_APP and FLASK_ENV=development environment variables were used instead. FLASK_APP and FLASK_DEBUG=1 can still be used in place of the CLI options above.
$ export FLASK_APP=sample
$ export FLASK_ENV=development
$ flask run
On Windows CMD, use set instead of export.
> set FLASK_APP=sample
For PowerShell, use $env:.
> $env:FLASK_APP = "sample"
The python sample.py command runs a Python file and sets __name__ == "__main__". If the main block calls app.run(), it will run the development server. If you use an app factory, you could also instantiate an app instance at this point.
if __name__ == "__main__":
app = create_app()
app.run(debug=True)
Both these commands ultimately start the Werkzeug development server, which as the name implies starts a simple HTTP server that should only be used during development. You should prefer using the flask run command over the app.run().
Latest documentation has the following example assuming you want to run hello.py(using .py file extension is optional):
Unix, Linux, macOS, etc.:
$ export FLASK_APP=hello
$ flask run
Windows:
> set FLASK_APP=hello
> flask run
you just need to run this command
python app.py
(app.py is your desire flask file)
but make sure your .py file has the following flask settings(related to port and host)
from flask import Flask, request
from flask_restful import Resource, Api
import sys
import os
app = Flask(__name__)
api = Api(app)
port = 5100
if sys.argv.__len__() > 1:
port = sys.argv[1]
print("Api running on port : {} ".format(port))
class topic_tags(Resource):
def get(self):
return {'hello': 'world world'}
api.add_resource(topic_tags, '/')
if __name__ == '__main__':
app.run(host="0.0.0.0", port=port)
The very simples automatic way without exporting anything is using python app.py see the example here
from flask import (
Flask,
jsonify
)
# Function that create the app
def create_app(test_config=None ):
# create and configure the app
app = Flask(__name__)
# Simple route
#app.route('/')
def hello_world():
return jsonify({
"status": "success",
"message": "Hello World!"
})
return app # do not forget to return the app
APP = create_app()
if __name__ == '__main__':
# APP.run(host='0.0.0.0', port=5000, debug=True)
APP.run(debug=True)
For Linux/Unix/MacOS :-
export FLASK_APP = sample.py
flask run
For Windows :-
python sample.py
OR
set FLASK_APP = sample.py
flask run
You can also run a flask application this way while being explicit about activating the DEBUG mode.
FLASK_APP=app.py FLASK_DEBUG=true flask run

Flask not activating debug mode

I am getting started with flask, I am trying to follow some tutorials, but I have been unable to run Flask app in debug mode.
I tried the simplest code I found:
from flask import Flask
app = Flask(__name__)
app.debug = True
# I have also tried with a configuration
# app.config.from_object('config')
# file with constant
# DEBUG = True
#app.route('/')
def hello_world():
return 'Hello World!'
Then I run
export FLASK_APP=hello_world.py
flask run
But I allways get this output
* Serving Flask app "hello_world.py"
* 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)
When I run print(app.debug) I get False
This is the output of pip freeze:
click==7.1.2
Flask==1.1.2
itsdangerous==1.1.0
Jinja2==2.11.2
MarkupSafe==1.1.1
Werkzeug==1.0.1
And I have python 3.8.2
I have tried the below steps and it worked for me.
Have added these lines of codes to my app.py file.
if __name__ == "__main__":
app.run(debug=True)
Then I ran the program from the Terminal using the command line
python3 app.py
and it worked.
Please find the below screenshot
if you are using windows just type the following in your terminal :
in PowerShell:
$env:FLASK_ENV = "development"
flask run
in command prompt :
C:\path\to\app>set FLASK_ENV=development
flask run
and for mac you probably need to run this :
$ export FLASK_ENV=development
$ flask run
enjoy !!
Try This:
When you run,
export FLASK_APP=hello_world.py
Run this command after the above,
export FLASK_DEBUG=1
Finally,
flask run
I hope this would start the debug mode.
Make sure that you're running the right program, sometimes it happens
that we're making changes in some other program and running something
else.
Also ensure that Setting app.debug = True is altogether a
different thing from setting FLASK_DEBUG mode to on.
Try this, this works at my end.
from flask import Flask
app = Flask(__name__)
#app.route('/')
def hello_world():
return 'Hello World!'
if __name__ == "__main__":
app.run(debug=True)
There are two way to run Flask App.
Environment Variable
Programmatically
Environment Variable you need to exporting the FLASK_APP file using command for window set FLASK_APP = *(file_name)*.
set FLASK_APP = app.py`
And for mac
export FLASK_ENV=development
You can also control debug mode separately from the environment by exporting FLASK_DEBUG=1. (set command for mac and export for window)
set FLASK_APP = app.py
set FLASK_DEBUG=1
But sometimes debugger does not work on production servers. It is a major security risk to be used on production machines.
Programmatically you have to include main section on your Flask app.py main file. It will run your app in debug mode easily but do not use flask run command use only python (file_name) command.
from flask import Flask
app = Flask(__name__)
app.debug = True
#app.route('/')
def hello_world():
return 'Hello World!'
if __name__ == '__main__':
app.run(debug=True)
python app.py
Apparently, because debug mode is already off, stopping and rerunning it didn't work.
add the line below to app.py and save.
if __name__ == "__main__":
app.run(debug=True)
restart the editor.
then run
set FLASK_DEBUG=1
then run your project
python3 app.py

flask.cli.NoAppException: The file/path provided (new_app.py) does not appear to exist

I keep getting this error flask.cli.NoAppException: The file/path provided (new_app.py) does not appear to exist. Please verify the path is correct. If app is not on PYTHONPATH, ensure the extension is .py it goes away after I restart the Flask server.
I am running flask run in the correct directory where my app is. This just started happening after working for 2 weeks. I've read that it could be due to an import error, but I am not finding any modules that are not installed on my virutalenv.
from flask import Flask
app = Flask(__name__)
app.debug=True
Most likely you haven't set the FLASK_APP environment variable.
To run the application you can either use the flask command or
python’s -m switch with Flask. Before you can do that you need to tell
your terminal the application to work with by exporting the FLASK_APP
environment variable:
$ export FLASK_APP=hello.py
$ flask run * Running on http://127.0.0.1:5000/
If you are on Windows you need to use set
instead of export.
Alternatively you can use python -m flask:
$ export FLASK_APP=hello.py
$ python -m flask run * Running on http://127.0.0.1:5000/
EDIT
If you have FLASK_APP set then try adding this to new_app.py
app.run(debug=True, port=8800)
Or if you're on Windows:
if __name__ == '__main__':
app.run(debug=True, port=8800)
And then just execute the app with python new_app.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