练习到底:使用 Flask 框架快速构建 Web 应用程序
Python 在 1995 年(20 世纪 90 年代初)首次用于 Web 开发,当时使用 CGI 脚本编写动态网页。 Django 框架于 2004 年发布,是一个高度模块化的框架,提供了许多开箱即用的功能,使 Web 开发变得更容易、更快。 Flask 框架于 2010 年发布,是一个轻量级框架,提供的默认功能较少,但也更加灵活,允许开发人员根据需要添加或删除功能。
技术栈
- Python 3.6+
- Flask 1.1.2
- HTML、CSS、JavaScript
- MySQL Flask 是什么?
Flask 是一个基于 Python 的轻量级 Web 框架。它的特点是易于使用和极大的灵活性。 Flask框架能够快速构建Web应用程序,是一个不错的选择。 Flask框架的核心思想是WSGI(Web Server Gateway Interface),它定义了Web服务器和Web应用程序之间的通信协议。
1.1 Flask 的优点
- 易用:Flask 框架的 API 简单易用,开发者可以快速上手。 MVC 设计模式。
- 高灵活性:Flask框架具有高度可扩展性,可以根据实际需求进行扩展。
- 轻量级:Flask框架代码量小,运行速度快。
- 文档全面:Flask框架的文档非常详细,可以让开发者轻松找到自己需要的信息。
1.2 Flask 的缺点
- 轻:Flask 本体的轻特性也是其缺点之一。它的功能比较有限,需要你自己扩展。
- 不适合大型应用:Flask框架适合小型应用,大型应用可能会遇到性能瓶颈。你现在可以考虑Django。
1.3 Flask 基本组件
Flask 框架由以下基本组件组成:
- 路由:定义 URL 和视图函数之间的映射关系。
- 查看功能:处理请求并返回响应。
- 模板:创建 HTML 页面。
- 表单:处理用户提交的信息。
- 扩展:实现Flask框架的扩展功能。
2。基本用法
2.1 安装 Flask
在开始使用 Flask 之前,您需要安装 Flask。可以用pip安装:
pip install Flask
2.2 Hello World
下面是一个简单的例子,说明如何使用Flask框架打印“Hello World”。新建一个app.py文件,输入以下内容。 在 Linux 上运行:export FLASK_APP=app.pyflask run打开浏览器并转到 http://127.0.0.1:5000/。 如果在windows中执行: set FLASK_APP=app.pyflask run
from flask import Flask app = Flask(__name__) @app.route('/') def hello_world(): return 'Hello, World!'
2.3 路由和查看功能
在Flask中,路由和视图密切相关。路由用于映射 URL 以查看处理请求和返回响应的函数。为了实现路由和查看功能,我们可以使用 Flask 中的
@app.route
装饰器。下面是一个简单的例子:from flask import Flask app = Flask(__name__) @app.route('/') def index(): return 'This is the index page.' @app.route('/hello') def hello(): return 'Hello, World!'
@app.route('/')
和@app.route('/hello')
分别定义了两条路由,♽index () 和hello()
是两个视图函数。2.4 模板
模板是在 Flask 中创建 HTML 页面的一种方法。 Flask 支持多种模板引擎,包括 Jinja2、Mako、Tenjin 等。在本文中,我们将使用 Jinja2 作为模板引擎。
以下是一个简单的示例,展示如何使用模板创建 HTML 页面:
from flask import Flask, render_template app = Flask(__name__) @app.route('/') def index(): return render_template('index.html', title='Home') @app.route('/hello') def hello(): return render_template('hello.html', name='Flask')
render_template()
该函数用于渲染模板。第一个参数指定模板名称,第二个参数是模板名称。使用的变量。2.5 静态文件
静态文件包括CSS、JavaScript、图片等。在Flask中,可以使用
url_for()
函数生成静态文件URL。以下是一个简单的示例:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>{{ title }}</title> <link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}"> </head> <body> <h1>{{ title }}</h1> <p>Hello, Flask!</p> </body> </html>
url_for('static', filename='style.css')
创建静态文件 URL。
2.6 表单
表单是在线应用程序中常用的交互方式。在 Flask 中,可以使用
request
对象来获取用户提交的表单数据。下面是一个简单的例子:
from flask import Flask, request app = Flask(__name__) @app.route('/login', methods=['GET', 'POST']) def login(): if request.method == 'POST': username = request.form['username'] password = request.form['password'] if username == 'admin' and password == 'password': return 'Login success!' else: return 'Invalid username or password.' else: return ''' <form method="post"> <label>Username:</label> <input type="text" name="username"> <label>Password:</label> <input type="password" name="password"> <input type="submit" value="Login"> </form> '''
request.form
可以获取POST请求发送的表单数据。3。案例研究:构建一个 Todo(待办事项)应用程序
接下来,我们将通过一个案例研究来演示如何使用 Flask 框架构建一个 Todo 应用程序。
3.1 数据库设计
首先我们需要设计数据库。在本文中,我们使用MySQL作为数据库。以下是数据库设计:
CREATE TABLE `todos` ( `id` int(11) NOT NULL AUTO_INCREMENT, `title` varchar(255) NOT NULL, `completed` tinyint(1) NOT NULL DEFAULT '0', PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
3.2 后台实现
接下来实现后台操作:
from flask import Flask, render_template, request, redirect, url_for import pymysql.cursors app = Flask(__name__) app.config['SECRET_KEY'] = 'secret' connection = pymysql.connect( host='localhost', user='root', password='password', db='todo', charset='utf8mb4', cursorclass=pymysql.cursors.DictCursor ) @app.route('/') def index(): with connection.cursor() as cursor: cursor.execute('SELECT * FROM `todos`') todos = cursor.fetchall() return render_template('index.html', todos=todos) @app.route('/add', methods=['POST']) def add(): title = request.form['title'] with connection.cursor() as cursor: cursor.execute('INSERT INTO `todos` (`title`) VALUES (%s)', title) connection.commit() return redirect(url_for('index')) @app.route('/toggle/<int:todo_id>', methods=['POST']) def toggle(todo_id): with connection.cursor() as cursor: cursor.execute('SELECT `completed` FROM `todos` WHERE `id` = %s', todo_id) completed = cursor.fetchone()['completed'] cursor.execute('UPDATE `todos` SET `completed` = %s WHERE `id` = %s', (not completed, todo_id)) connection.commit() return redirect(url_for('index')) @app.route('/delete/<int:todo_id>', methods=['POST']) def delete(todo_id): with connection.cursor() as cursor: cursor.execute('DELETE FROM `todos` WHERE `id` = %s', todo_id) connection.commit() return redirect(url_for('index'))
分析:建立数据库连接,指定四个路由: /❀:显示所有任务。
/add
:添加任务。/切换/
:标记任务是否已完成。/删除/
:删除任务。 ?4。技术总结
今天我们演示了如何使用Flask框架进行Web开发,并实际开发了一个轻量级的Web应用程序。 Flask 是一个轻量级的 Python Web 框架。它易于使用且非常灵活,即使是初学者也能快速上手。
版权声明
本文仅代表作者观点,不代表Code前端网立场。
本文系作者Code前端网发表,如需转载,请注明页面地址。
发表评论:
◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。