在 WSGI 客户端上将 CSS 和 JSS 连接到 HTML

问题描述 投票:0回答:1

我有以下代码在女服务员服务器上实现页面路由。我面临以下任务:我需要连接 CSS 和 JS 样式,我该怎么做?

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)
javascript css server wsgi content-type
1个回答
0
投票

通过添加此条件,应用程序会检查请求的路径是否以“/static/”开头。如果是,它会尝试直接从指定路径提供静态文件。这样,您的 CSS 和 JS 文件将得到正确的服务。

          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"]
© www.soinside.com 2019 - 2024. All rights reserved.