Problem:
I have the following code that implements page routing on the waitress server. I am faced with the following task: I need to connect CSS and JS styles, how do I do this?
from waitress import serve
def render_template(template_name, context={}):
html_str=""
with open(template_name, 'r') as f:
html_str=f.read()
html_str=html_str.format(**context)
return html_str
def home(environ):
return render_template('templates/index.html', context={})
def contact_us(environ):
return render_template('templates/contact.html', context={})
def contact2(environ):
return render_template('templates/2.html', context={})
def app(environ, start_response):
path= environ.get("PATH_INFO")
if path == "/":
page = home(environ)
elif path == "/contact":
page = contact_us(environ)
elif path == "/contact/2":
page = contact2(environ)
else:
page = render_template('templates/404.html', context={"path":path})
page = page.encode("utf-8")
start_response(
f"200 OK", [
("Content-type", "text/html"),
]
)
return iter([page])
serve(app)
Solution:
By adding thiscondition, the app checks if the requested path starts with “/static/”. If it does, it attempts to serve the static file directly from the specified path. This way, your CSS and JS files will be served correctly.
if path.startswith("/static/"):
# Serve static files directly
static_file_path = path.lstrip("/static/")
try:
with open(static_file_path, 'rb') as f:
content = f.read()
start_response("200 OK", [("Content-type", "text/css" if path.endswith(".css") else "text/javascript")])
return [content]
except FileNotFoundError:
start_response("404 Not Found", [("Content-type", "text/plain")])
return [b"404 Not Found"]