帮我写具体的代码并告诉我实现过程
时间: 2024-03-26 11:35:35 浏览: 17
好的,下面是具体的代码实现过程:
1. 安装 Flask 框架
在命令行中输入以下命令来安装 Flask 框架:
```python
pip install flask
```
2. 创建 Flask 应用程序
在你的代码文件中,先引入 Flask 模块,然后创建一个 Flask 应用程序实例:
```python
from flask import Flask
app = Flask(__name__)
```
3. 创建 HTML 模板
在项目根目录下创建一个名为 `templates` 的文件夹,在该文件夹下创建一个名为 `index.html` 的文件,在该文件中添加以下代码:
```html
<!DOCTYPE html>
<html>
<head>
<title>Flask App</title>
</head>
<body>
<h1>Flask App</h1>
<p>Enter a number:</p>
<input type="text" id="input">
<br><br>
<button onclick="calculate()">Calculate</button>
<br><br>
<p>Result:</p>
<textarea id="output" rows="4" cols="50"></textarea>
<script>
function calculate() {
var input = document.getElementById("input").value;
fetch("/calculate?input=" + input)
.then(response => response.text())
.then(data => {
document.getElementById("output").value = data;
});
}
</script>
</body>
</html>
```
4. 创建视图函数
在你的代码文件中添加以下代码:
```python
@app.route("/")
def index():
return render_template("index.html")
@app.route("/calculate")
def calculate():
input = int(request.args.get("input"))
output = input + 2
return str(output)
```
这里假设您的代码文件名为 `app.py`。
5. 运行应用程序
在命令行中输入以下命令来运行应用程序:
```python
export FLASK_APP=app.py
flask run
```
在浏览器中打开 http://localhost:5000,您应该可以看到一个输入框和一个按钮。在输入框中输入一个数字,点击按钮后,您应该可以在输出框中看到输入数字加上 2 的结果。
希望这个例子对您有所帮助!如果您有任何问题,请随时问我。