Skip to content

Instantly share code, notes, and snippets.

@liquidgenius
Created February 7, 2020 04:46
Show Gist options
  • Save liquidgenius/3d699f49eed0023f39cb658200ab6bbc to your computer and use it in GitHub Desktop.
Save liquidgenius/3d699f49eed0023f39cb658200ab6bbc to your computer and use it in GitHub Desktop.
ExternalAccess provides convenience methods for using PyNgrok with FastAPI.
from pathlib import Path
from pyngrok import ngrok
class ExternalAccess:
""" ExternalAccess provides convenience methods for using PyNgrok with FastAPI. It assumes
you have a custom NGROK config file at resources/ngrok.yml. Pyngrok install is required:
https://pyngrok.readthedocs.io/en/latest/
USAGE:
from ExternalAccess import ExternalAccess
ea = EA()
if __name__ == "__main__":
print(f"Authenticate: {ea.public_url}/docs")
uvicorn.run(app, host='0.0.0.0', port=ea.port, log_level="info")
"""
def __init__(self):
self.config_path = None
self.public_url = None
self.process = None
self.domain = None
self.tunnels = None
self.process = None
self.port = None
self.set_config_path()
self.connect()
self.set_domain()
self.set_process()
self.set_tunnels()
self.set_port()
def set_config_path(self):
config_path = Path.cwd() / 'resources' / 'ngrok.yml'
self.config_path = config_path
def connect(self, ensure_https=True):
public_url = ngrok.connect(port=5050, config_path=self.config_path).replace('http','https')
if ensure_https:
public_url = public_url.replace('http', 'https')
self.public_url = public_url
def set_domain(self):
self.domain = self.public_url.split('//')[-1]
def set_process(self):
self.process = ngrok.get_ngrok_process()
def set_tunnels(self):
self.tunnels = ngrok.get_tunnels()
def set_port(self):
self.port = int(self.tunnels[0].config['addr'].split(':')[-1])
def get_port(self):
return self.port
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment