一、Flask 的介绍
1. 什么是Flask?
Flask 是一个轻量级的 Python Web 框架,因其简单易用、灵活性高而广受接待。它得当快速开辟小型应用,也可以通过扩展支持复杂的功能需求。可以联合 HTML、CSS 和 JavaScript 实现丰富的交互功能。
2. 核心功能
2.1 路由(Routing)
功能:将 URL 映射到对应的处置惩罚函数。
实现:使用装饰器 @app.route 界说路由。
示例:
- from flask import Flask
- app = Flask(__name__)
- @app.route('/')
- def home():
- return "Welcome to the Home Page!"
- @app.route('/about')
- def about():
- return "This is the About Page."
- if __name__ == '__main__':
- app.run(debug=True)
复制代码 2.2 请求与响应(Request and Response)
功能:处置惩罚 HTTP 请求并返反响应。
常用对象:
request:获取请求数据(如查询参数、表单数据、JSON 数据等)。
response:自界说响应内容和状态码。
示例:
- from flask import Flask, request, jsonify
- app = Flask(__name__)
- @app.route('/greet', methods=['GET'])
- def greet():
- name = request.args.get('name', 'Guest') # 获取查询参数
- return f"Hello, {name}!"
- @app.route('/post', methods=['POST'])
- def post_data():
- data = request.json # 获取 JSON 数据
- return jsonify({"received": data}), 201 # 返回 JSON 响应
- if __name__ == '__main__':
- app.run(debug=True)
复制代码 2.3 模板渲染(Template Rendering)
功能:使用 Jinja2 模板引擎动态天生 HTML 页面。
实现:通过 render_template 函数加载模板文件。
示例:
- from flask import Flask, render_template
- app = Flask(__name__)
- @app.route('/')
- def home():
- return render_template('index.html', title="Home Page", message="Welcome!")
- if __name__ == '__main__':
- app.run(debug=True)
复制代码 模板文件 templates/index.html:
- <!DOCTYPE html>
- <html>
- <head>
- <title>{{ title }}</title>
- </head>
- <body>
- <h1>{{ message }}</h1>
- </body>
- </html>
复制代码 2.4 静态文件(Static Files)
功能:提供静态资源(如 CSS、JavaScript、图片等)。
路径:默认存放在 static/ 文件夹中。
示例:
- <link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">
复制代码 2.5 会话管理(Session Management)
功能:在客户端存储少量数据(如用户登录状态)。
实现:使用 session 对象,基于加密签名的 Cookie。
示例:
- from flask import Flask, session, redirect, url_for
- app = Flask(__name__)
- app.secret_key = 'your_secret_key' # 设置密钥
- @app.route('/login')
- def login():
- session['user'] = 'Alice'
- return "Logged in as Alice"
- @app.route('/logout')
- def logout():
- session.pop('user', None)
- return "Logged out"
- @app.route('/profile')
- def profile():
- user = session.get('user', 'Guest')
- return f"Profile of {user}"
- if __name__ == '__main__':
- app.run(debug=True)
复制代码 2.6 扩展功能
Flask 本身是轻量级的,但通过扩展可以支持更多功能。
(1) 数据库集成
SQLAlchemy:ORM 工具,用于操作关系型数据库。
示例:
- from flask import Flask
- from flask_sqlalchemy import SQLAlchemy
- app = Flask(__name__)
- app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///test.db'
- db = SQLAlchemy(app)
- class User(db.Model):
- id = db.Column(db.Integer, primary_key=True)
- username = db.Column(db.String(80), unique=True, nullable=False)
- @app.route('/')
- def home():
- users = User.query.all()
- return f"Users: {[u.username for u in users]}"
- if __name__ == '__main__':
- db.create_all() # 创建表
- app.run(debug=True)
复制代码 (2) 用户认证
Flask-Login:简化用户登录、登出和会话管理。
示例:
- from flask import Flask, redirect, url_for
- from flask_login import LoginManager, UserMixin, login_user, logout_user, login_required
- app = Flask(__name__)
- app.secret_key = 'your_secret_key'
- login_manager = LoginManager(app)
- class User(UserMixin):
- def __init__(self, id):
- self.id = id
- @login_manager.user_loader
- def load_user(user_id):
- return User(user_id)
- @app.route('/login')
- def login():
- user = User(1)
- login_user(user)
- return "Logged in"
- @app.route('/logout')
- @login_required
- def logout():
- logout_user()
- return "Logged out"
- if __name__ == '__main__':
- app.run(debug=True)
复制代码 (3) RESTful API
Flask-RESTful:构建 RESTful 风格的 API。
示例:
- from flask import Flask
- from flask_restful import Api, Resource
- app = Flask(__name__)
- api = Api(app)
- class HelloWorld(Resource):
- def get(self):
- return {"message": "Hello, World!"}
- api.add_resource(HelloWorld, '/')
- if __name__ == '__main__':
- app.run(debug=True)
复制代码 (4) 表单验证
WTForms:用于验证和处置惩罚表单数据。
示例:
- from flask import Flask, render_template, request
- from wtforms import Form, StringField, validators
- app = Flask(__name__)
- class LoginForm(Form):
- username = StringField('Username', [validators.Length(min=4, max=25)])
- @app.route('/', methods=['GET', 'POST'])
- def login():
- form = LoginForm(request.form)
- if request.method == 'POST' and form.validate():
- return f"Welcome, {form.username.data}!"
- return render_template('login.html', form=form)
- if __name__ == '__main__':
- app.run(debug=True)
复制代码 2.7 Flask 的优势
(1)简单易用
(2)高度灵活
- 可根据需求选择扩展模块。
- 不逼迫使用特定的工具或库。
(3)社区支持
- 丰富的第三方扩展(如 Flask-SQLAlchemy、Flask-WTF、Flask-RESTful 等)。
- 大量文档和教程。
二、使用 Flask 搭建前端页面
1. 详细教程—核心步调
1.1 安装 Flask
起首,确保安装了 Flask:
1.2 项目结构
app.py # 用来存放主程序文件
templates/ # 用来存放 HTML 文件
static/ # 用来存放静态资源(CSS、JS、图片等)
1.3 编写主程序 app.py
- from flask import Flask, render_template
- app = Flask(__name__)
- # 定义路由
- @app.route('/')
- def home():
- return render_template('index.html')
- if __name__ == '__main__':
- app.run(debug=True)
复制代码 render_template 函数用于渲染 HTML 页面。
debug=True 开启调试模式,方便开辟。
1.4 编写前端页面 templates/index.html
- <!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>My Flask App</title> <!-- 引入 CSS --> <link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">
- </head><body> <div class="container"> <h1>Hello, 兄弟们!</h1> <button id="clickMe">Click Me!</button> </div> <!-- 引入 JavaScript --> <script src="{{ url_for('static', filename='script.js') }}"></script></body></html>
复制代码 {{ url_for(‘static’, filename=‘…’) }} 是 Flask 提供的模板语法,用于动态天生静态资源路径。
1.5 编写样式文件 static/style.css
- body {
- font-family: Arial, sans-serif;
- background-color: #f4f4f9;
- margin: 0;
- padding: 0;
- display: flex;
- justify-content: center;
- align-items: center;
- height: 100vh;
- }
- .container {
- text-align: center;
- background: #fff;
- padding: 20px;
- border-radius: 8px;
- box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
- }
- button {
- padding: 10px 20px;
- background-color: #007bff;
- color: white;
- border: none;
- border-radius: 4px;
- cursor: pointer;
- }
- button:hover {
- background-color: #0056b3;
- }
复制代码 1.6 编写脚本文件 static/script.js
- document.getElementById('clickMe').addEventListener('click', function() {
- alert('Button clicked! This is JavaScript in action.');
- });
复制代码 1.7 运行应用
在pycharm中运行或者在终端中运行以下下令启动 Flask 应用:
1.8 结果
打开欣赏器,访问 http://127.0.0.1:5000/,即可看到你的前端页面。
![在这里插入图片形貌](https://i-blog.csdnimg.cn/direct/2f7c44e6129244369ef1d1cf04fd5209.png
2. 拓展
如果你需要更复杂的功能,可以选择其它更高级的前端搭建框架。
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。 |