我可以获取flask_ngrok或py-ngrok生成的ip地址或域名并返回到127.0.0.1/

Posted

技术标签:

【中文标题】我可以获取flask_ngrok或py-ngrok生成的ip地址或域名并返回到127.0.0.1/【英文标题】:Can i get the generated ip-address or domain name of flask_ngrok or py-ngrok and return it to 127.0.0.1/ 【发布时间】:2021-02-05 06:17:45 【问题描述】:

我正在尝试在部署后获取 flask_ngrok 或 py-ngrok 生成的域名或 IP 地址。我想将 flask_app 部署到 localhost 并在主页上获取新的 IP 地址或域名。

IE:如果我访问 127.0.0.1/ 我希望它返回类似 您现在可以通过https://aaf8447ee878.ngrok.io/登录

我已尝试检查目录并阅读了一些帮助,但我仍然无法获得它。提前谢谢❤

【问题讨论】:

看看Flask的Request context,然后看看request.host。那是你要找的吗?如果请求来自localhost127,则呈现不同的页面。 【参考方案1】:

添加

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

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

不要导入 flask_ngrok 最后在 name == 'ma​​in' 之前添加这个函数

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

app.run() 之前和之后

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

并运行警告:如果您不希望在 ngrok url 函数中使用您想要对 url 执行的任何操作替换 print,这将使您的代码编辑器/或终端崩溃

【讨论】:

谢谢,我试试看。【参考方案2】:

你不需要那个

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

您也可以在导入集之后删除 name == 'ma​​in' 之前的线程部分 ngrok_address = '' 然后您可以在代码中的任何位置访问 ngrok_address

【讨论】:

【参考方案3】:

我发现最简单的方法是在用户访问网站时复制 url。你可以这样做...

@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'

【讨论】:

以上是关于我可以获取flask_ngrok或py-ngrok生成的ip地址或域名并返回到127.0.0.1/的主要内容,如果未能解决你的问题,请参考以下文章

如何键入可以获取列表或元组的列表或元组的函数?

我可以在 iOS 中使用 Map 或 Locate SDK 获取 POI

有啥方法或方法可以找出我的错误以获取此命令的解决方案吗?

对于一个对象,我可以使用反射或其他方式获取它的所有子类吗?

我可以从 Swift 中的 SecKeyRef 对象中获取模数或指数吗?

我可以使用ffmpeg或ffprobe获取h.264每一帧的引用列表吗?