Web 开发入门
本教程共 70 篇 · 第 60 篇 · 更新于 2026-07-22 · 约 5 分钟阅读
60. Web 开发入门
本节目标:理解 WSGI 是什么,能写出一个最简单的 Web 应用,并跑通 Flask 框架的基础用法。
前面的章节里,你已经学会了用 socket 手写 HTTP 请求。真实项目中没人从零写 Web 服务,而是借助框架快速搭建。这节带你从 WSGI 协议出发,再上手最流行的 Python Web 框架之一:Flask。
WSGI:Python Web 的通用插座
Web 框架五花八门,如果每个框架都要适配不同的 Web 服务器,开发和部署会变成灾难。WSGI(Web Server Gateway Interface)就是 Python 社区定下的标准接口,让框架和服务器可以任意组合。
一个符合 WSGI 标准的应用本质上是一个可调用对象,接收两个参数,返回响应体:
def application(environ, start_response):
start_response('200 OK', [('Content-Type', 'text/html')])
return [b'<h1>Hello, WSGI!</h1>']
environ:字典,包含 HTTP 请求的所有信息,如请求方法、路径、查询参数。start_response:回调函数,用来设置状态码和响应头。- 返回值:可迭代对象,内容是响应体字节串。
你可以用 Python 内置的 wsgiref 模块跑起来:
from wsgiref.simple_server import make_server
with make_server('', 8000, application) as httpd:
print("服务运行在 http://localhost:8000")
httpd.serve_forever()
打开浏览器访问 http://localhost:8000,就能看到 “Hello, WSGI!”。
Note
wsgiref只适合开发和测试,生产环境要用 Gunicorn、uWSGI 等专业服务器。理解 WSGI 的意义在于:你知道框架底层是怎么和服务器对接的。
Flask:从 Hello World 开始
Flask 是轻量级 Web 框架的代表,核心代码简洁,扩展丰富。安装只需一行:
pip install flask
最小应用:
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello():
return 'Hello, Flask!'
if __name__ == '__main__':
app.run(debug=True)
运行后访问 http://127.0.0.1:5000,页面上会显示 “Hello, Flask!”。
代码拆解:
Flask(__name__)创建应用实例。@app.route('/')把 URL 路径和函数绑定,这个函数叫视图函数。app.run()启动开发服务器,debug=True开启调试模式,代码改动会自动重载。
Warning
app.run()自带的开发服务器性能很差,不要用于生产环境。部署时请用 Gunicorn:gunicorn -w 4 app:app。
路由与请求处理
Flask 的路由支持变量片段:
@app.route('/user/<name>')
def show_user(name):
return f'用户: {name}'
@app.route('/post/<int:post_id>')
def show_post(post_id):
return f'文章编号: {post_id}'
<int:post_id> 会自动把参数转成整数,如果访问 /post/abc 会返回 404。
获取请求数据:
from flask import request
@app.route('/login', methods=['GET', 'POST'])
def login():
if request.method == 'POST':
username = request.form.get('username')
password = request.form.get('password')
return f'收到用户名: {username}'
return '''
<form method="post">
<input name="username" placeholder="用户名">
<input type="password" name="password" placeholder="密码">
<button type="submit">登录</button>
</form>
'''
request.form获取 POST 表单数据。request.args获取 URL 查询参数。request.json获取 JSON 格式的请求体(写 API 时常用)。
模板渲染
把 HTML 硬编码在 Python 里很难维护。Flask 默认集成 Jinja2 模板引擎,把页面结构和数据分离。
项目结构:
project/
app.py
templates/
hello.html
templates/hello.html:
<!doctype html>
<html>
<head><title>{{ title }}</title></head>
<body>
<h1>你好, {{ name }}!</h1>
{% if items %}
<ul>
{% for item in items %}
<li>{{ item }}</li>
{% endfor %}
</ul>
{% endif %}
</body>
</html>
app.py:
from flask import render_template
@app.route('/hello/<name>')
def hello(name):
return render_template('hello.html',
title='欢迎页面',
name=name,
items=['Python', 'Flask', 'Jinja2'])
Jinja2 的语法接近 Python:
{{ var }}输出变量。{% if %}、{% for %}控制流程。- 模板文件默认放在
templates文件夹下,Flask 会自动查找。
Tip模板里不要写复杂的业务逻辑。数据整理和计算应该在视图函数里完成,模板只负责展示。
静态文件
CSS、JavaScript、图片等静态文件放到 static 文件夹:
<link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">
url_for('static', filename='...') 会自动生成正确的 URL,不怕路径变动。
小结
- WSGI 是 Python Web 框架和服务器的标准桥梁,理解它有助于排查部署问题。
- Flask 上手极快,路由、请求处理、模板渲染几行代码就能跑通。
- 开发时用
app.run(debug=True),生产环境务必换 Gunicorn 等专业服务器。
来源:参考了 liaoxuefeng「22. Web开发/22.3. WSGI接口/22.4. 使用Web框架/22.5. 使用模板」等,改写后所得。