How to run a flask application? - 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

Terminal is showing error when running command "flask db init". Error: No such command 'db' [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

Why does my terminal not recognise pip or any Python modules that is recognised before? [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 Run - ImportError was raised

Starting my Flask app using:
flask run
Doesn't appear to work... and I get the error message:
Error: While importing 'entry', an ImportError was raised.
however if I run:
python entry.py
The app will build successfully? Why is this? Both FLASK_APP and FLASK_ENV are set correctly, here is my folder structure:
entry.py:
from application import create_app
app = create_app()
if __name__ == '__main__':
app.run(host='0.0.0.0', port=8080)
application/init.py:
import os
from flask import Flask
from config import DevConfig, TestConfig, ProdConfig
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
from application.models import Report
def create_app(testing=False):
app = Flask(__name__)
flask_env = os.getenv("FLASK_ENV", None)
# Configure the application, depending on the environment
if testing:
app.config.from_object(TestConfig)
elif flask_env == "development":
app.config.from_object(DevConfig)
elif flask_env == "production":
app.config.from_object(ProdConfig)
else:
raise ValueError("FLASK_ENV is not set or there is an unknown environment type!")
# init plugins, if any
db.init_app(app)
if flask_env == "development":
with app.app_context():
db.create_all()
db.session.commit()
# register blueprints
register_blueprints(app)
return app
def register_blueprints(app):
from application.main import main_blueprint
app.register_blueprint(main_blueprint)
If you want to start the application through the flask executable, then you have to consider that flask will look for the app.py file containing the app application, if not (as in your case), then you will have to correctly set the value of the environment variable FLASK_APP, which will be equal to FLASK_APP=entry.py:app
On Linux, macOS:
$ export FLASK_APP=entry.py:app
$ flask run
On Windows:
$ set FLASK_APP=entry.py:app
$ flask run
Take a look here: Run The Application.
Here, however, it is explained how flask looks for the application to run
In this case (python entry.py) everything works correctly, because flask is invoked via python inside the main section, which instead is not called if entry.py is executed directly from flask, in fact flask will not enter the main section, but will look for the app.py file and the app variable inside it. (Obviously it will look for entry.py and app if you have configured the environment variable correctly)

How to set a help message for a Flask command group?

I'm trying to adapt an example from Flask documentation to create a custom command in a group:
import click
from flask import Flask
from flask.cli import AppGroup
app = Flask(__name__)
user_cli = AppGroup('user')
#user_cli.command('create')
#click.argument('name')
def create_user(name):
...
app.cli.add_command(user_cli)
$ flask user create demo
This appears to work fine, however when I run flask --help I see the commands listed without any help messages, e.g.:
Commands:
user
foo
db Perform database migrations.
How can I add a help message to a group of commands ('user' in this case)?
If you use a Blueprint to create CLI commands, add blueprint_obj.cli.short_help for top-level help:
bp_database = Blueprint('bp_database', __name__, cli_group='database')
bp_database.cli.short_help = 'Database utilities'
Output:
Commands:
database Database utilities
run Run a development server.
shell Run a shell in the app context.
Use the short_help parameter. AppGroup inherits from Group which inherits from MultiCommand which inherits from Command. See Click source code for Command.
For example:
import click
from flask import Flask
from flask.cli import AppGroup
user_cli = AppGroup('user', short_help="Adds a user")
#user_cli.command('create')
#click.argument('name')
def create_user(name):
print(name)
app = Flask(__name__)
app.cli.add_command(user_cli)
#app.route('/')
def hello_world():
return 'Hello World!'
if __name__ == '__main__':
app.run()
Gives the following output (Windows PyCharm terminal):
(flask_cli_group) D:\Paul\PycharmProjects\flask_cli_group>flask
Usage: flask [OPTIONS] COMMAND [ARGS]...
A general utility script for Flask applications.
Provides commands from Flask, extensions, and the application. Loads the
application defined in the FLASK_APP environment variable, or from a
wsgi.py file. Setting the FLASK_ENV environment variable to 'development'
will enable debug mode.
> set FLASK_APP=hello.py
> set FLASK_ENV=development
> flask run
Options:
--version Show the flask version
--help Show this message and exit.
Commands:
routes Show the routes for the app.
run Run a development server.
shell Run a shell in the app context.
user Adds a user
(flask_cli_group) D:\Paul\PycharmProjects\flask_cli_group>

'flask run' or 'python run' which to use?

Reading http://flask.pocoo.org/docs/1.0/quickstart/ describes using 'flask run' to start flask based app.
I've been using python run.py myconfig.conf as there does not appear to be an option to set config file 'myconfig.conf' as part of flask startup.
my run code :
if __name__ == '__main__':
app.config.from_pyfile(sys.argv[1]))
app.run(host='0.0.0.0', port=app.config["PORT"])
Can see myconfig.conf is registered with sys.argv[1]
Should I use flask mechanism instead of python for executing flask server ? If so how to pass myconfig.conf to main method ?
As using :
flask run myconfig.py
returns error :
Usage: flask run [OPTIONS]
Error: Got unexpected extra argument (myconfig.py)
You can use flasks custom commands (http://flask.pocoo.org/docs/1.0/cli/#custom-commands) which will help you to define your own flask command line options. There you can set app.config.from_pyfile(confige_file). Then run flask run to execute flask server.
#app.cli.command()
#click.argument('config_file')
def set_config(config_file):
app.config.from_pyfile(confige_file)
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/
from the above link itself. you have to set FLASK_APP environmet variable to your script

Categories