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
Related
After reading following docs and examples about deploying python app to evennode I've tried to do it with Flask application, but didn't succeed
https://www.evennode.com/docs/git-deployment
https://github.com/evennode/python-getting-started
Here is my main.py module's code:
from flask import Flask
app = Flask(__name__)
#app.route("/")
def hello():
return "Hello, World!"
if __name__ == "__main__":
app.run(host='0.0.0.0', port=8000)
Also I'have created conf.py file with configuration for gunicorn:
workers = 4
bind = "0.0.0.0:8000"
Then I'm running the application with gunicorn --config=conf.py main:app and all works well on my local machine. To run it on evennode I populated requirements.txt and committed above files. Then run following commands:
git remote add evennode git#git.evennode.com:your_app_here
git push evennode master
The output looks next way and I don't know what to do with it:
ssh: connect to host git.evennode.com port 8000: No route to host
fatal: Could not read from remote repository.
Please make sure you have the correct access rights
and the repository exists.
I have added my public ssh key to evennode app settings as well, so that's can't be an issue
Any help is appreciated
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
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
...
I'm running Ubuntu using Virtual Box Manager from windows machine. Inside the VM box ubuntu i'm running a python flask application which is running at http://localhost:5000.
I tried to access the VM box localhost URL on windows machine using the VM box IP which I got using ifconfig. But it's says :
Your Internet access is blocked
Am i accessing it the right way ?
here is my python flask code :
from flask import Flask
app = Flask(__name__)
#app.route("/")
def hello():
return "Hello World!"
if __name__ == "__main__":
app.run()
You need to specify a host='0.0.0.0' while starting your app. By default it will only accept requests from localhost. So if you are sending a request from some other IP then you must have to specify a host.
See below example.
from flask import Flask
app = Flask(__name__)
#app.route("/")
def hello():
return "Hello World!"
if __name__ == "__main__":
app.run(host='0.0.0.0')
Also if you want to activate the debugging mode to analyse the exceptions/errors while you access your application. You can also set debug attribute to 'True'.
if __name__ == "__main__":
app.run(host='0.0.0.0', debug=True)
Below code will allow you to access Flask web from any public IP instead of 127.0.0.1
if __name__ == '__main__':
app.run(host='0.0.0.0', debug='TRUE')
By default Flask runs on port: 5000. Sometime on VM this port will be blocked. To allow traffic on this port execute below command.
iptables -I INPUT -p tcp --dport 5000 -j ACCEPT
user manager.py runserver my flask webframework can start on http://127.0.0.1:5000 but it can not access on other computer in network.
so i need use an open IP in network.
although i use bellow command:
manage.py runserver 192.168.49.25:8000
it can not run and give a error info:
manage.py: error: unrecognized arguments: 192.168.49.25:8000
I don't known what's wrong with it??
If you want to use Flask-Script (python manage.py runserver) to run your Flask Application you can use the parameter --host to run it on a public IP.
python manage.py runserver --host 0.0.0.0
see also: https://flask-runner.readthedocs.org/en/latest/
Read the documentation:
Externally Visible Server If you run the server you will notice that
the server is only accessible from your own computer, not from any
other in the network. This is the default because in debugging mode a
user of the application can execute arbitrary Python code on your
computer.
If you have debug disabled or trust the users on your network, you can
make the server publicly available simply by changing the call of the
run() method to look like this:
app.run(host='0.0.0.0') This tells your operating system to listen on
all public IPs.
If you're already using Flask-Script then you have a way to get your host defined in your code.
from yourapp import create_app
from flask_script import Manager, Server
from yourapp import config
app = create_app(config.DevelopmentConfig)
manager = Manager(app)
manager.add_command("runserver", Server(host=app.config['HOST'], port=app.config['PORT']))
if __name__ == '__main__':
manager.run()
now the server host and port will come from config