Simple FastAPI server that return headers, remote and local IP addresses
3.3K
_app.py
import os
import socket
from fastapi import APIRouter, Request, HTTPException
router = APIRouter()
def get_ipv4_address():
try:
with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as s:
s.connect(('8.8.8.8', 80))
return s.getsockname()[0]
except Exception:
return "NotFound"
def get_ipv6_address():
try:
with socket.socket(socket.AF_INET6, socket.SOCK_DGRAM) as s:
s.connect(('2001:4860:4860::8888', 80))
return s.getsockname()[0]
except Exception:
return "NotFound"
hostname = socket.gethostname()
ipv4_address = get_ipv4_address()
ipv6_address = get_ipv6_address()
def generate_data_dict(app_name, request):
return {
'app': app_name,
'hostname': os.getenv('HOST_HOSTNAME', 'Unknown'),
'c-hostname': hostname,
'ipv4': os.getenv('HOST_IPV4', ipv4_address),
'ipv6': os.getenv('HOST_IPV6', ipv6_address),
'remote-addr': request.client.host,
'headers': dict(request.headers)
}
@router.get("/")
async def default(request: Request):
return generate_data_dict('SERVER', request)
@router.get("/path1")
async def path1(request: Request):
return generate_data_dict('SERVER-PATH1', request)
@router.get("/path2")
async def path2(request: Request):
return generate_data_dict('SERVER-PATH2', request)
@router.get("/healthz")
async def healthz(request: Request):
# Example of adding specific logic for a particular endpoint if needed
# allowed_hosts = ["healthz.az.corp"]
# if request.client.host not in allowed_hosts:
# raise HTTPException(status_code=403, detail="Access denied")
return "OK"
main.py
from fastapi import FastAPI, Request, Response, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse
from _app import router as app_router
import json
import ssl
import uvicorn
class PrettyJSONResponse(Response):
media_type = "application/json"
def render(self, content: any) -> bytes:
return json.dumps(content, indent=2).encode('utf-8')
app = FastAPI(default_response_class=PrettyJSONResponse)
# CORS middleware
app.add_middleware(
CORSMiddleware,
allow_origins=["*"], # Replace * with actual frontend domain
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# Custom middleware to add Access-Control-Allow-Origin header
@app.middleware("http")
async def add_cors_header(request, call_next):
response = await call_next(request)
response.headers["Access-Control-Allow-Origin"] = "*"
return response
# Include the API router
app.include_router(app_router, tags=["Features"])
requirements.txt
cryptography==41.0.7
fastapi==0.105.0
uvicorn==0.25.0
Content type
Image
Digest
sha256:f6e92d246…
Size
27.7 MB
Last updated
about 1 month ago
docker pull ksalawu/fastapi