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)
2
Answers
Thanks to Ramziya's answer, I figured out how to do it, for which many thanks! So far I've only connected CSS styles, but I already know how to do it with JS, I'll do it later!
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.