Flask 从路由到模板:做一个迷你站点

Flask 轻量、好上手,很适合把 Python 能力接到 Web 上。本文从路由、请求、模板三块搭一个迷你站点骨架。

最小应用

from flask import Flask, render_template, request, redirect, url_for

app = Flask(__name__)

@app.get("/")
def index():
    return render_template("index.html", title="首页")

@app.route("/hello/<name>")
def hello(name: str):
    return f"你好,{name}!"

@app.post("/search")
def search():
    q = request.form.get("q", "").strip()
    return render_template("search.html", q=q)

if __name__ == "__main__":
    app.run(debug=True, port=5000)

模板继承

{# templates/base.html #}
<!doctype html>
<title>{% block title %}站点{% endblock %}</title>
<body>
  <nav><a href="{{ url_for('index') }}">首页</a></nav>
  {% block content %}{% endblock %}
</body>
{# templates/index.html #}
{% extends "base.html" %}
{% block title %}首页{% endblock %}
{% block content %}
<h1>欢迎</h1>
{% endblock %}

项目结构建议

myapp/
  app.py
  templates/
  static/
  requirements.txt

下一步

  1. 把业务拆成 Blueprint(用户、文章、后台)
  2. 用 Flask-Session / JWT 做登录态
  3. 配置与密钥走环境变量

先跑通「页面能开、表单能交、模板能复用」,再谈框架对比。

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注