Forked from alexdlaird/pyngrok_FastApiExample_server.py
Created
March 15, 2021 03:59
-
-
Save raaghulr/37c1582b934944a68a1421653879d12c to your computer and use it in GitHub Desktop.
Fast API 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
# USE_NGROK=True uvicorn server:app | |
import os | |
import sys | |
from fastapi import FastAPI | |
from fastapi.logger import logger | |
from pydantic import BaseSettings | |
class Settings(BaseSettings): | |
# ... The rest of our FastAPI settings | |
BASE_URL = "http://localhost:8000" | |
USE_NGROK = os.environ.get("USE_NGROK", "False") == "True" | |
settings = Settings() | |
def init_webhooks(base_url): | |
# Update inbound traffic via APIs to use the public-facing ngrok URL | |
pass | |
# Initialize the FastAPI app for a simple web server | |
app = FastAPI() | |
if settings.USE_NGROK: | |
# pyngrok should only ever be installed or initialized in a dev environment when this flag is set | |
from pyngrok import ngrok | |
# Get the dev server port (defaults to 8000 for Uvicorn, can be overridden with `--port` | |
# when starting the server | |
port = sys.argv[sys.argv.index("--port") + 1] if "--port" in sys.argv else 8000 | |
# Open a ngrok tunnel to the dev server | |
public_url = ngrok.connect(port) | |
logger.info("ngrok tunnel \"{}\" -> \"http://127.0.0.1:{}/\"".format(public_url, port)) | |
# Update any base URLs or webhooks to use the public ngrok URL | |
settings.BASE_URL = public_url | |
init_webhooks(public_url) | |
# ... Initialize routers and the rest of our app |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment