在这篇博客中,我们将介绍如何使用 Flask 创建一个简单的 Web 计算器应用程序。Flask 是一个轻量级的 Python Web 框架,非常适合快速开发和原型设计。通过这个项目,你将学习到如何使用 Flask 构建 Web 应用程序,以及如何处理用户输入和显示结果。
环境准备
首先,确保你已经安装了 Flask。你可以使用以下命令安装 Flask:
pip install Flask
创建 Flask 应用程序
步骤 1:创建应用实例
from flask import Flask, render_template, request
app = Flask(__name__)
解析:
from flask import Flask, render_template, request
:导入 Flask 框架及其相关模块。app = Flask(__name__)
:创建一个 Flask 应用实例,__name__
变量表示当前模块的名称。
步骤 2:定义根路由
@app.route('/')
def index():
return render_template('index.html')
解析:
@app.route('/')
:定义根路由,当用户访问根 URL (/
) 时,调用index()
函数。def index(): return render_template('index.html')
:index()
函数返回index.html
模板。
步骤 3:定义计算路由
@app.route('/calculate', methods=['POST'])
def calculate():
try:
expression = request.form['expression']
result = eval(expression)
return render_template('index.html', result=result, expression=expression)
except Exception as e:
return render_template('index.html', result='错误', expression=expression)
解析:
@app.route('/calculate', methods=['POST'])
:定义处理计算请求的路由,使用 POST 方法。expression = request.form['expression']
:获取用户输入的表达式。result = eval(expression)
:计算表达式的结果。return render_template('index.html', result=result, expression=expression)
:返回index.html
模板,并传递计算结果和表达式。except Exception as e: return render_template('index.html', result='错误', expression=expression)
:如果计算过程中出现错误,返回错误信息。
步骤 4:运行应用
if __name__ == '__main__':
app.run(debug=True)
解析:
if __name__ == '__main__': app.run(debug=True)
:以调试模式运行应用。
创建 HTML 模板
步骤 1:HTML 头部
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Flask 计算器</title>
<style>
body {
font-family: Arial, sans-serif;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
margin: 0;
}
.calculator {
border: 1px solid #ccc;
padding: 20px;
border-radius: 5px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}
.display {
width: 100%;
padding: 10px;
margin-bottom: 10px;
font-size: 1.2em;
text-align: right;
}
.buttons {
display: grid;
grid-template-columns: repeat(4, 1fr);
gap: 10px;
}
.buttons button {
padding: 20px;
font-size: 1.2em;
cursor: pointer;
}
</style>
</head>
解析:
<!DOCTYPE html>
:声明文档类型为 HTML5。<html lang="en">
:定义 HTML 文档的语言为英语。<head>
:包含文档的元数据。<meta charset="UTF-8">
:设置文档的字符编码为 UTF-8。<title>Flask 计算器</title>
:设置网页标题。<style>
:包含 CSS 样式,用于美化计算器界面。
步骤 2:HTML 主体
<body>
<div class="calculator">
<form method="post" action="/calculate">
<input type="text" name="expression" class="display" value="{{ expression }}" readonly>
<div class="buttons">
<button type="button" onclick="appendToExpression('7')">7</button>
<button type="button" onclick="appendToExpression('8')">8</button>
<button type="button" onclick="appendToExpression('9')">9</button>
<button type="button" onclick="appendToExpression('/')">/</button>
<button type="button" onclick="appendToExpression('4')">4</button>
<button type="button" onclick="appendToExpression('5')">5</button>
<button type="button" onclick="appendToExpression('6')">6</button>
<button type="button" onclick="appendToExpression('*')">*</button>
<button type="button" onclick="appendToExpression('1')">1</button>
<button type="button" onclick="appendToExpression('2')">2</button>
<button type="button" onclick="appendToExpression('3')">3</button>
<button type="button" onclick="appendToExpression('-')">-</button>
<button type="button" onclick="appendToExpression('0')">0</button>
<button type="button" onclick="appendToExpression('.')">.</button>
<button type="submit">=</button>
<button type="button" onclick="appendToExpression('+')">+</button>
</div>
</form>
{% if result is not none %}
<div class="result">
<h2>结果: {{ result }}</h2>
</div>
{% endif %}
</div>
<script>
function appendToExpression(value) {
const display = document.querySelector('.display');
display.value += value;
}
</script>
</body>
</html>
解析:
<body>
:包含网页的主体内容。<div class="calculator">
:定义计算器的容器。<form method="post" action="/calculate">
:定义表单,使用 POST 方法提交数据到/calculate
路由。<input type="text" name="expression" class="display" value="{{ expression }}" readonly>
:定义显示屏,显示用户输入的表达式。<div class="buttons">
:定义按钮容器,使用 CSS 网格布局排列按钮。<button type="button" onclick="appendToExpression('7')">7</button>
:定义按钮,点击按钮时调用appendToExpression('7')
函数,将数字 7 追加到显示屏。<script>
:包含 JavaScript 代码,用于处理按钮点击事件。
运行 Flask 应用程序
然后在浏览器中访问 http://127.0.0.1:5000/
,你将看到一个简单的计算器界面。
完整代码
Python
from flask import Flask, render_template, request
app = Flask(__name__)
@app.route('/')
def index():
return render_template('index.html')
@app.route('/calculate', methods=['POST'])
def calculate():
try:
expression = request.form['expression']
result = eval(expression)
return render_template('index.html', result=result, expression=expression)
except Exception as e:
return render_template('index.html', result='错误', expression=expression)
if __name__ == '__main__':
app.run(debug=True)
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Flask 计算器</title>
<style>
body {
font-family: Arial, sans-serif;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
margin: 0;
}
.calculator {
border: 1px solid #ccc;
padding: 20px;
border-radius: 5px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}
.display {
width: 100%;
padding: 10px;
margin-bottom: 10px;
font-size: 1.2em;
text-align: right;
}
.buttons {
display: grid;
grid-template-columns: repeat(4, 1fr);
gap: 10px;
}
.buttons button {
padding: 20px;
font-size: 1.2em;
cursor: pointer;
}
</style>
</head>
<body>
<div class="calculator">
<form method="post" action="/calculate">
<input type="text" name="expression" class="display" value="{{ expression }}" readonly>
<div class="buttons">
<button type="button" onclick="appendToExpression('7')">7</button>
<button type="button" onclick="appendToExpression('8')">8</button>
<button type="button" onclick="appendToExpression('9')">9</button>
<button type="button" onclick="appendToExpression('/')">/</button>
<button type="button" onclick="appendToExpression('4')">4</button>
<button type="button" onclick="appendToExpression('5')">5</button>
<button type="button" onclick="appendToExpression('6')">6</button>
<button type="button" onclick="appendToExpression('*')">*</button>
<button type="button" onclick="appendToExpression('1')">1</button>
<button type="button" onclick="appendToExpression('2')">2</button>
<button type="button" onclick="appendToExpression('3')">3</button>
<button type="button" onclick="appendToExpression('-')">-</button>
<button type="button" onclick="appendToExpression('0')">0</button>
<button type="button" onclick="appendToExpression('.')">.</button>
<button type="submit">=</button>
<button type="button" onclick="appendToExpression('+')">+</button>
</div>
</form>
{% if result is not none %}
<div class="result">
<h2>结果: {{ result }}</h2>
</div>
{% endif %}
</div>
<script>
function appendToExpression(value) {
const display = document.querySelector('.display');
display.value += value;
}
</script>
</body>
</html>
这个 HTML 模板定义了计算器的界面,包括显示屏和按钮。我们使用了简单的 CSS 样式来美化界面,并使用 JavaScript 处理按钮点击事件,将输入值追加到显示屏。
运行 Flask 应用程序
效果图:
相关类型推荐
- Flask 官方文档
- Flask Mega-Tutorial
- Flask 入门教程
其他文章推荐
- 使用 Python 指定内容 爬取百度引擎搜索结果-优快云博客
- 90道 编程题挑战:从基础到高级项目-优快云博客
- 使用 Python 指定内容 爬取百度引擎搜索结果-优快云博客
- 使用Python和Selenium爬取QQ新闻热榜-优快云博客
- 使用Python 和 Selenium 实现 优快云 文章 质量分数查询 附源码-优快云博客
总结
在这个项目中,你学习了以下内容:
- Flask 框架:你了解了如何使用 Flask 框架来构建一个简单的 Web 应用程序。
- 路由和视图函数:你学习了如何定义路由和视图函数来处理用户请求和返回响应。
- 模板渲染:你学习了如何使用 Jinja2 模板引擎来渲染 HTML 页面,并动态显示数据。
- 表单处理:你了解了如何处理用户输入的数据,并在服务器端进行验证和处理。
- 静态文件:你学习了如何管理和提供静态文件,如 CSS、JavaScript 和图像。
结论
通过这个项目,你学习了如何使用 Flask 构建一个简单的 Web 应用程序,并了解了如何处理用户输入和显示结果,欢迎在评论区留言。继续探索和学习,祝你在深度学习的旅程中取得更多的成果!🚀
希望这个博客对你有所帮助 如果你有任何问题或需要进一步的指导,请随时提问。继续加油!🚀