You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

runserver_ngrok.py 1.6KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. import os
  2. from six.moves.urllib_parse import urlparse
  3. import requests
  4. from django_grip import get_pubcontrol
  5. from django.apps import apps
  6. if apps.is_installed('django.contrib.staticfiles'):
  7. from django.contrib.staticfiles.management.commands import runserver
  8. else:
  9. from django.core.management.commands import runserver
  10. class Command(runserver.Command):
  11. help = 'Set ngrok tunnel as origin for GRIP service, then invoke runserver'
  12. def setup(self):
  13. host = None
  14. port = None
  15. ssl_host = None
  16. ssl_port = None
  17. resp = requests.get('http://localhost:4040/api/tunnels')
  18. tunnels = resp.json()['tunnels']
  19. for tunnel in tunnels:
  20. if tunnel['proto'] in ('http', 'https'):
  21. parsed = urlparse(tunnel['public_url'])
  22. if tunnel['proto'] == 'http':
  23. host = parsed.hostname
  24. port = parsed.port if parsed.port is not None else 80
  25. elif tunnel['proto'] == 'https':
  26. ssl_host = parsed.hostname
  27. ssl_port = parsed.port if parsed.port is not None else 443
  28. if host is None and ssl_host is None:
  29. self.stderr.write('Error: no ngrok tunnels found')
  30. return
  31. pub = get_pubcontrol()
  32. if len(pub.clients) == 0:
  33. self.stderr.write('Error: no GRIP proxy configured')
  34. return
  35. pub.set_origin(
  36. host=host,
  37. port=port,
  38. ssl_host=ssl_host,
  39. ssl_port=ssl_port,
  40. rewrite_host=True)
  41. self.stdout.write(
  42. 'Setting ngrok tunnel %s as GRIP origin' % (host or ssl_host))
  43. def run(self, **options):
  44. # be sure to execute setup() only once, even if autoreload is used
  45. use_reloader = options['use_reloader']
  46. if not use_reloader or os.environ.get('RUN_MAIN') != 'true':
  47. self.setup()
  48. super(Command, self).run(**options)