Python中的Flask深入认知&搭建前端页面?

打印 上一主题 下一主题

主题 862|帖子 862|积分 2586

一、Flask 的介绍

1. 什么是Flask?

Flask 是一个轻量级的 Python Web 框架,因其简单易用、灵活性高而广受接待。它得当快速开辟小型应用,也可以通过扩展支持复杂的功能需求。可以联合 HTML、CSS 和 JavaScript 实现丰富的交互功能。
2. 核心功能

2.1 路由(Routing)

功能:将 URL 映射到对应的处置惩罚函数。
实现:使用装饰器 @app.route 界说路由。
示例:
  1. from flask import Flask
  2. app = Flask(__name__)
  3. @app.route('/')
  4. def home():
  5.     return "Welcome to the Home Page!"
  6. @app.route('/about')
  7. def about():
  8.     return "This is the About Page."
  9. if __name__ == '__main__':
  10.     app.run(debug=True)
复制代码
2.2 请求与响应(Request and Response)

功能:处置惩罚 HTTP 请求并返反响应。
常用对象:
request:获取请求数据(如查询参数、表单数据、JSON 数据等)。
response:自界说响应内容和状态码。
示例:
  1. from flask import Flask, request, jsonify
  2. app = Flask(__name__)
  3. @app.route('/greet', methods=['GET'])
  4. def greet():
  5.     name = request.args.get('name', 'Guest')  # 获取查询参数
  6.     return f"Hello, {name}!"
  7. @app.route('/post', methods=['POST'])
  8. def post_data():
  9.     data = request.json  # 获取 JSON 数据
  10.     return jsonify({"received": data}), 201  # 返回 JSON 响应
  11. if __name__ == '__main__':
  12.     app.run(debug=True)
复制代码
2.3 模板渲染(Template Rendering)

功能:使用 Jinja2 模板引擎动态天生 HTML 页面。
实现:通过 render_template 函数加载模板文件。
示例:
  1. from flask import Flask, render_template
  2. app = Flask(__name__)
  3. @app.route('/')
  4. def home():
  5.     return render_template('index.html', title="Home Page", message="Welcome!")
  6. if __name__ == '__main__':
  7.     app.run(debug=True)
复制代码
模板文件 templates/index.html:
  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4.     <title>{{ title }}</title>
  5. </head>
  6. <body>
  7.     <h1>{{ message }}</h1>
  8. </body>
  9. </html>
复制代码
2.4 静态文件(Static Files)

功能:提供静态资源(如 CSS、JavaScript、图片等)。
路径:默认存放在 static/ 文件夹中。
示例:
  1. <link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">
复制代码
2.5 会话管理(Session Management)

功能:在客户端存储少量数据(如用户登录状态)。
实现:使用 session 对象,基于加密签名的 Cookie。
示例:
  1. from flask import Flask, session, redirect, url_for
  2. app = Flask(__name__)
  3. app.secret_key = 'your_secret_key'  # 设置密钥
  4. @app.route('/login')
  5. def login():
  6.     session['user'] = 'Alice'
  7.     return "Logged in as Alice"
  8. @app.route('/logout')
  9. def logout():
  10.     session.pop('user', None)
  11.     return "Logged out"
  12. @app.route('/profile')
  13. def profile():
  14.     user = session.get('user', 'Guest')
  15.     return f"Profile of {user}"
  16. if __name__ == '__main__':
  17.     app.run(debug=True)
复制代码
2.6 扩展功能

Flask 本身是轻量级的,但通过扩展可以支持更多功能。
(1) 数据库集成
SQLAlchemy:ORM 工具,用于操作关系型数据库。
示例:
  1. from flask import Flask
  2. from flask_sqlalchemy import SQLAlchemy
  3. app = Flask(__name__)
  4. app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///test.db'
  5. db = SQLAlchemy(app)
  6. class User(db.Model):
  7.     id = db.Column(db.Integer, primary_key=True)
  8.     username = db.Column(db.String(80), unique=True, nullable=False)
  9. @app.route('/')
  10. def home():
  11.     users = User.query.all()
  12.     return f"Users: {[u.username for u in users]}"
  13. if __name__ == '__main__':
  14.     db.create_all()  # 创建表
  15.     app.run(debug=True)
复制代码
(2) 用户认证
Flask-Login:简化用户登录、登出和会话管理。
示例:
  1. from flask import Flask, redirect, url_for
  2. from flask_login import LoginManager, UserMixin, login_user, logout_user, login_required
  3. app = Flask(__name__)
  4. app.secret_key = 'your_secret_key'
  5. login_manager = LoginManager(app)
  6. class User(UserMixin):
  7.     def __init__(self, id):
  8.         self.id = id
  9. @login_manager.user_loader
  10. def load_user(user_id):
  11.     return User(user_id)
  12. @app.route('/login')
  13. def login():
  14.     user = User(1)
  15.     login_user(user)
  16.     return "Logged in"
  17. @app.route('/logout')
  18. @login_required
  19. def logout():
  20.     logout_user()
  21.     return "Logged out"
  22. if __name__ == '__main__':
  23.     app.run(debug=True)
复制代码
(3) RESTful API
Flask-RESTful:构建 RESTful 风格的 API。
示例:
  1. from flask import Flask
  2. from flask_restful import Api, Resource
  3. app = Flask(__name__)
  4. api = Api(app)
  5. class HelloWorld(Resource):
  6.     def get(self):
  7.         return {"message": "Hello, World!"}
  8. api.add_resource(HelloWorld, '/')
  9. if __name__ == '__main__':
  10.     app.run(debug=True)
复制代码
(4) 表单验证
WTForms:用于验证和处置惩罚表单数据。
示例:
  1. from flask import Flask, render_template, request
  2. from wtforms import Form, StringField, validators
  3. app = Flask(__name__)
  4. class LoginForm(Form):
  5.     username = StringField('Username', [validators.Length(min=4, max=25)])
  6. @app.route('/', methods=['GET', 'POST'])
  7. def login():
  8.     form = LoginForm(request.form)
  9.     if request.method == 'POST' and form.validate():
  10.         return f"Welcome, {form.username.data}!"
  11.     return render_template('login.html', form=form)
  12. if __name__ == '__main__':
  13.     app.run(debug=True)
复制代码
2.7 Flask 的优势

(1)简单易用


  • 代码简便,学习曲线平缓。
  • 得当快速原型开辟。
(2)高度灵活


  • 可根据需求选择扩展模块。
  • 不逼迫使用特定的工具或库。
(3)社区支持


  • 丰富的第三方扩展(如 Flask-SQLAlchemy、Flask-WTF、Flask-RESTful 等)。
  • 大量文档和教程。
二、使用 Flask 搭建前端页面

1. 详细教程—核心步调

1.1 安装 Flask

起首,确保安装了 Flask:
  1. pip install flask
复制代码
1.2 项目结构


app.py # 用来存放主程序文件
templates/ # 用来存放 HTML 文件
static/ # 用来存放静态资源(CSS、JS、图片等)
1.3 编写主程序 app.py

  1. from flask import Flask, render_template
  2. app = Flask(__name__)
  3. # 定义路由
  4. @app.route('/')
  5. def home():
  6.     return render_template('index.html')
  7. if __name__ == '__main__':
  8.     app.run(debug=True)
复制代码
render_template 函数用于渲染 HTML 页面。
debug=True 开启调试模式,方便开辟。
1.4 编写前端页面 templates/index.html

  1. <!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') }}">
  2. </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

  1. body {
  2.     font-family: Arial, sans-serif;
  3.     background-color: #f4f4f9;
  4.     margin: 0;
  5.     padding: 0;
  6.     display: flex;
  7.     justify-content: center;
  8.     align-items: center;
  9.     height: 100vh;
  10. }
  11. .container {
  12.     text-align: center;
  13.     background: #fff;
  14.     padding: 20px;
  15.     border-radius: 8px;
  16.     box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
  17. }
  18. button {
  19.     padding: 10px 20px;
  20.     background-color: #007bff;
  21.     color: white;
  22.     border: none;
  23.     border-radius: 4px;
  24.     cursor: pointer;
  25. }
  26. button:hover {
  27.     background-color: #0056b3;
  28. }
复制代码
1.6 编写脚本文件 static/script.js

  1. document.getElementById('clickMe').addEventListener('click', function() {
  2.     alert('Button clicked! This is JavaScript in action.');
  3. });
复制代码
1.7 运行应用

在pycharm中运行或者在终端中运行以下下令启动 Flask 应用:
  1. python app.py
复制代码
1.8 结果

打开欣赏器,访问 http://127.0.0.1:5000/,即可看到你的前端页面。
![在这里插入图片形貌](https://i-blog.csdnimg.cn/direct/2f7c44e6129244369ef1d1cf04fd5209.png

2. 拓展

如果你需要更复杂的功能,可以选择其它更高级的前端搭建框架。

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

x
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

天津储鑫盛钢材现货供应商

金牌会员
这个人很懒什么都没写!

标签云

快速回复 返回顶部 返回列表