匿名投票系统代码实现
时间: 2023-08-10 16:05:58 浏览: 73
以下是一个简单的匿名投票系统代码实现,使用 Python 和 Flask 框架:
1. 安装 Flask
```bash
pip install Flask
```
2. 创建一个 Python 文件,例如 app.py,编写代码如下:
```python
from flask import Flask, render_template, request, redirect
import csv
app = Flask(__name__)
@app.route("/")
def index():
return render_template("index.html")
@app.route("/vote", methods=["POST"])
def vote():
name = request.form.get("name")
choice = request.form.get("choice")
with open("votes.csv", "a", newline="") as file:
writer = csv.writer(file)
writer.writerow([name, choice])
return redirect("/results")
@app.route("/results")
def results():
options = ["Option A", "Option B", "Option C"]
counts = [0, 0, 0]
with open("votes.csv", "r") as file:
reader = csv.reader(file)
for row in reader:
if row[1] == "Option A":
counts[0] += 1
elif row[1] == "Option B":
counts[1] += 1
elif row[1] == "Option C":
counts[2] += 1
return render_template("results.html", options=options, counts=counts)
if __name__ == "__main__":
app.run(debug=True)
```
3. 创建 HTML 模板文件,例如 index.html 和 results.html,编写代码如下:
index.html:
```html
<!DOCTYPE html>
<html>
<head>
<title>Vote</title>
</head>
<body>
<h1>Vote</h1>
<form action="/vote" method="POST">
<label for="name">Name:</label>
<input type="text" id="name" name="name"><br><br>
<label for="choice">Choice:</label>
<select id="choice" name="choice">
<option value="Option A">Option A</option>
<option value="Option B">Option B</option>
<option value="Option C">Option C</option>
</select><br><br>
<input type="submit" value="Vote">
</form>
</body>
</html>
```
results.html:
```html
<!DOCTYPE html>
<html>
<head>
<title>Results</title>
</head>
<body>
<h1>Results</h1>
<table>
<tr>
<th>Option</th>
<th>Count</th>
</tr>
{% for option, count in zip(options, counts) %}
<tr>
<td>{{ option }}</td>
<td>{{ count }}</td>
</tr>
{% endfor %}
</table>
</body>
</html>
```
4. 运行应用程序
在命令行中使用以下命令运行应用程序:
```bash
python app.py
```
然后在浏览器中访问 http://localhost:5000/,即可进行匿名投票并查看结果。投票数据将保存在 votes.csv 文件中。