Can i get the generated ip-address or domain name of flask_ngrok or py-ngrok and return it to 127.0.0.1/

1k views Asked by At

I'm trying to get the generated domain name or IP-address of flask_ngrok or py-ngrok after been deploy. I want to deploy flask_app to localhost and get the new IP-address or domain name on the main page.

I.E: If I access 127.0.0.1/ I want it to return something like You can now log in through https://aaf8447ee878.ngrok.io/

I have tried checking through the directories and read some help but I can't still get it. Thanks in advance ❤

3

There are 3 answers

0
MrAni On

I found out the easiest way to do this is the just copy the url when the user is visiting the site. You can do this by...

@app.before_request
def before_request():
    global url
    url = request.url
    # url = url.replace('http://', 'https://', 1)
    url = url.split('.ngrok.io')[0]
    url += '.ngrok.io'
1
MrAni On

add

import atexit
import json
import os
import platform
import shutil
import subprocess
import tempfile
import time
import zipfile
from pathlib import Path
from threading import Timer

import requests


def _run_ngrok():
    ngrok_path = str(Path(tempfile.gettempdir(), "ngrok"))
    _download_ngrok(ngrok_path)
    system = platform.system()
    if system == "Darwin":
        command = "ngrok"
    elif system == "Windows":
        command = "ngrok.exe"
    elif system == "Linux":
        command = "ngrok"
    else:
        raise Exception(f"{system} is not supported")
    executable = str(Path(ngrok_path, command))
    os.chmod(executable, 777)

    ngrok = subprocess.Popen([executable, 'http', '5000'])
    atexit.register(ngrok.terminate)
    localhost_url = "http://localhost:4040/api/tunnels"  # Url with tunnel details
    time.sleep(1)
    tunnel_url = requests.get(localhost_url).text  # Get the tunnel information
    j = json.loads(tunnel_url)

    tunnel_url = j['tunnels'][0]['public_url']  # Do the parsing of the get
    tunnel_url = tunnel_url.replace("https", "http")
    return tunnel_url


def _download_ngrok(ngrok_path):
    if Path(ngrok_path).exists():
        return
    system = platform.system()
    if system == "Darwin":
        url = "https://bin.equinox.io/c/4VmDzA7iaHb/ngrok-stable-darwin-amd64.zip"
    elif system == "Windows":
        url = "https://bin.equinox.io/c/4VmDzA7iaHb/ngrok-stable-windows-amd64.zip"
    elif system == "Linux":
        url = "https://bin.equinox.io/c/4VmDzA7iaHb/ngrok-stable-linux-amd64.zip"
    else:
        raise Exception(f"{system} is not supported")
    download_path = _download_file(url)
    with zipfile.ZipFile(download_path, "r") as zip_ref:
        zip_ref.extractall(ngrok_path)


def _download_file(url):
    local_filename = url.split('/')[-1]
    r = requests.get(url, stream=True)
    download_path = str(Path(tempfile.gettempdir(), local_filename))
    with open(download_path, 'wb') as f:
        shutil.copyfileobj(r.raw, f)
    return download_path

def start_ngrok():
    global ngrok_address
    ngrok_address = _run_ngrok()
    print(f" * Running on {ngrok_address}")
    print(f" * Traffic stats available on http://127.0.0.1:4040")


def run_with_ngrok(app):
    """
    The provided Flask app will be securely exposed to the public internet via ngrok when run,
    and the its ngrok address will be printed to stdout
    :param app: a Flask application object
    :return: None
    """
    old_run = app.run

    def new_run():
        thread = Timer(1, start_ngrok)
        thread.setDaemon(True)
        thread.start()
        old_run()
    app.run = new_run

####################

dont import flask_ngrok at the end at before name == 'main' add this function

def ngrok_url():
    global tunnel_url
    while True:
        try:
            print(ngrok_address)
        except Exception as e:
            print(e)

and after before app.run() put

thread = Timer(1, ngrok_url)
thread.setDaemon(True)
thread.start()

and run Warning: this will crash your code editor/ or terminal if u dont want that in the ngrok url function replace print with whatever you want to do with the url

0
MrAni On

and you dont need that

global tunnel_url
def ngrok_url():
    while True:
        try:
            print(ngrok_address)
        except Exception as e:
                print(e)

you can delete the threading part before the name == 'main' too after the imports set ngrok_address = '' then you can accses the ngrok_address anywhere in your code