Denizhalil

Quickly Expose Web Servers with Python and Ngrok

Introduction:

In the process of web development, there is often a need to expose a locally developed web application to the outside world. This arises when the application needs to be tested on different devices, shared, or deployed to a live environment. However, the inability of local servers to be accessible from the general internet can complicate this process. This is where Ngrok comes in. Ngrok is a tool that quickly exposes local servers, making this process much simpler. In this article, we will learn how to use Ngrok and integrate it with Python.

Learning Objectives:

  • Understand the basic usage of Ngrok
  • Learn how to integrate Ngrok with Python
  • Provide a step-by-step guide to exposing a Python web server with Ngrok

Project Objective:

This project aims to quickly expose a local web server using Python and Ngrok. Our goal is to provide a practical solution for easily sharing and testing a web application developed locally during the development process. With Ngrok’s flexibility and ease of use, completing this project will save a significant amount of time during the development process.

A Brief Look at Ngrok:

Ngrok is a service that makes your local server accessible from the general internet. It generates a URL for your local server and allows access to it via the internet. For more details, you can refer to this link.

Let’s Start Writing Our Code:

  • First, let’s write our server that will expose us to the external network.

1. Creating the HTTP Server:

from http.server import SimpleHTTPRequestHandler, HTTPServer
import threading

2. HTTP Server Handler Class:

class RequestHandler(SimpleHTTPRequestHandler):
    def do_GET(self):
        # Set the request path to 'index.php'
        self.path = 'index.php'
        return SimpleHTTPRequestHandler.do_GET(self)

3. Sending HTTP Request for Ngrok:

class Ngrok:
    @staticmethod
    def get_ngrok_url():
        try:
            # Send a request to Ngrok's API to get the URL
            response = requests.get("http://127.0.0.1:4040/api/tunnels")
            data = response.json()
            ngrok_url = data["tunnels"][0]["public_url"]
            return ngrok_url
        except Exception as e:
            # Return None in case of an error
            return None

    @staticmethod
    def start_ngrok():
        try:
            # Start Ngrok
            import subprocess
            subprocess.run(["ngrok", "http", "8000"])
        except Exception as e:
            print("Ngrok could not be started:", e)

4. Class to Start the HTTP Server:

class HTTPServerWithNgrok:
    def __init__(self):
        # Set the server address and port
        self.server_address = ("", 8000)
        # Create the HTTP server
        self.httpd = HTTPServer(self.server_address, RequestHandler)
        # Start a new thread to start Ngrok
        self.ngrok_thread = threading.Thread(target=Ngrok.start_ngrok, daemon=True)
        self.ngrok_thread.start()

    def start_server(self):
        print("Waiting for Ngrok URL...")
        while True:
            # Get the URL generated by Ngrok
            ngrok_url = Ngrok.get_ngrok_url()
            if ngrok_url:
                print("Ngrok URL:", ngrok_url)
                break
        # Continuously run the server
        self.httpd.serve_forever()

5. Starting the HTTP Server:

# Start the HTTP server and Ngrok
http_server = HTTPServerWithNgrok()
http_server.start_server()

After the program is run, the URL provided by Ngrok can be used to access the server.

Python Ngrok Integration
Expose Local Server to Internet Python
Ngrok Python Web Server Tutorial
  • Now let’s write a simple HTML code to test that our code can be accessed from the external network.
<!-- index.html -->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>DenizHalil.com</title>
</head>
<body>
    <!-- Simple HTML content -->
    <h1>Hello Everyone</h1>
</body>
</html>

Conclusion:

In this article, we explored how to integrate Ngrok with Python and quickly expose local web servers. Ngrok’s flexibility and ease of use provide a significant advantage for web developers. You can now easily share, test, and even deploy locally developed web applications(HTML Injection and Examples).

By minimizing the time spent during the development process, Ngrok’s simple interface and powerful features allow for a more efficient workflow. Additionally, with the pyngrok library provided by Ngrok for Python, it is possible to manage your application programmatically.

This project not only teaches the basics of exposing a web server with Ngrok using Python but also provides a solution that simplifies the sharing and testing processes during web application development in general. From now on, you can work more efficiently by using Ngrok in your web development projects.

Leave a Comment

Join our Mailing list!

Get all latest news, exclusive deals and academy updates.