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

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

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

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

How to include command when executing python entry-point command in AWS Elasticbeanstalk?

I am deploying my flask application in AWS Elasticbeanstalk and I want to add a command for running datadog tracing when executing entry-point command. How can I do that?
This is the entry-point command to start my flask app in local machine:
python3 application.py
This is how to add a command before that entry-point command (using datadog as example):
ddtrace-run python3 application.py
How to do the same in AWS elasticbeanstalk? Seems like beanstalk is using apache + mod_wsgi to run python-flask application but I am not sure how to add a command before the entry-point command.
You can run datadog tracing on AWS Elastic Beanstalk with Flask by configure tracing manually as defined here:
from ddtrace import patch_all
patch_all()
from flask import Flask
app = Flask(__name__)
#app.route('/')
def index():
return 'hello world'
if __name__ == '__main__':
app.run()

The flask host adress in docker run

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
...

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.

Categories

Resources