generated from hjess/PythonTemplateProject
Lets test
All checks were successful
Build, Push, and Deploy to Nomad / docker-nomad (push) Successful in 33s
All checks were successful
Build, Push, and Deploy to Nomad / docker-nomad (push) Successful in 33s
This commit is contained in:
27
app.py
27
app.py
@@ -3,12 +3,32 @@ from fastapi.staticfiles import StaticFiles
|
|||||||
from fastapi.templating import Jinja2Templates
|
from fastapi.templating import Jinja2Templates
|
||||||
import json
|
import json
|
||||||
import os
|
import os
|
||||||
from fastapi import FastAPI
|
|
||||||
from fastapi.responses import HTMLResponse
|
from fastapi.responses import HTMLResponse
|
||||||
from contextlib import asynccontextmanager
|
from contextlib import asynccontextmanager
|
||||||
from markdown_render import render_markdown_with_jinja
|
from markdown_render import render_markdown_with_jinja
|
||||||
|
|
||||||
from starlette.middleware.httpsredirect import HTTPSRedirectMiddleware
|
from starlette.middleware.httpsredirect import HTTPSRedirectMiddleware
|
||||||
|
from fastapi import FastAPI, Request
|
||||||
|
from fastapi.responses import RedirectResponse
|
||||||
|
from starlette.middleware.base import BaseHTTPMiddleware
|
||||||
|
|
||||||
|
class ConditionalHTTPSRedirectMiddleware(BaseHTTPMiddleware):
|
||||||
|
async def dispatch(self, request: Request, call_next):
|
||||||
|
# Extract the host or remote address
|
||||||
|
host = request.headers.get("host", "")
|
||||||
|
client_ip = request.client.host # Get the client's IP address
|
||||||
|
|
||||||
|
# Log for debugging
|
||||||
|
print(f"Client IP: {client_ip}, Host: {host}")
|
||||||
|
|
||||||
|
# Check condition: Redirect only if not on 127.0.0.1
|
||||||
|
if client_ip != "127.0.0.1" and request.url.scheme == "http":
|
||||||
|
https_url = request.url.replace(scheme="https")
|
||||||
|
return RedirectResponse(url=https_url)
|
||||||
|
|
||||||
|
# Continue processing other requests
|
||||||
|
response = await call_next(request)
|
||||||
|
return response
|
||||||
|
|
||||||
|
|
||||||
# Context manager for app lifespan
|
# Context manager for app lifespan
|
||||||
@asynccontextmanager
|
@asynccontextmanager
|
||||||
@@ -25,7 +45,8 @@ app.mount("/data", StaticFiles(directory="data"), name="data")
|
|||||||
|
|
||||||
# Mount static files
|
# Mount static files
|
||||||
app.mount("/static", StaticFiles(directory="static"), name="static")
|
app.mount("/static", StaticFiles(directory="static"), name="static")
|
||||||
app.add_middleware( HTTPSRedirectMiddleware )
|
#app.add_middleware( HTTPSRedirectMiddleware )
|
||||||
|
app.add_middleware(ConditionalHTTPSRedirectMiddleware)
|
||||||
|
|
||||||
# Templates directory
|
# Templates directory
|
||||||
templates = Jinja2Templates(directory="templates")
|
templates = Jinja2Templates(directory="templates")
|
||||||
|
|||||||
Reference in New Issue
Block a user