Cos I tied myself in knots reading about static file handling in Python’s Flask, I thought I’d take a note of what worked for now (GPT’s help appreciated). Attempts to look at StackOverflow for the same advice was confusing as defaults had changed over the years. Attempts would work for my localhost deployment, and not for the corporate app-server, or vice versa, but not both.

Prompt: “Make a Python/Flask app that has a static JavaScript resource that says document.write("Hello"); a page web page template that says “world” after the JavaScript has inserted its word into the page, but also a context (top-level directory of the webapp) “greeting” that’s passed in as an argument to the Python and not hard-coded anywhere”. Well, close enough as it took three goes.

Python ‘app.py’ script

import os
import argparse
from flask import Flask, render_template, send_from_directory

# Argument parsing
parser = argparse.ArgumentParser(description='Run a Flask app with a given URL context.')
parser.add_argument('context', type=str, help='Context for the app URL')
args = parser.parse_args()

app = Flask(__name__)
context = args.context.strip('/')

# Static file serving route
@app.route(f'/{context}/static/<path:filename>')
def custom_static(filename):
return send_from_directory('static', filename)

@app.route(f'/{context}/')
def index():
greeting = "world"
return render_template('index.html', greeting=greeting)

if __name__ == '__main__':
app.run(debug=True)

script.js inside static/ folder

document.write("Hello");

index.html in template/ folder

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Flask App</title>
</head>
<body>
  <script src="./static/script.js"></script>
  <span id="js-greeting"></span> <span>, how are you?</span>
</body>
</html>

Launching

python app.py

There is url_for(..) template function for Flask, but it didn’t help at all. Relative via “./” was the best/correct approach in the html for loading static resources without having to know the context name. To be honest that was true in 1995 and hasn’t changed. Of course, web-scale deployments should at least use the likes of Nginx for static resources.



Published

February 8th, 2024
Reads: