flask代码
时间: 2023-07-02 08:24:37 浏览: 42
好的,下面是一个简单的 Flask Web 应用程序的代码示例:
```python
from flask import Flask, render_template, request
app = Flask(__name__)
@app.route('/')
def index():
return render_template('index.html')
@app.route('/hello', methods=['POST'])
def hello():
name = request.form['name']
return render_template('hello.html', name=name)
if __name__ == '__main__':
app.run(debug=True)
```
这个 Flask 应用程序包含了两个路由,分别是 `/` 和 `/hello`。当用户访问 `/` 路由时,应用程序会渲染 `index.html` 模板并返回给用户;当用户提交 POST 请求到 `/hello` 路由时,应用程序会从表单中获取用户输入的姓名,然后渲染 `hello.html` 模板并返回给用户。
其中,`index.html` 模板的代码如下:
```html
<!DOCTYPE html>
<html>
<head>
<title>Flask Example</title>
</head>
<body>
<h1>Hello, World!</h1>
<form action="/hello" method="POST">
<label for="name">What's your name?</label>
<input type="text" id="name" name="name">
<button type="submit">Submit</button>
</form>
</body>
</html>
```
`hello.html` 模板的代码如下:
```html
<!DOCTYPE html>
<html>
<head>
<title>Hello, {{ name }}!</title>
</head>
<body>
<h1>Hello, {{ name }}!</h1>
</body>
</html>
```
这个 Flask 应用程序非常简单,但它演示了如何使用 Flask 来创建 Web 应用程序,并使用模板和表单来处理用户输入。您可以根据自己的需要扩展这个应用程序,添加更多的路由、模板和功能。