You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在Waitress WSGI服务器中为HTML引入CSS与JS的方法

在Waitress服务器中为HTML页面引入CSS和JS样式的方法

我现有一段在Waitress服务器上实现页面路由的代码,现在需要给HTML页面引入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)

实现步骤

1. 规划静态文件目录结构

先在项目根目录下创建静态文件存放目录,规范文件分类:

项目根目录/
├── templates/       # 原有HTML模板目录
│   ├── index.html
│   ├── contact.html
│   ├── 2.html
│   └── 404.html
├── static/          # 新增静态资源目录
│   ├── css/         # CSS文件存放子目录
│   │   └── style.css
│   └── js/          # JS文件存放子目录
│       └── main.js
└── app.py           # 你的Waitress服务代码文件

2. 修改服务代码,添加静态文件路由

在原有代码中新增静态文件处理逻辑,识别静态资源请求并返回正确的响应:

from waitress import serve
import os

def render_template(template_name, context={}):
   html_str=""
   with open(template_name, 'r', encoding='utf-8') 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 serve_static(environ, start_response):
    # 获取请求的静态文件路径
    path = environ.get("PATH_INFO").lstrip('/')
    file_path = os.path.join(os.getcwd(), path)
    
    # 检查文件是否存在
    if not os.path.exists(file_path) or os.path.isdir(file_path):
        start_response("404 Not Found", [("Content-type", "text/plain")])
        return iter([b"Static file not found"])
    
    # 根据文件后缀设置正确的Content-Type
    content_type = "text/plain"
    if file_path.endswith('.css'):
        content_type = "text/css"
    elif file_path.endswith('.js'):
        content_type = "application/javascript"
    elif file_path.endswith('.png'):
        content_type = "image/png"
    elif file_path.endswith(('.jpg', '.jpeg')):
        content_type = "image/jpeg"
    
    # 读取并返回文件内容
    with open(file_path, 'rb') as f:
        file_content = f.read()
    
    start_response("200 OK", [("Content-type", content_type)])
    return iter([file_content])

def app(environ, start_response):
   path= environ.get("PATH_INFO")
   
   # 优先处理静态资源请求
   if path.startswith('/static/'):
       return serve_static(environ, start_response)
   
   # 原有页面路由逻辑
   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; charset=utf-8"),
      ]
    )
   return iter([page])

serve(app, host='0.0.0.0', port=8080)

3. 在HTML模板中引入静态资源

修改HTML文件,使用绝对路径引入CSS和JS:

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>首页</title>
    <!-- 引入CSS样式 -->
    <link rel="stylesheet" href="/static/css/style.css">
</head>
<body>
    <h1>欢迎访问首页</h1>
    <!-- 引入JS脚本 -->
    <script src="/static/js/main.js"></script>
</body>
</html>

4. 测试验证

启动服务器后,访问页面即可看到CSS样式生效,JS代码正常执行。


内容的提问来源于stack exchange,提问作者Dread

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.08 08:07:42