0

I wanted to build a server and a website that is accessible from any computer connected to internet. here is my code:

from flask import Flask, render_template
import forms

def hello_world():
    for i in range(10):
        print('Hello World')
    
app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret-key'  # this is for when we define a form
@app.route('/')

#@app.route('/about')    

@app.route('/about', methods = ['GET', 'POST'])

def about():
    b = '''
   <form>
    <input type="checkbox" id="vehicle1" name="vehicle1" value="Bike">
    <label for="vehicle1"> I have a bike</label><br>
    <input type="checkbox" id="vehicle2" name="vehicle2" value="Car">
    <label for="vehicle2"> I have a car</label><br>
    <input type="checkbox" id="vehicle3" name="vehicle3" value="Boat">
    <label for="vehicle3"> I have a boat</label>
   </form>
    '''
    return b  # runs html commands in string b that is defined above
    

It builds a server on http://127.0.0.1:5000/ and it is accessible from my own computer where I'm running python code. However when I try to open this address on a another computer web browser, it does not work. How can I make it accessible from another computers connected to Internet?

Emon
  • 9
  • 1
  • You need to decide whether to host your site on your PC, or on a commercial hoster, eg digital ocean, heroku and many others. – Jürgen Gmach Mar 27 '21 at 10:18

1 Answers1

0

Testing your localhost app from anther device

ngrok is a tunneling tool that creates public URLs that allow access to your application from another computer. Typically, your computer has a firewall which prevents access to your application.

To use it, you will need to install it:

(venv)$ pip3 install pyngrok

pyngrok is a Python wrapper for ngrok that manages its own binary and puts it on your path, making ngrok readily available from anywhere on the command line and via a convenient Python API.

Run ngrok --help in your virtual environment to confirm that it is installed and working:

(venv)$ ngrok --help

How it works

Open two terminal windows:

enter image description here

If you do not know how to do this on your default ubuntu terminal window, consider using the byobu window manager and terminal multiplexer. Alternatively, if you are on VSCode, you can simply split your terminal.

  • On your first window, start your application to access http://127.0.0.1:5000/
  • On your second terminal, start ngrok:
(venv)$ ngrok http 5000 
# Or any other port you may be using

From the second window running ngrok, look for lines beginning with "Forwarding". ngrok provides you with both http and https versions of free publicly accessible URLs. You might have something such as http://23ebfb1baa7e.ngrok.io.

enter image description here

The subdomain portion is going to be different each time you run ngrok. Send this URL to anther device to access your locally running application. It works from anywhere in the world!

This is the quickest way you can access your application while it is still in development.

Going further: How to create a ngrok tunnel

It is exciting to know that you can actually run your application on another device. The method that I have shown you above will require you to do this every time you want to access your application. But you might want to automatically create ngrok tunnel every time you fire up your server. I will show you an example using the flask server.

In your application instance (app/init.py), use ngrok.connect to return a free public URL that is assigned to your tunnel.

def start_ngrok():
    from pyngrok import ngrok

    url = ngrok.connect(5000).public_url
    print('* Tunnel: ', url)

if app.config['START_NGROK']:
    start_ngrok()

As soon as we have defined the function which handles the ngrok tunnel, we check if its configuration has been set in our environment variables. In your config.py file, create an instance of START_NGROK:

START_NGROK = os.environ.get('START_NGROK') is not None

Then in a hidden file that has all your environment variables (we can call it .flaskenv), define your variable:

# .flaskenv

START_NGROK=1

If you use a reloader and have enabled the ngrok tunnel, you will notice that two URLs are provided as soon as you fire up your server.

enter image description here

Use the URLs on another device to access your locally running application.

For clarity, this is the kind of application structure I am referring to when building a flask application:

project_folder
    | ---------- config.py
    | ---------- app.py
    | ---------- .flaskenv
    | ---------- app/
                  | ---------- routes.py
                  | ---------- __init__.py
                  | ---------- models.py
                  | ---------- templates/
                  | ---------- static/
alexdlaird
  • 1,174
  • 12
  • 34
Gitau Harrison
  • 3,179
  • 1
  • 19
  • 23
  • Thanks for proper reply. I just wonder, is there a simple way to build a website that can be opened in any computer connected to internet easily? I mean, do all website developer have to go thorough so many steps to make their website available for users? Or is there a way around? I guess the soul of the challenge I mentioned above is about how to make a website accessible for users across the internet – Emon Mar 29 '21 at 14:28
  • it is best to host your application on sites such as Heroku, digital ocean as @J.G above suggested. This way, anyone who knows the application's URL can access it on the internet. To do this, you have to learn the process of doing it. It is not a drag and drop kind of process to host your application from a developer standpoint. – Gitau Harrison Mar 29 '21 at 15:36
  • But for locally hosted application, you can't do that. It will be only accessible to you. `ngrok` would be ideal to access the application URL from anywhere. The downside of using `ngrok` especially the free tier package is that the public URL given keeps changing. If you like the ngrok service, you can purchase their packages to get reserved domains – Gitau Harrison Mar 29 '21 at 15:38
  • Thanks. Then what is the value of having just a local website by flask? does it mean that it can only bee seen in the local computer where the python code and has been run? or can it only be seen at least in an internal network of few computers that are connected ; say; in a company? – Emon Apr 01 '21 at 19:55
  • It is recommended not to use the Flask server in production because it is designed not to be particularly secure, stable or efficient. That is why you have noticed 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. – Gitau Harrison Apr 01 '21 at 23:44
  • 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 computer to listen to all public IPs. See [deployment options](https://flask.palletsprojects.com/en/master/deploying/) and the [flask quickstart guide](https://flask.palletsprojects.com/en/1.1.x/quickstart/) – Gitau Harrison Apr 01 '21 at 23:44
  • I use Jupyter notebook to write codes, and then Anaconda prompt for commands, and my computer is on Windows 10. I tried to make the website public by above command (flask run --host==0.0.0.0), but it seems it did not work. Looks I'm missing something in the sequence of commands in Anaconda command prompt. could you please guide the sequence of commands for windows and Anaconda prompt? – Emon Apr 05 '21 at 14:04