Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Now uses ngrok's auth tokens #35

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 9 additions & 8 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,30 +15,31 @@ Python 3.6+ is required.
```bash
pip install flask-ngrok
```
### Inside Jupyter / Colab Notebooks
Notebooks have [an issue](https://stackoverflow.com/questions/51180917/python-flask-unsupportedoperation-not-writable) with newer versions of Flask, so force an older version if working in these environments.
```bash
!pip install flask==0.12.2
```
See the [example notebook](https://colab.research.google.com/github/gstaff/flask-ngrok/blob/master/examples/flask_ngrok_example.ipynb) for a working example.

## Quickstart
0. Signup on `ngrok` to get an auth token.
1. Import with ```from flask_ngrok import run_with_ngrok```
2. Add `run_with_ngrok(app)` to make your Flask app available upon running
2. Add `run_with_ngrok(app, 'YOUR AUTH TOKEN')` to make your Flask app available upon running
```python
# flask_ngrok_example.py
# examples/flask_ngrok_example.py
from flask import Flask
import os

from flask_ngrok import run_with_ngrok

app = Flask(__name__)
run_with_ngrok(app) # Start ngrok when app is run
run_with_ngrok(app, '<YOUR AUTH TOKEN HERE>') # Start ngrok when app is run


@app.route("/")
def hello():
return "Hello World!"


if __name__ == '__main__':
app.run()

```
Running the example:
```bash
Expand Down
61 changes: 30 additions & 31 deletions examples/flask_ngrok_example.ipynb
Original file line number Diff line number Diff line change
@@ -1,48 +1,35 @@
{
"nbformat": 4,
"nbformat_minor": 0,
"metadata": {
"colab": {
"name": "flask-ngrok-example.ipynb",
"version": "0.3.2",
"provenance": [],
"collapsed_sections": []
},
"kernelspec": {
"name": "python3",
"display_name": "Python 3"
}
},
"cells": [
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "1cljkrUaPeyg",
"colab": {},
"colab_type": "code",
"colab": {}
"id": "1cljkrUaPeyg"
},
"cell_type": "code",
"outputs": [],
"source": [
"!pip install flask-ngrok\n",
"!pip install flask==0.12.2 # Newer versions of flask don't work in Colab\n",
" # See https://github.com/plotly/dash/issues/257"
],
"execution_count": 0,
"outputs": []
"!pip install flask"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "H39hVXhiPtBo",
"colab": {},
"colab_type": "code",
"colab": {}
"id": "H39hVXhiPtBo"
},
"cell_type": "code",
"outputs": [],
"source": [
"# flask_ngrok_example.py\n",
"from flask import Flask\n",
"from flask_ngrok import run_with_ngrok\n",
"\n",
"app = Flask(__name__)\n",
"run_with_ngrok(app) # Start ngrok when app is run\n",
"run_with_ngrok(app, '<YOUR AUTH TOKEN HERE>') # Start ngrok when app is run\n",
"\n",
"@app.route(\"/\")\n",
"def hello():\n",
Expand All @@ -51,9 +38,21 @@
"if __name__ == '__main__':\n",
" app.run() # If address is in use, may need to terminate other sessions:\n",
" # Runtime > Manage Sessions > Terminate Other Sessions"
],
"execution_count": 0,
"outputs": []
]
}
]
}
],
"metadata": {
"colab": {
"collapsed_sections": [],
"name": "flask-ngrok-example.ipynb",
"provenance": [],
"version": "0.3.2"
},
"kernelspec": {
"display_name": "Python 3",
"name": "python3"
}
},
"nbformat": 4,
"nbformat_minor": 0
}
3 changes: 2 additions & 1 deletion examples/flask_ngrok_example.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
from flask import Flask
import os

from flask_ngrok import run_with_ngrok

app = Flask(__name__)
run_with_ngrok(app) # Start ngrok when app is run
run_with_ngrok(app, '<YOUR AUTH TOKEN HERE>') # Start ngrok when app is run


@app.route("/")
Expand Down
37 changes: 24 additions & 13 deletions flask_ngrok.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,22 +26,28 @@ def _get_command():
return command


def _run_ngrok(port):
def _run_ngrok(port, auth_token):
if not auth_token:
return None

command = _get_command()
ngrok_path = str(Path(tempfile.gettempdir(), "ngrok"))
_download_ngrok(ngrok_path)
executable = str(Path(ngrok_path, command))
os.chmod(executable, 0o777)
ngrok = subprocess.Popen([executable, 'http', str(port)])
ngrok = subprocess.Popen([executable, 'http', str(port), '--authtoken', auth_token])
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
try:
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
except requests.exceptions.ConnectionError:
return


def _download_ngrok(ngrok_path):
Expand Down Expand Up @@ -70,24 +76,29 @@ def _download_file(url):
return download_path


def start_ngrok(port):
ngrok_address = _run_ngrok(port)
print(f" * Running on {ngrok_address}")
print(f" * Traffic stats available on http://127.0.0.1:4040")
def start_ngrok(port, auth_token):
ngrok_address = _run_ngrok(port, auth_token)
if ngrok_address:
print(f" * Running on {ngrok_address}")
print(f" * Traffic stats available on http://127.0.0.1:4040")
else:
print("There is an issue with your `auth_token`. Please check it!")
print(f" - ngrok is not running")


def run_with_ngrok(app):
def run_with_ngrok(app, auth_token):
"""
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
:param auth_token: Your ngrok authentication token
:return: None
"""
old_run = app.run

def new_run(*args, **kwargs):
port = kwargs.get('port', 5000)
thread = Timer(1, start_ngrok, args=(port,))
thread = Timer(1, start_ngrok, args=(port, auth_token))
thread.setDaemon(True)
thread.start()
old_run(*args, **kwargs)
Expand Down
2 changes: 1 addition & 1 deletion setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@

setuptools.setup(
name="flask-ngrok",
version="0.0.26",
version="0.0.27",
author="Grant Stafford",
description="A simple way to demo Flask apps from your machine.",
long_description=long_description,
Expand Down