用一个Flask 写两个网页
时间: 2023-09-26 11:06:47 浏览: 54
当你使用 Flask 框架开发应用程序时,你可以根据需要编写多个路由函数,来为应用程序定义多个网页。下面是一个示例代码,展示如何在 Flask 中编写两个网页:
```python
from flask import Flask, render_template
app = Flask(__name__)
@app.route('/')
def index():
return render_template('index.html')
@app.route('/about')
def about():
return render_template('about.html')
if __name__ == '__main__':
app.run(debug=True)
```
在这个代码中,我们定义了两个路由函数,一个对应根目录 `/`,另一个对应 `/about`。当用户访问这两个网页时,Flask 框架会自动调用对应的路由函数,并返回相应的 HTML 内容。
你需要在 `templates` 目录下编写两个 HTML 模板文件 `index.html` 和 `about.html`,来渲染这两个网页的内容。在这两个模板文件中,你可以添加你需要的 HTML 元素和样式,以及 Flask 模板语言的代码来动态生成网页内容。
启动应用后,你可以在浏览器中访问 `http://127.0.0.1:5000/` 和 `http://127.0.0.1:5000/about` 来查看这两个网页的内容。
相关问题
flask框架中一个网页两个路由
在 Flask 中,一个网页可以拥有多个路由,你可以通过 `@app.route` 装饰器来指定不同的路由。以下是一个示例代码,其中一个网页 `/hello` 拥有两个路由 `/` 和 `/world`:
```python
from flask import Flask
app = Flask(__name__)
@app.route('/hello')
@app.route('/')
def hello():
return 'Hello, World!'
@app.route('/hello/world')
def hello_world():
return 'Hello, World from /hello/world!'
if __name__ == '__main__':
app.run()
```
在上面的代码中,`@app.route('/hello')` 和 `@app.route('/')` 都指定了路由,它们都指向了 `hello()` 函数,因此当用户访问 `/hello` 或 `/` 时,都会返回 `Hello, World!`。另外,`@app.route('/hello/world')` 指定了一个新的路由 `/hello/world`,它指向了 `hello_world()` 函数,因此当用户访问 `/hello/world` 时,会返回 `Hello, World from /hello/world!`。
写一个flask界面
好的,下面是一个简单的 Flask 界面示例:
```python
from flask import Flask, render_template, request
app = Flask(__name__)
@app.route('/')
def index():
return render_template('index.html')
@app.route('/result', methods=['POST'])
def result():
name = request.form['name']
age = request.form['age']
return render_template('result.html', name=name, age=age)
if __name__ == '__main__':
app.run(debug=True)
```
该示例包含两个路由函数,一个用于渲染主页(`index()`),另一个用于处理表单提交并返回结果(`result()`)。在 `index.html` 模板中,我们创建了一个简单的表单,用户可以输入姓名和年龄信息。在 `result.html` 模板中,我们展示了用户提交的信息。
下面是 `index.html` 模板代码:
```html
<!DOCTYPE html>
<html>
<head>
<title>Flask Form Example</title>
</head>
<body>
<h1>Enter Your Information</h1>
<form method="POST" action="/result">
<label>Name:</label>
<input type="text" name="name" required>
<br><br>
<label>Age:</label>
<input type="text" name="age" required>
<br><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
```
下面是 `result.html` 模板代码:
```html
<!DOCTYPE html>
<html>
<head>
<title>Flask Form Example</title>
</head>
<body>
<h1>Thank You!</h1>
<p>Your name is {{ name }} and you are {{ age }} years old.</p>
</body>
</html>
```
运行该代码后,用户可以在网页上输入姓名和年龄信息,提交表单后会显示一个包含用户信息的页面。