Back to ports You're done! Click here to return home.

Testing on different devices

Sometimes we might want other devices in the network to be able to access our program. By specifying the host as an argument we can allow this.

Let’s set the host to 0.0.0.0. This is an “invalid” address that can’t exist. Instead, the computer will use all it’s IP addresses to allow us to access flask.

app.run(host'0.0.0.0')

The problem is, if we go to localhost:5000 we won’t find anything now.

We need to work out our machines IP address. We can do that using command prompt, or by adding some code to our program that will give us a link to the testing address.

Let’s add this method to the top of our program

import socket

 

#method: show ip address

def printIP(): 

    try

        host_name = socket.gethostname() 

        host_ip = socket.gethostbyname(host_name) 

        print("Testing Address: https://"+host_ip+":5000/"

    except

        print("Unable to get Testing Address"

When run, this will tell us the IP address of the host machine, if we are connected to the network.

Let’s tell it to run just above the flask.run() call. We can simply do this by adding the following code:

printIP()

We now have a complete program looking like this:

#imports

from flask import Flask

from pathlib import Path

 

import socket

 

#method: show ip address

def printIP(): 

    try

        host_name = socket.gethostname() 

        host_ip = socket.gethostbyname(host_name) 

        print("Testing Address: https://"+host_ip+":5000/"

    except

        print("Unable to get Testing Address"

 

@flaskApp.route('/'

@flaskApp.route('/index')

def index(): 

    return  "Hello, world!"

 

#create flask instance

app = Flask(__name__,   #same as our original flask instance creation

            static_url_path=''#tells the server that requests at this address should be used to serach for static files

            static_folder='/')  #in this folder

 

#method calls

printIP()

if __name__ == '__main__':

    app.run(host'0.0.0.0')

When we run this we’ll get told our IP address, and any device connected to the network should be able to access your sample site!

Remember that if you change your port, you’ll have to change it in your link too

Back to ports Return to top You're done! Click here to return home.