web.py 是一个轻量级、简洁的 Python Web 框架,由 Aaron Swartz 开发。它以简单直接的设计哲学著称,适合快速构建小型 Web 应用和 API接口实现。
核心特点:
- 1. 极简设计:代码量少,核心文件仅一个 web模块
安装 web.py
通过 pip 安装:
pip install web.py
注意:Python 3 请使用 pip install web.py==0.62(0.62+ 版本支持 Python 3)
基础配置
创建基础应用结构:
myapp/
├── app.py         # 主程序
├── templates/     # 模板目录
│   └── index.html
└── static/        # 静态文件
    └── style.css
使用示例
示例 1:基础 Web 应用
# app.py
import web
# URL 路由配置
urls =(
    '/','Index',
    '/hello/(.*)','Hello'
)
app = web.application(urls,globals())
classIndex:
    defGET(self):
        return"Welcome to web.py!"
classHello:
    defGET(self, name):
        returnf"Hello, {name}!"
if __name__ =="__main__":
    app.run()
运行应用:
python app.py
访问:
- • http://localhost:8080/hello/Leo

示例 2:使用模板引擎
<!-- templates/index.html -->
<html>
<head><title>web.py Demo</title></head>
<body>
    <h1>$title</h1>
    <ul>
    $for item in items:
        <li>$item</li>
    </ul>
</body>
</html>
# app.py (添加新路由)
urls =(
    '/','Index',
    '/list','List'
)
render = web.template.render('templates/')
classList:
    defGET(self):
        data ={
            "title":"Shopping List",
            "items":["Apples","Bananas","Coffee"]
        }
        return render.index(**data)
示例 3:表单处理
# 添加表单路由
urls =(
'/form','FormHandler'
)
classFormHandler:
defGET(self):
return'''<form method="post">
                    <input type="text" name="name">
                    <button>Submit</button>
                  </form>'''
defPOST(self):
        data = web.input()
return f"Received: {data.name}"
示例 4:数据库操作(SQLite)
# 添加表单路由
urls =(
    '/form','FormHandler'
)
classFormHandler:
    defGET(self):
        return'''<form method="post">
                    <input type="text" name="name">
                    <button>Submit</button>
                  </form>'''
    
    defPOST(self):
        data = web.input()
        return f"Received: {data.name}"
关键组件详解
- 1. URL 路由系统:urls = (
 '/path', 'ClassName',
 '/(.*)', 'CatchAll'  # 正则匹配
 )
 
- 2. 请求处理:class MyHandler:
 def GET(self):
 # 获取查询参数
 input_data = web.input(id=None)
 
 def POST(self):
 # 获取表单数据
 form_data = web.input()
 
- 3. 模板使用:render = web.template.render('templates/')
 return render.my_template(name="John", age=30)
 
- 4. HTTP 工具:# 重定向
 raise web.seeother('/new-url')
 
 # 设置 Cookie
 web.setcookie("user", "john")
 
部署生产环境
使用内置 WSGI 服务器部署:
# app.py 底部添加
application = app.wsgifunc()
然后用 uWSGI/Gunicorn 运行:
gunicorn app:application
适用场景
注意:对于大型复杂项目,建议使用 Django 或 Flask 等更全功能的框架。
最近在看官方微信公众号开发指南和chatgpt-on-wechat都是基于web.py进行简单示例讲解和开发的,所以很有必要学习和记录一下web.py模块。 web.py 以其极简哲学著称,核心代码仅数千行,但提供了完整的 Web 开发基础功能,是理解 Web 框架设计的优秀学习资源。
该文章在 2025/7/15 10:30:28 编辑过