Python Ngrok get active ngrok agent session for use in Flask App

936 views Asked by At

I am writing a Flask app that filters HTTP requests through an Ngrok tunnel. Everything works fine when I hard code the tunnel URL. The problem presented itself when I tried to introduce some automation logic to my program that checks if the there is an active tunnel with: ngrok.get_tunnels()

My plan was to establish a new connection and update my notification URL in the event of a missing active connection. Unfortunately, I can't even get to that step because my program Errors out with the message:

Your account is limited to 1 simultaneous ngrok agent session.\nActive ngrok agent sessions in region 'us'

This error occurs on ngrok.get_tunnels()

I've tried killing the ngrok.exe process, but the error still occurs as soon as my app call my ngrok function.

I am looking for a method to get the agent session to use in my program so a new session doesn't attempt to start if one is already active.

This is the logic I am trying to implement:

def tunnel_host():
    active_tunnels = ngrok.get_tunnels()
    if not active_tunnels:
        tunnel = ngrok.connect(5000, bind_tls=True)
        tunnel_url = tunnel.public_url
        return tunnel_url
    else:
        tunnel = ngrok.get_tunnels()
        tunnel_url = tunnel[0].public_url
        return tunnel_url

I greatly appreciate any feedback.

2

There are 2 answers

0
Kevin Cando On

There are different ways this may be happening, it could be you have the debug option active on Flask which is causing this. This can be fixed if you setup debug to False.

It could be the Werkzeug reloader (this is the library Flask supplies with the development server) that restarts the process each time your code changes.

If you set use_reloader to False you'll see the behaviour go away, but then you also lose the reloading functionality:

app.run(port=5001, debug=config.DEBUG, host='0.0.0.0', use_reloader=False)

You can disable the reloader when using the flask run command too:

FLASK_DEBUG=1 flask run --no-reload

In my case what did the trick was to setup the option monitor_thread to False.

from pyngrok import conf, ngrok

conf.get_default().monitor_thread = False
0
Russ Savage On

PM from ngrok here. At the time of this post, free accounts are limited to 1 ngrok agent running at a time. To see and kill any running agents in your account, check out the ngrok Dashboard Agents section and click the icon to stop the agent.