【后端】Flask

长期更新,建议关注收藏点赞!


实例1

Jinja2 是 Flask 和 Django 使用的 模板引擎,它允许你在 HTML 中嵌入 Python 代码,以动态生成页面内容。Jinja2 语法类似于 Django 模板,并支持变量、条件判断、循环、过滤器等。

python 复制代码
from flask import Flask, render_template

app = Flask(__name__)

#@app.route('/') 是路由装饰器,定义访问时执行的函数,这里即index。
@app.route('/') 
def index():
    return render_template("index.html") 
#render_template()是Flask提供的函数用于加载HTML模板文件(存放在templates 目录下)。
#render_template("index.html") 让 Flask 查找 templates/index.html 并返回给浏览器。

return render_template("index.html", title="首页", message="欢迎来到 Flask") #配合.html文件
'''
<head>
    <title>{{ title }}</title>
</head>
<body>
    <h1>{{ message }}</h1>
</body>
'''

@app.route('/')
def index():
    users = ["Alice", "Bob", "Charlie"]
    return render_template("index.html", users=users)
'''Jinja2 模板语法
{% ... %}:表示 Jinja2 代码块,里面可以写 Python 代码,比如 for 循环、if 判断等。{% endfor %}结束循环

<ul>
    {% for user in users %}
        <li>{{ user }}</li>
    {% endfor %}
</ul>
'''

if __name__ == "__main__":
    app.run(debug=True)  # 启动 Flask 服务器
相关推荐
知行合一。。。1 天前
Python--04--数据容器(总结)
开发语言·python
架构师老Y1 天前
008、容器化部署:Docker与Python应用打包
python·容器·架构
lifewange1 天前
pytest-类中测试方法、多文件批量执行
开发语言·python·pytest
GreenTea1 天前
一文搞懂Harness Engineering与Meta-Harness
前端·人工智能·后端
pluvium271 天前
记对 xonsh shell 的使用, 脚本编写, 迁移及调优
linux·python·shell·xonsh
2401_827499991 天前
python项目实战09-AI智能伴侣(ai_partner_5-6)
开发语言·python
PD我是你的真爱粉1 天前
MCP 协议详解:从架构、工作流到 Python 技术栈落地
开发语言·python·架构
ZhengEnCi1 天前
P2G-Python字符串方法完全指南-split、join、strip、replace的Python编程利器
python
是小蟹呀^1 天前
【总结】LangChain中工具的使用
python·langchain·agent·tool
宝贝儿好1 天前
【LLM】第二章:文本表示:词袋模型、小案例:基于文本的推荐系统(酒店推荐)
人工智能·python·深度学习·神经网络·自然语言处理·机器人·语音识别