Python学习计划——11.1使用Flask创建一个简单的Web应用

Flask是一个轻量级的Python Web框架,适合快速开发小型Web应用。它易于学习和使用,并且具有丰富的扩展功能。以下是Flask基本知识的详细讲解和一个可运行的Python案例。

  1. 安装Flask

首先,需要安装Flask。可以使用pip进行安装:

python 复制代码
pip install Flask
  1. 创建一个简单的Flask应用

一个简单的Flask应用包含一个或多个路由,每个路由处理特定的URL和HTTP方法。以下是一个基本的Flask应用示例:

示例:创建简单的Flask应用

python 复制代码
from flask import Flask

# 创建Flask应用
app = Flask(__name__)

# 定义路由和视图函数
@app.route('/')
def home():
    return "Hello, Flask!"

# 启动应用
if __name__ == '__main__':
    app.run(debug=True)

将上述代码保存为app.py,然后运行它:

bash 复制代码
python app.py

然后打开浏览器,访问http://127.0.0.1:5000/,你将看到以下文本:

python 复制代码
Hello, Flask!
  1. 添加更多路由和视图函数

可以为应用添加多个路由,每个路由对应不同的URL和视图函数。

示例:添加多个路由

python 复制代码
from flask import Flask

app = Flask(__name__)

@app.route('/')
def home():
    return "Hello, Flask!"

@app.route('/about')
def about():
    return "This is the About page."

@app.route('/user/<username>')
def user_profile(username):
    return f"Hello, {username}!"

if __name__ == '__main__':
    app.run(debug=True)

访问以下URL:

  • http://127.0.0.1:5000/:显示"Hello, Flask!"
  • http://127.0.0.1:5000/about:显示"This is the About page."
  • http://127.0.0.1:5000/user/John:显示"Hello, John!"
  1. 模板渲染

Flask使用Jinja2模板引擎,可以动态生成HTML页面。模板文件通常存放在名为templates的目录中。

示例:使用模板渲染HTML页面

首先,创建一个名为templates的目录,并在其中创建一个名为index.html的文件:

html 复制代码
<!-- templates/index.html -->
<!DOCTYPE html>
<html>
<head>
    <title>Flask App</title>
</head>
<body>
    <h1>Hello, {{ name }}!</h1>
</body>
</html>

然后修改Flask应用代码:

python 复制代码
from flask import Flask, render_template

app = Flask(__name__)

@app.route('/')
def home():
    return render_template('index.html', name="Flask")

@app.route('/about')
def about():
    return "This is the About page."

@app.route('/user/<username>')
def user_profile(username):
    return f"Hello, {username}!"

if __name__ == '__main__':
    app.run(debug=True)

访问http://127.0.0.1:5000/,你将看到渲染后的HTML页面:

python 复制代码
Hello, Flask!
  1. 处理表单数据

可以使用Flask处理表单提交的数据。下面是一个简单的示例,演示如何处理表单数据并进行响应。

示例:处理表单数据

首先,在templates目录中创建一个名为form.html的文件:

html 复制代码
<!-- templates/form.html -->
<!DOCTYPE html>
<html>
<head>
    <title>Form Example</title>
</head>
<body>
    <h1>Submit a Form</h1>
    <form method="POST" action="/submit">
        <label for="name">Name:</label>
        <input type="text" id="name" name="name">
        <button type="submit">Submit</button>
    </form>
</body>
</html>

然后修改Flask应用代码:

python 复制代码
from flask import Flask, render_template, request

app = Flask(__name__)

@app.route('/')
def home():
    return render_template('index.html', name="Flask")

@app.route('/about')
def about():
    return "This is the About page."

@app.route('/user/<username>')
def user_profile(username):
    return f"Hello, {username}!"

@app.route('/form')
def form():
    return render_template('form.html')

@app.route('/submit', methods=['POST'])
def submit():
    name = request.form['name']
    return f"Form submitted! Hello, {name}!"

if __name__ == '__main__':
    app.run(debug=True)

访问http://127.0.0.1:5000/form,填写表单并提交,你将看到提交后的响应:

css 复制代码
Form submitted! Hello, [name]!
  1. 可运行的Python案例

下面是一个完整的Python程序,演示了如何使用Flask创建一个简单的Web应用,包括路由、模板渲染和表单处理。

python 复制代码
from flask import Flask, render_template, request

app = Flask(__name__)

@app.route('/')
def home():
    return render_template('index.html', name="Flask")

@app.route('/about')
def about():
    return "This is the About page."

@app.route('/user/<username>')
def user_profile(username):
    return f"Hello, {username}!"

@app.route('/form')
def form():
    return render_template('form.html')

@app.route('/submit', methods=['POST'])
def submit():
    name = request.form['name']
    return f"Form submitted! Hello, {name}!"

if __name__ == '__main__':
    app.run(debug=True)

可以将上面的代码保存为app.py,并创建对应的模板文件(index.htmlform.html),然后运行程序。这个案例综合了Flask Web开发的基本知识,帮助你理解和掌握这些操作。继续加油,学习Python会越来越有趣和有用!

相关推荐
thginWalker1 小时前
18 继续学习
学习
梦幻精灵_cq1 小时前
《用餐》,午餐食堂即景小诗分享(手机/小视频/光盘/养生)
学习
Warren982 小时前
Appium学习笔记
android·windows·spring boot·笔记·后端·学习·appium
一尘之中2 小时前
在Python 2.7中安装SQLAlchemy的完整指南
开发语言·python·ai写作
彤银浦2 小时前
PHP学习笔记1
笔记·学习·php
电商数据girl2 小时前
Python 爬虫获得淘宝商品详情 数据【淘宝商品API】
大数据·开发语言·人工智能·爬虫·python·json·php
钢铁男儿2 小时前
Python 网络编程进阶:使用 SocketServer 模块构建 TCP 服务器与客户端
网络·python·tcp/ip
大模型真好玩3 小时前
深入浅出LangChain AI Agent智能体开发教程(十)—LangChain搭建数据分析智能助手
人工智能·python·mcp
七夜zippoe4 小时前
Python性能优化实战(三):给内存“减负“的实用指南
python·内存·优化
WSSWWWSSW9 小时前
Seaborn数据可视化实战:Seaborn数据可视化基础-从内置数据集到外部数据集的应用
python·信息可视化·数据分析·matplotlib·seaborn