Skip to content

Instantly share code, notes, and snippets.

@jacoduplessis
Created May 31, 2017 15:48
Show Gist options
  • Save jacoduplessis/94db3b88857eacdf261a8a79d3099cc9 to your computer and use it in GitHub Desktop.
Save jacoduplessis/94db3b88857eacdf261a8a79d3099cc9 to your computer and use it in GitHub Desktop.
Management command to set Django Site 1 domain to ngrok public url. In an app, add this file under `/management/commands/` as `ngrok.py`. Remember the `__init__.py` files. Run with `python manage.py ngrok`.
import json
from urllib.request import urlopen
from django.contrib.sites.models import Site
from django.core.management.base import BaseCommand, CommandError
class Command(BaseCommand):
help = 'Sets site domain to ngrok url and update telegram bot webhook'
def handle(self, *args, **options):
try:
with urlopen("http://localhost:4040/api/tunnels") as conn:
api_data = json.loads(conn.read().decode('utf-8'))
tunnels = api_data['tunnels']
ngrok_public_url = None
for tunnel in tunnels:
if tunnel['proto'] != 'https':
continue
ngrok_public_url = tunnel['public_url'].replace('https://', '')
assert ngrok_public_url is not None
except Exception as e:
raise CommandError("{}\nCould not find ngrok public url. "
"Did you remember to run `ngrok http $PORT`?".format(e))
site = Site.objects.get(pk=1)
site.domain = ngrok_public_url
site.save()
self.stdout.write(self.style.SUCCESS("Site 1 domain set to {}".format(ngrok_public_url)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment