I'm trying to run a simple web server on a Raspberry Pi with Flask. When I run my Flask app, it says:
running on http://127.0.0.1:5000/
But when I enter this address on my laptop's in Chrome, I get
ERR_CONNECTION_REFUSED
I can open 127.0.0.1:5000 on the Raspberry Pi's browser. What do I need to do to connect from another computer?
Run your app like this:
if __name__ == '__main__':
app.run(host='0.0.0.0')
It will make the server externally visible. If the IP address of the machine is 192.168.X.X then, from the same network you can access it in 5000 port. Like, http://192.168.X.X:5000
when you are running the server via flask run change it to flask run --host=0.0.0.0
to connect, find the IPV4 address of the server that your script is running on. On the same network, go to http://[IPV4 address]:5000
A reason could also be in firewall refusing incoming connections on port 5000. Try:
sudo ufw allow 5000
app.run(host='0.0.0.0',port=5000)
if you run your app in this way then your server will be visible externally.
Steps by Setp:
Run your app by using the following command
app.run(host='0.0.0.0',port=5000)
Go to the window cmd . Type ipconfig and get the get the IPV4 adress suppose your IPV4 address is 192.168.X.X
Go to the mobile browser and type the 192.168.X.X:5000
If you have debug = True inside your app.run(), then it will not be visible to other machines either. Specify host and port inside app.run() without the debug = True.
You will have to run the development server such that it listens to requests on all interfaces and not just the local one
Ask Flask to listen on 0.0.0.0:PORT_NUMBER
or any other port you may choose
On MacOS 12.4 (Monterey) I couldn't load localhost nor my local IP but it worked with both of these:
0.0.0.0
127.0.0.1
Just change the URL in the browser if it loads with "localhost".
Both devices must be connected to same network.
Use app.run(host='0.0.0.0',port=5000) and run with your own Ipv4
address like his http://[Your Ipv4 address]:5000
If you are connecting this with android app then don't forget to
put INTERNET permission in manifest file.
Contrary to popular believe 127.0.0.1 is not the same a localhost.
I solved the issue above by setting 127.0.0.1 explicitly on both ends.
Well i was also here to know answer but i guess i found out problem. The reason is that you may not activated or run flask that's why it is showing error. For that you have to start from terminal "flask run" and then surely your flask will run...
The issue may occur, if VPN is on, so try to switch it off.
Related
I'm not sure if this is Flask specific, but when I run an app in dev mode (http://localhost:5000), I cannot access it from other machines on the network (with http://[dev-host-ip]:5000). With Rails in dev mode, for example, it works fine. I couldn't find any docs regarding the Flask dev server configuration. Any idea what should be configured to enable this?
While this is possible, you should not use the Flask dev server in production. The Flask dev server is not designed to be particularly secure, stable, or efficient. See the docs on deploying for correct solutions.
The --host option to flask run, or the host parameter to app.run(), controls what address the development server listens to. By default it runs on localhost, change it to flask run --host=0.0.0.0 (or app.run(host="0.0.0.0")) to run on all your machine's IP addresses.
0.0.0.0 is a special value that you can't use in the browser directly, you'll need to navigate to the actual IP address of the machine on the network. You may also need to adjust your firewall to allow external access to the port.
The Flask quickstart docs explain this in the "Externally Visible Server" section:
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 the debugger disabled or trust the users on your network,
you can make the server publicly available simply by adding
--host=0.0.0.0 to the command line:
$ flask run --host=0.0.0.0
This tells your operating system to listen on all public IPs.
If you use the flask executable to start your server, use flask run --host=0.0.0.0 to change the default from 127.0.0.1 and open it up to non-local connections.
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 the debugger disabled or trust the users on your network,
you can make the server publicly available simply by adding
--host=0.0.0.0 to the command line:
$ flask run --host=0.0.0.0
This tells your operating system to listen on all public IPs.
Reference: https://flask.palletsprojects.com/quickstart/
Try this if the 0.0.0.0 method doesn't work
Boring Stuff
I personally battled a lot to get my app accessible to other devices(laptops and mobile phones) through a local-server. I tried the 0.0.0.0 method, but no luck. Then I tried changing the port, but it just didn't work. So, after trying a bunch of different combinations, I arrived to this one, and it solved my problem of deploying my app on a local server.
Steps
Get the local IPv4 address of your computer.
This can be done by typing ipconfig on Windows and ifconfig on Linux
and Mac.
Please note: The above step is to be performed on the machine you are serving the app on, and on not the machine on which you are accessing it. Also note, that the IPv4 address might change if you disconnect and reconnect to the network.
Now, simply run the flask app with the acquired IPv4 address.
flask run -h 192.168.X.X
E.g. In my case (see the image), I ran it as:
flask run -h 192.168.1.100
On my mobile device
Optional Stuff
If you are performing this procedure on Windows and using Power Shell as the CLI, and you still aren't able to access the website, try a CTRL + C command in the shell that's running the app. Power Shell gets frozen up sometimes and it needs a pinch to revive. Doing this might even terminate the server, but it sometimes does the trick.
That's it. Give a thumbs up if you found this helpful.😉
Some more optional stuff
I have created a short Powershell script that will get you your IP address whenever you need one:
$env:getIp = ipconfig
if ($env:getIp -match '(IPv4[\sa-zA-Z.]+:\s[0-9.]+)') {
if ($matches[1] -match '([^a-z\s][\d]+[.\d]+)'){
$ipv4 = $matches[1]
}
}
echo $ipv4
Save it to a file with .ps1 extension (for PowerShell), and run it on before starting your app. You can save it in your project folder and run it as:
.\getIP.ps1; flask run -h $ipv4
Note: I saved the above shellcode in getIP.ps1.
Cool.👌
Add host='0.0.0.0' to app.run`.
if __name__ == '__main__':
app.run(host='0.0.0.0', port=5000)
If you get OSError: [WinError 10013] An attempt was made to access a socket in a way forbidden by its access permissions on Windows, you either don't have permission to use the port, or something else is using it which you can find with netstat -na|findstr 5000.
Check whether the particular port is open on the server to serve the client or not?
in Ubuntu or Linux distro
sudo ufw enable
sudo ufw allow 5000/tcp //allow the server to handle the request on port 5000
Configure the application to handle remote requests
app.run(host='0.0.0.0' , port=5000)
python3 app.py & #run application in background
If your cool app has it's configuration loaded from an external file, like in the following example, then don't forget to update the corresponding config file with HOST="0.0.0.0"
cool.app.run(
host=cool.app.config.get("HOST", "localhost"),
port=cool.app.config.get("PORT", 9000)
)
If you're having troubles accessing your Flask server, deployed using PyCharm, take the following into account:
PyCharm doesn't run your main .py file directly, so any code in if __name__ == '__main__': won't be executed, and any changes (like app.run(host='0.0.0.0', port=5000)) won't take effect.
Instead, you should configure the Flask server using Run Configurations, in particular, placing --host 0.0.0.0 --port 5000 into Additional options field.
More about configuring Flask server in PyCharm
You can also set the host (to expose it on a network facing IP address) and port via environment variables.
$ export FLASK_APP=app.py
$ export FLASK_ENV=development
$ export FLASK_RUN_PORT=8000
$ export FLASK_RUN_HOST=0.0.0.0
$ flask run
* Serving Flask app "app.py" (lazy loading)
* Environment: development
* Debug mode: on
* Running on https://0.0.0.0:8000/ (Press CTRL+C to quit)
* Restarting with stat
* Debugger is active!
* Debugger PIN: 329-665-000
See How to get all available Command Options to set environment variables?
Go to your project path on CMD(command Prompt) and execute the following command:-
set FLASK_APP=ABC.py
SET FLASK_ENV=development
flask run -h [yourIP] -p 8080
you will get following o/p on CMD:-
Serving Flask app "expirement.py" (lazy loading)
Environment: development
Debug mode: on
Restarting with stat
Debugger is active!
Debugger PIN: 199-519-700
Running on http://[yourIP]:8080/ (Press CTRL+C to quit)
Now you can access your flask app on another machine using http://[yourIP]:8080/ url
For me i followed the above answer and modified it a bit:
Just grab your ipv4 address using ipconfig on command prompt
Go to the file in which flask code is present
In main function write app.run(host= 'your ipv4 address')
Eg:
Create file .flaskenv in the project root directory.
The parameters in this file are typically:
FLASK_APP=app.py
FLASK_ENV=development
FLASK_RUN_HOST=[dev-host-ip]
FLASK_RUN_PORT=5000
If you have a virtual environment, activate it and do a pip install python-dotenv .
This package is going to use the .flaskenv file, and declarations inside it will be automatically imported across terminal sessions.
Then you can do flask run
This answer is not solely related with flask, but should be applicable for all cannot connect service from another host issue.
use netstat -ano | grep <port> to see if the address is 0.0.0.0 or ::. If it is 127.0.0.1 then it is only for the local requests.
use tcpdump to see if any packet is missing. If it shows obvious imbalance, check routing rules by iptables.
Today I run my flask app as usual, but I noticed it cannot connect from other server. Then I run netstat -ano | grep <port>, and the local address is :: or 0.0.0.0 (I tried both, and I know 127.0.0.1 only allows connection from the local host). Then I used telnet host port, the result is like connect to .... This is very odd. Then I thought I would better check it with tcpdump -i any port <port> -w w.pcap. And I noticed it is all like this:
Then by checking iptables --list OUTPUT section, I could see several rules:
these rules forbid output tcp vital packets in handshaking. By deleting them, the problem is gone.
I had the same problem, I use PyCharm as an editor and when I created the project, PyCharm created a Flask Server. What I did was create a server with Python in the following way;
basically what I did was create a new server but flask if not python
I hope it helps you
This finally worked for me.
import os
Then place this at the end of your python app.py or main file.
if __name__ == "__main__":
port = int(os.environ.get("PORT", 5000))
app.run(host='0.0.0.0', port=port)
go to project path
set FLASK_APP=ABC.py
SET FLASK_ENV=development
flask run -h [yourIP] -p 8080
you will following o/p on CMD:-
* Serving Flask app "expirement.py" (lazy loading)
* Environment: development
* Debug mode: on
* Restarting with stat
* Debugger is active!
* Debugger PIN: 199-519-700
* Running on http://[yourIP]:8080/ (Press CTRL+C to quit)
If none of the above solutions are working, try manually adding "http://" to the beginning of the url.
Chrome can distinguish "[ip-address]:5000" from a search query. But sometimes that works for a while, and then stops connecting, seemingly without me changing anything. My hypothesis is that the browser might sometimes automatically prepend https:// (which it shouldn't, but this fixed it in my case).
In case you need to test your app from an external network.
Simply serve it to the whole Internet with ngrok.com
which will deploy it like a dev server but in no time and locally, saved me a lot of time, and no, I'm not related to that company :)
Just make sure to change the port in your flask app:
app.run(host='0.0.0.0', port=80)
I'm not sure if this is Flask specific, but when I run an app in dev mode (http://localhost:5000), I cannot access it from other machines on the network (with http://[dev-host-ip]:5000). With Rails in dev mode, for example, it works fine. I couldn't find any docs regarding the Flask dev server configuration. Any idea what should be configured to enable this?
While this is possible, you should not use the Flask dev server in production. The Flask dev server is not designed to be particularly secure, stable, or efficient. See the docs on deploying for correct solutions.
The --host option to flask run, or the host parameter to app.run(), controls what address the development server listens to. By default it runs on localhost, change it to flask run --host=0.0.0.0 (or app.run(host="0.0.0.0")) to run on all your machine's IP addresses.
0.0.0.0 is a special value that you can't use in the browser directly, you'll need to navigate to the actual IP address of the machine on the network. You may also need to adjust your firewall to allow external access to the port.
The Flask quickstart docs explain this in the "Externally Visible Server" section:
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 the debugger disabled or trust the users on your network,
you can make the server publicly available simply by adding
--host=0.0.0.0 to the command line:
$ flask run --host=0.0.0.0
This tells your operating system to listen on all public IPs.
If you use the flask executable to start your server, use flask run --host=0.0.0.0 to change the default from 127.0.0.1 and open it up to non-local connections.
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 the debugger disabled or trust the users on your network,
you can make the server publicly available simply by adding
--host=0.0.0.0 to the command line:
$ flask run --host=0.0.0.0
This tells your operating system to listen on all public IPs.
Reference: https://flask.palletsprojects.com/quickstart/
Try this if the 0.0.0.0 method doesn't work
Boring Stuff
I personally battled a lot to get my app accessible to other devices(laptops and mobile phones) through a local-server. I tried the 0.0.0.0 method, but no luck. Then I tried changing the port, but it just didn't work. So, after trying a bunch of different combinations, I arrived to this one, and it solved my problem of deploying my app on a local server.
Steps
Get the local IPv4 address of your computer.
This can be done by typing ipconfig on Windows and ifconfig on Linux
and Mac.
Please note: The above step is to be performed on the machine you are serving the app on, and on not the machine on which you are accessing it. Also note, that the IPv4 address might change if you disconnect and reconnect to the network.
Now, simply run the flask app with the acquired IPv4 address.
flask run -h 192.168.X.X
E.g. In my case (see the image), I ran it as:
flask run -h 192.168.1.100
On my mobile device
Optional Stuff
If you are performing this procedure on Windows and using Power Shell as the CLI, and you still aren't able to access the website, try a CTRL + C command in the shell that's running the app. Power Shell gets frozen up sometimes and it needs a pinch to revive. Doing this might even terminate the server, but it sometimes does the trick.
That's it. Give a thumbs up if you found this helpful.😉
Some more optional stuff
I have created a short Powershell script that will get you your IP address whenever you need one:
$env:getIp = ipconfig
if ($env:getIp -match '(IPv4[\sa-zA-Z.]+:\s[0-9.]+)') {
if ($matches[1] -match '([^a-z\s][\d]+[.\d]+)'){
$ipv4 = $matches[1]
}
}
echo $ipv4
Save it to a file with .ps1 extension (for PowerShell), and run it on before starting your app. You can save it in your project folder and run it as:
.\getIP.ps1; flask run -h $ipv4
Note: I saved the above shellcode in getIP.ps1.
Cool.👌
Add host='0.0.0.0' to app.run`.
if __name__ == '__main__':
app.run(host='0.0.0.0', port=5000)
If you get OSError: [WinError 10013] An attempt was made to access a socket in a way forbidden by its access permissions on Windows, you either don't have permission to use the port, or something else is using it which you can find with netstat -na|findstr 5000.
Check whether the particular port is open on the server to serve the client or not?
in Ubuntu or Linux distro
sudo ufw enable
sudo ufw allow 5000/tcp //allow the server to handle the request on port 5000
Configure the application to handle remote requests
app.run(host='0.0.0.0' , port=5000)
python3 app.py & #run application in background
If your cool app has it's configuration loaded from an external file, like in the following example, then don't forget to update the corresponding config file with HOST="0.0.0.0"
cool.app.run(
host=cool.app.config.get("HOST", "localhost"),
port=cool.app.config.get("PORT", 9000)
)
If you're having troubles accessing your Flask server, deployed using PyCharm, take the following into account:
PyCharm doesn't run your main .py file directly, so any code in if __name__ == '__main__': won't be executed, and any changes (like app.run(host='0.0.0.0', port=5000)) won't take effect.
Instead, you should configure the Flask server using Run Configurations, in particular, placing --host 0.0.0.0 --port 5000 into Additional options field.
More about configuring Flask server in PyCharm
You can also set the host (to expose it on a network facing IP address) and port via environment variables.
$ export FLASK_APP=app.py
$ export FLASK_ENV=development
$ export FLASK_RUN_PORT=8000
$ export FLASK_RUN_HOST=0.0.0.0
$ flask run
* Serving Flask app "app.py" (lazy loading)
* Environment: development
* Debug mode: on
* Running on https://0.0.0.0:8000/ (Press CTRL+C to quit)
* Restarting with stat
* Debugger is active!
* Debugger PIN: 329-665-000
See How to get all available Command Options to set environment variables?
Go to your project path on CMD(command Prompt) and execute the following command:-
set FLASK_APP=ABC.py
SET FLASK_ENV=development
flask run -h [yourIP] -p 8080
you will get following o/p on CMD:-
Serving Flask app "expirement.py" (lazy loading)
Environment: development
Debug mode: on
Restarting with stat
Debugger is active!
Debugger PIN: 199-519-700
Running on http://[yourIP]:8080/ (Press CTRL+C to quit)
Now you can access your flask app on another machine using http://[yourIP]:8080/ url
For me i followed the above answer and modified it a bit:
Just grab your ipv4 address using ipconfig on command prompt
Go to the file in which flask code is present
In main function write app.run(host= 'your ipv4 address')
Eg:
Create file .flaskenv in the project root directory.
The parameters in this file are typically:
FLASK_APP=app.py
FLASK_ENV=development
FLASK_RUN_HOST=[dev-host-ip]
FLASK_RUN_PORT=5000
If you have a virtual environment, activate it and do a pip install python-dotenv .
This package is going to use the .flaskenv file, and declarations inside it will be automatically imported across terminal sessions.
Then you can do flask run
This answer is not solely related with flask, but should be applicable for all cannot connect service from another host issue.
use netstat -ano | grep <port> to see if the address is 0.0.0.0 or ::. If it is 127.0.0.1 then it is only for the local requests.
use tcpdump to see if any packet is missing. If it shows obvious imbalance, check routing rules by iptables.
Today I run my flask app as usual, but I noticed it cannot connect from other server. Then I run netstat -ano | grep <port>, and the local address is :: or 0.0.0.0 (I tried both, and I know 127.0.0.1 only allows connection from the local host). Then I used telnet host port, the result is like connect to .... This is very odd. Then I thought I would better check it with tcpdump -i any port <port> -w w.pcap. And I noticed it is all like this:
Then by checking iptables --list OUTPUT section, I could see several rules:
these rules forbid output tcp vital packets in handshaking. By deleting them, the problem is gone.
I had the same problem, I use PyCharm as an editor and when I created the project, PyCharm created a Flask Server. What I did was create a server with Python in the following way;
basically what I did was create a new server but flask if not python
I hope it helps you
This finally worked for me.
import os
Then place this at the end of your python app.py or main file.
if __name__ == "__main__":
port = int(os.environ.get("PORT", 5000))
app.run(host='0.0.0.0', port=port)
go to project path
set FLASK_APP=ABC.py
SET FLASK_ENV=development
flask run -h [yourIP] -p 8080
you will following o/p on CMD:-
* Serving Flask app "expirement.py" (lazy loading)
* Environment: development
* Debug mode: on
* Restarting with stat
* Debugger is active!
* Debugger PIN: 199-519-700
* Running on http://[yourIP]:8080/ (Press CTRL+C to quit)
If none of the above solutions are working, try manually adding "http://" to the beginning of the url.
Chrome can distinguish "[ip-address]:5000" from a search query. But sometimes that works for a while, and then stops connecting, seemingly without me changing anything. My hypothesis is that the browser might sometimes automatically prepend https:// (which it shouldn't, but this fixed it in my case).
In case you need to test your app from an external network.
Simply serve it to the whole Internet with ngrok.com
which will deploy it like a dev server but in no time and locally, saved me a lot of time, and no, I'm not related to that company :)
Just make sure to change the port in your flask app:
app.run(host='0.0.0.0', port=80)
SSH works everywhere
I recently obtained a static IP at work and attached it to an internal domain. I am able to SSH into the machine with ssh MY_DOMAIN regardless of whether I'm
physically at work and on the same network, or
connected with full-tunnel VPN.
Flask works at work
If I'm physically at work and start a Flask server (code below) after logging into the desktop the domain is routed to, I can open up MY_DOMAIN in a browser on any computer at work (no VPN) and see Hello There!.
from flask import Flask
app = Flask(__name__)
#app.route("/")
def hello():
return "<h1 style='color:blue'>Hello There!</h1>"
if __name__ == "__main__":
app.run(host='0.0.0.0', port=80) # 127.0.0.1 didn't work either
# changing host to MY_DOMAIN or IP and port to 5000, etc. also didn't work
If I'm away from work but on VPN and SSH into the machine to start the Flask server, my connection times out when navigating to MY_DOMAIN in a browser.
Ping also works at work
On VPN, when I ping MY_DOMAIN, I see 0 packets received (all packets received when I'm at work):
9 packets transmitted, 0 packets received, 100.0% packet loss
If I turn off VPN away from work and ping MY_DOMAIN, I see:
ping: cannot resolve MY_DOMAIN: Unknown host
How am I able to SSH without any issues when I'm at work or away and on VPN, but can't interact with my domain in any other way on VPN?
I suspect this could be related to ports but I have limited networking knowledge.
And yep, I've done my research. This was the closest question on here connecting to flask app over VPN but it doesn't help (at least I don't think I want to deploy anything). I don't know if this is possible, but I think I want to configure: "forward incoming requests on port 80 of MY_DOMAIN to Flask app on localhost, port 80". (Edit: don't know any more after the Apache Web server works.)
Edit: I can connect to an Apache server on VPN but not Flask
I can navigate to MY_DOMAIN in a browser connected VPN and see "It Works" when I SSH and run:
sudo apachectl start
sudo defaults write /System/Library/LaunchDaemons/org.apache.httpd Disabled -bool false
I wonder why this doesn't work with Flask.
(reference: https://www.quora.com/How-can-I-make-my-iMac-the-hosting-for-my-website)
I am running the flask API using the following statement:
app.run(host='0.0.0.0', threaded=True, use_reloader=False)
My system IP is: 10.0.0.1, and I am on WIFI right now.
The API is accessible to local system via following URL:
127.0.0.1:5000/api/version/search/?text='search'
or via following:
10.0.0.1:5000/api/version/search/?text='search'
Now I have another system connected with the same network through WIFI and am trying to access the API through the URL:
10.0.0.1:5000/api/version/search/?text='search'
But it is saying : 10.0.0.1 refused to connect
Hence , I tried this:
0.0.0.0:5000/api/version/search/?text='search'
But still I got the same error: 0.0.0.0 refused to connect
Kindly, let me know how I can access the API through same wifi connect on another system?
in host argument (in run function) set your ip in your local network by example:
app.run(host='192.168.1.100', threaded=True, use_reloader=False)
you can get your ip using ifconfig command in linux (or ip addr command) or using ipconfig in windows.
It seems to be the firewall issue to me. Port 5000 needs to be set among the allowed ports in the firewall. Since you're running Ubuntu on your host machine, try the following command:
sudo ufw allow 5000
If that doesn't work, you need to set the iptables rules
We have developed an app in python and are using flask to expose its api via http requests.
all this on WINDOWS -
Everything works ok and we have tested in-house with no problems and we are now trying to use the app in the real world - we have gotten our IT dept to give us a public facing ip/port address (forwarded through a firewall ??) and now we can't access the server/app at all.
After a bit of digging, we've found the problem has something to do with the Windows Firewall configuration, when its on it won't work, when its off everything is fine.
the flask app code is run like so: app.run(debug=False, host='0.0.0.0', port=8080)
the port 8080 is setup in the Firewall Exceptions as is python.exe in the Program Exceptions
netstat -a shows the app is sitting there awaiting connection.
If I try to access the site though chrome I get the error: ERR_CONNECTION_TIMED_OUT.
With the firewall on i'm never seeing any "hits" come through to the app at all.
Is there some other configuration I'm missing?
Many thanks.
When running Flask from a windows machine with a firewall I open a port with the following commands:
netsh firewall add portopening TCP 8080 "MyAppName"
netsh advfirewall firewall add rule name="MyAppName TCP Port 8080" dir=in action=allow protocol=TCP localport=8080
netsh advfirewall firewall add rule name="MyAppName TCP Port 8080" dir=out action=allow protocol=TCP localport=8080
It work for me. Is it too much? I don't know as I am not a Firewall guru :(
When running as a service the program running the service is not python.exe but rather pythonservice.exe. You will have to add that to the allowed programs in the Windows Firewall Setup. In my case it is located under C:\Python33\Lib\site-packages\win32\pythonservice.exe.