Last active
March 5, 2024 18:20
-
-
Save alexdlaird/ad2b47f2bc4de67e79f6ed8534f08c29 to your computer and use it in GitHub Desktop.
Django integration example for pyngrok, full documentation found at https://pyngrok.readthedocs.io/en/latest/integrations.html
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import os | |
import sys | |
from urllib.parse import urlparse | |
from django.apps import AppConfig | |
from django.conf import settings | |
class CommonConfig(AppConfig): | |
name = "myproject.common" | |
verbose_name = "Common" | |
def ready(self): | |
if and settings.USE_NGROK and os.environ.get("NGROK_AUTHTOKEN"): | |
# pyngrok will only be installed, and should only ever be initialized, in a dev environment | |
from pyngrok import ngrok | |
# Get the dev server port (defaults to 8000 for Django, can be overridden with the | |
# last arg when calling `runserver`) | |
addrport = urlparse("http://{}".format(sys.argv[-1])) | |
port = addrport.port if addrport.netloc and addrport.port else "8000" | |
# Open a ngrok tunnel to the dev server | |
public_url = ngrok.connect(port).rstrip("/") | |
print(f"ngrok tunnel \"{public_url}\" -> \"http://127.0.0.1:{port}\") | |
# Update any base URLs or webhooks to use the public ngrok URL | |
settings.BASE_URL = public_url | |
CommonConfig.init_webhooks(public_url) | |
@staticmethod | |
def init_webhooks(base_url): | |
# Update inbound traffic via APIs to use the public-facing ngrok URL | |
pass |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import os | |
# ... The rest of our Django settings | |
BASE_URL = "http://localhost:8000" | |
USE_NGROK = os.environ.get("USE_NGROK", "False") == "True" and os.environ.get("RUN_MAIN", None) != "true" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment