Skip to content

Instantly share code, notes, and snippets.

@FlorianLudwig
Created October 14, 2020 14:49
Show Gist options
  • Save FlorianLudwig/96702ecc9da9034fad0ea4c625fc962b to your computer and use it in GitHub Desktop.
Save FlorianLudwig/96702ecc9da9034fad0ea4c625fc962b to your computer and use it in GitHub Desktop.
FastAPI With two ports
"""
hypercorn main:multi_port -k uvloop -b 127.0.0.1:8000 -b 127.0.0.1:8001
"""
from fastapi import FastAPI
from starlette_exporter import PrometheusMiddleware, handle_metrics
app = FastAPI()
app.add_middleware(PrometheusMiddleware)
@app.get("/")
def read_root():
return {"Hello": "World"}
app_meta = FastAPI()
app_meta.add_route("/metrics", handle_metrics)
def multi_port(scope):
if scope["server"][1] == 8000:
handler = app
elif scope["server"][1] == 8001:
handler = app_meta
async def asgi(receive, send):
await handler(scope, receive, send)
return asgi
@includeamin
Copy link

includeamin commented Oct 18, 2020

sample.py

from fastapi import FastAPI
from starlette_exporter import PrometheusMiddleware, handle_metrics

external = FastAPI()
internal = FastAPI()

external.add_middleware(PrometheusMiddleware)


@external.get("/users/information")
async def login(user_id: str):
    return {"user_id": user_id}


@internal.get("/login")
async def login():
    return {"login": "login"}


internal.add_route("/metrics", handle_metrics)


def run(scope):
    if scope['server'][1] == 8080:
        handler = internal
    elif scope['server'][1] == 80:
        handler = external

    async def asgi(receive, send):
        await handler(scope, receive, send)

    return asgi
gunicorn sample:run -w 2 -k uvicorn.workers.UvicornWorker --bind 0.0.0.0:80 --bind 0.0.0.0:8080 --threads=2

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment