博客导语
纯字符串返回无法满足Web开发需求,真实项目需要HTML页面渲染、静态资源(图片/JS/CSS)加载、接收前端参数、自定义响应格式。本文详解Flask模板语法、静态文件配置、完整请求参数获取、多种响应返回方式,覆盖前端交互核心场景。
一、Flask项目规范目录结构
Flask默认约定目录,无需手动配置,框架自动识别:
templates:存放HTML模板文件(必须同名)
static:存放静态文件(css/js/图片)
二、模板渲染实战(Jinja2模板)
Flask默认使用Jinja2模板引擎,支持变量渲染、循环、判断、模板继承,是前端页面动态渲染核心。
1. 基础模板渲染
templates/index.html 模板代码:
<!DOCTYPE html> <html> <body> <h1>欢迎{{ name }}使用Flask模板</h1> <p>年龄:{{ age }}</p> </body> </html>from flask import render_template @app.route("/index") def index(): # 向模板传递参数 return render_template("index.html", name="张三", age=20)2. 模板常用语法
<!-- 变量渲染 --> {{ msg }} <!-- 循环遍历 --> {% for item in list %} <li>{{ item }}</li> {% endfor %} <!-- 条件判断 --> {% if age > 18 %} <p>成年</p> {% else %} <p>未成年</p> {% endif %}三、静态文件使用
静态文件统一放入static文件夹,通过/static/路径访问,支持图片、样式、脚本引入。
<!-- 引入静态CSS/JS/图片 --> <link rel="stylesheet" href="/static/style.css"> <script src="/static/index.js"></script> <img src="/static/logo.png">四、请求对象:获取前端所有参数
通过request对象获取前端GET、POST、URL参数、请求头、文件等数据。
from flask import request @app.route("/get_info", methods=["GET", "POST"]) def get_info(): # 获取GET请求参数 name = request.args.get("name") # 获取POST表单参数 pwd = request.form.get("pwd") # 获取请求头 ua = request.headers.get("User-Agent") return f"姓名:{name},密码:{pwd}"五、多种响应返回方式
from flask import jsonify, redirect # 1. 返回普通文本 return "文本响应" # 2. 返回HTML页面 return render_template("index.html") # 3. 返回JSON数据(接口开发必备) return jsonify(code=200, msg="成功", data=[1,2,3]) # 4. 页面重定向 return redirect("/index")六、避坑总结
模板文件夹必须命名为templates,静态文件夹为static,默认不可修改
接收参数优先用get()方法,避免参数不存在导致程序报错
需要接收POST请求必须指定methods参数