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:
102
app.py
102
app.py
@@ -1,19 +1,34 @@
|
|||||||
from fastapi import FastAPI, Request
|
from fastapi import FastAPI, Request
|
||||||
from fastapi.staticfiles import StaticFiles
|
from fastapi.staticfiles import StaticFiles
|
||||||
from fastapi.responses import HTMLResponse
|
|
||||||
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 contextlib import asynccontextmanager
|
||||||
|
from markdown_render import render_markdown_with_jinja
|
||||||
from starlette.middleware.httpsredirect import HTTPSRedirectMiddleware
|
from starlette.middleware.httpsredirect import HTTPSRedirectMiddleware
|
||||||
|
|
||||||
app = FastAPI()
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
# Context manager for app lifespan
|
||||||
|
@asynccontextmanager
|
||||||
|
async def lifespan(app: FastAPI):
|
||||||
|
print("App startup: Processing Markdown files...")
|
||||||
|
process_markdown_files("./data", "./data") # Process all Markdown files
|
||||||
|
print("Markdown processing complete!")
|
||||||
|
yield # Allow the app to start
|
||||||
|
print("App shutdown: Cleanup complete.")
|
||||||
|
|
||||||
|
app = FastAPI(lifespan=lifespan)
|
||||||
|
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 )
|
|
||||||
|
|
||||||
# Templates directory
|
# Templates directory
|
||||||
templates = Jinja2Templates(directory="templates")
|
templates = Jinja2Templates(directory="templates")
|
||||||
@@ -23,34 +38,22 @@ with open("mock_data.json") as file:
|
|||||||
data = json.load(file)
|
data = json.load(file)
|
||||||
|
|
||||||
@app.get("/test", response_class=HTMLResponse)
|
@app.get("/test", response_class=HTMLResponse)
|
||||||
async def mark_test():
|
async def home_test():
|
||||||
markdown_content = """
|
# Load the Markdown content from a file
|
||||||
# Custom Tags Test
|
with open("templates/example.md", "r") as f:
|
||||||
|
markdown_content = f.read()
|
||||||
|
|
||||||
Here is an image overlay:
|
# Render Markdown first, then inject Jinja2 components
|
||||||
{img-left-overlay: src=my-cat.png}
|
rendered_html = render_markdown_with_jinja(markdown_content)
|
||||||
|
|
||||||
Here is a box:
|
# Wrap in a base HTML layout
|
||||||
{box: title=Important, content=This is a reusable box.}
|
html_template = f"""
|
||||||
|
|
||||||
And a note:
|
|
||||||
{note: content=This is a note for the user.}
|
|
||||||
|
|
||||||
Warning section:
|
|
||||||
{warning: content=Pay attention to this warning!}
|
|
||||||
"""
|
|
||||||
|
|
||||||
# Render Markdown content
|
|
||||||
rendered_html = md_renderer.render( markdown_content )
|
|
||||||
|
|
||||||
# Wrap in a basic template
|
|
||||||
template = f"""
|
|
||||||
<!DOCTYPE html>
|
<!DOCTYPE html>
|
||||||
<html lang="en">
|
<html lang="en">
|
||||||
<head>
|
<head>
|
||||||
<meta charset="UTF-8">
|
<meta charset="UTF-8">
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||||
<title>Markdown Tags</title>
|
<title>Markdown + Jinja2</title>
|
||||||
<style>
|
<style>
|
||||||
.img-left-overlay img {{ width: 300px; }}
|
.img-left-overlay img {{ width: 300px; }}
|
||||||
.box {{ border: 1px solid #ccc; padding: 10px; background-color: #f9f9f9; }}
|
.box {{ border: 1px solid #ccc; padding: 10px; background-color: #f9f9f9; }}
|
||||||
@@ -65,7 +68,37 @@ async def mark_test():
|
|||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
"""
|
"""
|
||||||
return HTMLResponse( content = template )
|
return HTMLResponse(content=html_template)
|
||||||
|
|
||||||
|
def process_markdown_files(input_dir: str, output_dir: str):
|
||||||
|
"""
|
||||||
|
Recursively process all Markdown files in the input directory,
|
||||||
|
render them to HTML, and save them in the output directory.
|
||||||
|
"""
|
||||||
|
for root, _, files in os.walk(input_dir):
|
||||||
|
for file in files:
|
||||||
|
if file.endswith(".md"):
|
||||||
|
input_file_path = os.path.join(root, file)
|
||||||
|
|
||||||
|
# Determine output file path (convert .md to .html)
|
||||||
|
relative_path = os.path.relpath(input_file_path, input_dir)
|
||||||
|
output_file_path = os.path.join(output_dir, os.path.splitext(relative_path)[0] + ".html")
|
||||||
|
|
||||||
|
# Ensure the output directory exists
|
||||||
|
os.makedirs(os.path.dirname(output_file_path), exist_ok=True)
|
||||||
|
|
||||||
|
# Read Markdown content
|
||||||
|
with open(input_file_path, "r", encoding="utf-8") as md_file:
|
||||||
|
markdown_content = md_file.read()
|
||||||
|
|
||||||
|
# Render Markdown with Jinja2
|
||||||
|
print(f"Processing: {input_file_path} -> {output_file_path}")
|
||||||
|
rendered_html = render_markdown_with_jinja(markdown_content)
|
||||||
|
|
||||||
|
# Write the rendered HTML to the output file
|
||||||
|
with open(output_file_path, "w", encoding="utf-8") as html_file:
|
||||||
|
html_file.write(rendered_html)
|
||||||
|
|
||||||
|
|
||||||
# Index route
|
# Index route
|
||||||
@app.get("/", response_class=HTMLResponse)
|
@app.get("/", response_class=HTMLResponse)
|
||||||
@@ -75,7 +108,18 @@ async def get_index(request: Request):
|
|||||||
{"request": request, "data": data, "page_title": "Forside", "author": "Henrik"}
|
{"request": request, "data": data, "page_title": "Forside", "author": "Henrik"}
|
||||||
)
|
)
|
||||||
|
|
||||||
|
@app.get("/sitemap", response_class=HTMLResponse)
|
||||||
|
async def sitemap():
|
||||||
|
"""Simple home page listing available HTML files."""
|
||||||
|
links = []
|
||||||
|
for root, _, files in os.walk("./data"):
|
||||||
|
for file in files:
|
||||||
|
if file.endswith(".html"):
|
||||||
|
relative_path = os.path.relpath(os.path.join(root, file), "./data")
|
||||||
|
link = f"<a href='/data/{relative_path}'>{relative_path}</a>"
|
||||||
|
links.append(link)
|
||||||
|
links_html = "<br>".join(links)
|
||||||
|
return HTMLResponse(content=f"<h1>Available Pages</h1>{links_html}")
|
||||||
|
|
||||||
# Category route
|
# Category route
|
||||||
@app.get("/category/{category_name}", response_class=HTMLResponse)
|
@app.get("/category/{category_name}", response_class=HTMLResponse)
|
||||||
|
|||||||
Reference in New Issue
Block a user