使用第三方库,实现简单网站的制作,要求能够接收用户姓名,年龄和性别信息,并在页面上显示出来。
时间: 2024-06-09 20:08:18 浏览: 4
可以使用 Flask 库来实现简单网站的制作,以下是一个示例代码:
```python
from flask import Flask, request, render_template
app = Flask(__name__)
@app.route('/', methods=['GET', 'POST'])
def index():
if request.method == 'POST':
name = request.form['name']
age = request.form['age']
gender = request.form['gender']
return render_template('result.html', name=name, age=age, gender=gender)
return render_template('index.html')
if __name__ == '__main__':
app.run()
```
在这个示例代码中,我们使用了 Flask 库来创建一个名为 `app` 的 Web 应用。在 `/` 这个路由上,我们处理了 GET 和 POST 两种请求。当用户通过 GET 请求访问时,我们渲染 `index.html` 模板并返回。当用户通过 POST 请求提交表单时,我们从表单中获取用户输入的姓名、年龄和性别信息,并将这些信息传递给 `result.html` 模板进行渲染。
接下来,我们需要创建两个 HTML 模板文件 `index.html` 和 `result.html`,分别用于展示表单和展示用户信息。以下是示例代码:
`index.html`:
```html
<!DOCTYPE html>
<html>
<head>
<title>Simple Web Form</title>
</head>
<body>
<h1>Simple Web Form</h1>
<form method="post" action="/">
<label for="name">Name:</label>
<input type="text" name="name" id="name"><br><br>
<label for="age">Age:</label>
<input type="text" name="age" id="age"><br><br>
<label for="gender">Gender:</label>
<input type="radio" name="gender" id="male" value="male">
<label for="male">Male</label>
<input type="radio" name="gender" id="female" value="female">
<label for="female">Female</label><br><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
```
`result.html`:
```html
<!DOCTYPE html>
<html>
<head>
<title>Simple Web Form Result</title>
</head>
<body>
<h1>Simple Web Form Result</h1>
<p>Name: {{ name }}</p>
<p>Age: {{ age }}</p>
<p>Gender: {{ gender }}</p>
</body>
</html>
```
在这两个模板中,我们使用了 Flask 提供的模板引擎 Jinja2 来渲染动态内容。在 `index.html` 模板中,我们创建了一个简单的表单,其中包含了三个输入框和一个提交按钮。在 `result.html` 模板中,我们展示了用户提交的信息。
最后,我们可以通过运行上面的 Python 代码来启动 Web 应用,并在浏览器中访问 `http://localhost:5000/` 来访问我们的网站。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)