Connect to Flask Server from other devices on same network - python

Dear smart people of stackoverflow,
I know this question has been asked a lot here but none of the posted solutions have worked for me as of yet. Any help here would be much appreciated:
The Problem: Cannot connect to flask app server from other devices (PCs, mobiles) on the same network. (in other words: localhost works perfectly but I cannot connect from external device)
What I've Tried:
1) Setting app.run(host='0.0.0.0', port=5000, debug=True, threaded=True) in the app.py so that the server will listen on all available network interfaces.
2) Enabling TCP traffic for port 5000 in local network in Windows Defender Firewall (with inbound and outbound rules added)
3) Using my host PC's IPv4 address in the URL bar of my external device's browser in the following format: http://<host_ipaddress>:<port>/
4) Using my host PC's hostname in the URL bar of my external device's browser in the following format: http://<host_name>:<port>/
5) Running the app.py file from Windows Powershell and Python (.py) Executor
None of these solutions has worked so far, even after attempting to connect from a few different external devices. Thanks in advance for your help!

I solved the issue by changing my home network profile to private instead of public, which allows my PC to be discoverable. Completely overlooked that!
Hope this helps someone!

Here is the method which worked for me.
Find the ip address of system using ifconfig command
Replace the host ip in code with your ip
server.py:
from flask import Flask
app = Flask(__name__)
#app.route('/')
def about():
return 'It worked!'
if __name__ == '__main__':
app.run(host='192.168.43.81', port=5000, debug=True, threaded=False)
To run the program:
python3 server.py
I know it is late, but I believe it can help others.

Much depends on how you're running your app. From what you've written, I'm guessing that you have
if __name__ == '__main__':
app.run(host='0.0.0.0', port=5000, debug=True, threaded=True)
If that's not working, changes are good that you're using flask run to start things up. The problem here is that flask will import your application before looking for app in your application's namespace. The problem is that __name__ will then reflect the name of the base file, and not __main__, so app.run() never gets run.
If that's the case, try passing --host=0.0.0.0 as an argument.

If you are on windows go to your internet settings and change network profile from Public to private

I did a similar setup with my django project. Your PC network settings are probably all good, but your router ( at least for wlan) is blocking the traffic. I solved this by tampering with needed settings in router manager api, which can be found from 192.168.1.1 in your local network. You can check your device ip addresses etc.

Go to your wifi settings and change network profile from public to private.
If its already private click on configure firewall and security settings shown below which opens windows security
There disable the microsoft defender firewall for private connections.
This worked for me

Related

Flask Waitress Simple Webserver

I am trying to set up a simple webserver. This is the simplified code.
from flask import Flask
from waitress import serve
app = Flask(__name__)
#app.route("/data")
def get_data():
return {"abc"[i]:i for i in range(3)}
if __name__=="__main__":
# app.run(debug=True, host="0.0.0.0", port=8080)
serve(app, host="0.0.0.0", port=8080)
I can connect to this on my desktop and my phone (which is on my WiFi) and it works as desired.
The issue comes when a connection is attempted from a device not on my network (say a phone on a different network). The response is ERR_ADDRESS_UNREACHABLE.
I setup an inbound rule in my firewall settings. I'm on a windows 10 OS right now if that matters.
ProtocolType=TCP (it was default)
LocalPort="Specific Ports" and 8080
RemotePort="All Ports"
I also read I should set up port forwarding in my router so I followed these instructions from my ISP.
It's in the Service List
Global Port Range is 8080-8080
Protocol is TCP/UDP (again, default)
Host Port is 8080
I'm not sure what else I should change.
Thanks!
Answering my own question for posterity.
My issue was some AT&T weirdness. I turned on IP passthrough in my router settings and other people can connect to the server.
If I run ipconfig in my cmd prompt, I get an IPv4 of A.B.C.D, but https://whatismyipaddress.com/ responds with E.F.G.H.
I can connect to A.B.C.D:8080/data from my computer but not the other IP.
Someone not on my IP can connect to E.F.G.H:8080/data from a different network but not the other one.
The final takeaway is that I should probably just use some sort of ns services like cloudflare.

How to run Python Flask app on domain name?

I own a domain name, how can I get my flask app to run on it, using my public IP address (assigned to me by my internet provider)? I don't want it to run on localhost, or my private IPv4 address, I want it to run on my Public IP address. Thanks in advance.
If it helps, I am using Google Domains.
Do I need to add anything to my flask app?
I'm currently running it like this:
if __name__ == "__main__":
db.create_all()
app.run(debug=True, host="0.0.0.0", port=80)
Was this a public IP provided by your Internet provider? Or is it a public IP provided by a web hosting company? The two answers are different.
If it came from a web hosting company, then you need to upload your flask app to your account on their server. Note, however, that most shared hosting companies will not let you run an app 24/7. They want to support FastCGI servers that come and go.
If this was provided by your Internet provider, then you will need to provide and configure a server. You will need to have your router redirect port 80 and 443 to that server. You will then need to run your flask app on that server. Make sure your server is secure, because public-facing IP address get hammered by scammers.

This site can’t be reached http://127.0.0.1:8000/hello using Flask as web framework

I am trying to run a simple "hello world" code using flask version 1.1.1 and python 3.7. the server is running but the web page is not loading. Can anyone please help???
from flask import Flask
app = Flask(__name__)
#app.route('/hello')
def hello_world():
return "Hello world"
if __name__ == '__main__':
app.run(host='127.0.0.1',port=8000, debug=True)
Output is as below
But the web page(http://127.0.0.1:8000/hello) displays "This site can’t be reached"
I encountered same problem when I change my default port from 5000 to 6000 with app.run(debug=True, host='127.0.0.1', port=6000). Which is the time I got this site can't be reached with unsafe port error from Chrome.
However, when I just tried with port 5001, 6868, 7999. All of them worked. Therefore, I guess if a port didn't work, it might be simply that some hidden system functions are already using it as a listening port, and all you gotta do is by changing and testing if any other port number could work
I tried using different port like 8000,8080,5000. finally worked for 7999 port number. The appropriate solution for this kind of problem is to experiment with different port numbers
make host =0.0.0.0 in app.run() and whatever port you will give it will work and if you will not give port in by default it will take 5000

Problems with external visibility of Flask web-server

I have managed to to install flask and run the hello-world script:
from flask import Flask
app = Flask(__name__)
#app.route('/')
def hello_world():
return 'Hello World!'
if __name__ == '__main__':
app.run()
I was impressed how easy it was. Then I wanted to make my web-server visible externally. As recommended, I put host='0.0.0.0' as the argument of run function. Then I found my IP address (in Google) and put it in the address line of my web browser (while the hello-world-script was running).
As a result I got: "A username and password are being requested" and a dialogue box where I need to put a user name and password. I am not sure but I think it comes from my wireless network. Is there a way to change this behaviour?
How are you trying to run your application? If you run flask as app.run() - flask creates its own WSGI server on your host (by default 127.0.0.1) and port (by default 5000) (need permissions if port < 1000). If you run flask using nginx + WSGI or etc. your server resolves host and port.
Now it looks like you want get application by port which resolved your server like nginx or Apache. Try to get flask application by http://your-server-host-or-ip:5000 with the default port or try to change the port (set explicit) like app.run('0.0.0.0', 8080) and get it by http://your-server-host-or-ip:8080.
By the way, you can always get IP address using command-line tools e.g. ifconfig for Unix-like systems, or ipconfig /all for Windows.
To elaborate a little bit onto what #tbicr said, that password prompt indicates that you're trying to connect to your IP on port 80, which is most likely hosting an administration page for your router/modem. You want to connect to your IP on port 5000, the default port for Flask apps run with app.run().

AWS - Running webservice - Cherrypy + Python

I have a linux box (Ubuntu 10.10 server edition) in ec2. I have written a web service using cherrypy framework. Let's say this is the code that I have written.
import sys
sys.path.insert(0,'cherrypy.zip')
import cherrypy
from cherrypy import expose
class Service:
#expose
def index(self):
return 'Hello World'
cherrypy.quickstart(Service())
I have copied this file, the cherrypy.zip file to /var/www in my ec2 instance. [I should inform that I created the www directory manually, as it wasn't there]. Then I ran
python webservice.py
and got the message
[01/Apr/2011:13:50:04] ENGINE Bus STARTED
However, when I try to run
(I have masked my public ip)
ec2-1**-2**-1**-**.ap-southeast-1.compute.amazonaws.com/
in my browser, I get connection failed. Can anyone tell me where I have gone wrong? or what I should do?
EDIT:
Okay, here is something interesting that I found. When I do
python webservice.py
I see
ENGINE Serving on 127.0.0.1:8080
Which means, the webservice will run only for the local machine. How do I make set the service 0.0.0.0 (that is, to serve any IP address?)
Hope this detail is sufficient for understanding the problem I'm facing. Help, please :)
EDIT 2:
Oh well, found the solution :-) Have to add this before cherrypy.quickstart() call
cherrypy.config.update({'server.socket_host': '0.0.0.0',
'server.socket_port': 80,
})
The cherrypy.quickstart function takes a config argument, which can be a dict, an open configuration file, or a path to a configuration file. I favor using a path to a configuration file because that minimizes the hardcoding of settings that you might prefer to control from a startup script.
In addition, since you control the server, you could configure a reverse proxy to route requests to the CherryPy application. This gives you quite a bit of flexibility. For example, if you wanted to, you could run multiple instances of the CherryPy application in parallel, each configured to listen on a different port.
Here's a sample configuration file for nginx, instructing it to forward requests to a single instance of your CherryPy application:
server
{
server_name your.hostname.com;
  location / {
    proxy_pass http://127.0.0.1:8080/;
  }
}
And here's a sample configuration file instructing nginx to load-balance across two instances of your application, which are listening on the loopback address at ports 33334 and 33335:
upstream myapps {
server 127.0.0.1:33334;
server 127.0.0.1:33335;
}
server {
server_name your.hostname.com;
location / {
proxy_pass http://myapps;
}
}

Categories

Resources