以下是一个简单的基于 Flask 的在线投票应用示例,使用 Python 3。
首先,我们需要安装 Flask 和 Flask-WTF 扩展。在命令行中执行以下命令:
pip install flask flask-wtf
然后,我们可以创建一个 Flask 应用,包含以下几个路由和视图函数:
from flask import Flask, render_template, redirect, url_for, request
from flask_wtf import FlaskForm
from wtforms import StringField, FieldList, FormField, RadioField
from wtforms.validators import DataRequired
app = Flask(__name__)
app.secret_key = 'my-secret-key'
# 表单类:投票选项
class ChoiceForm(FlaskForm):
choice = StringField('Choice', validators=[DataRequired()])
# 表单类:投票主题
class PollForm(FlaskForm):
title = StringField('Title', validators=[DataRequired()])
choices = FieldList(FormField(ChoiceForm), min_entries=2)
# 表单类:投票选择
class VoteForm(FlaskForm):
choice = RadioField('Choice', validators=[DataRequired()])
# 路由:创建投票
@app.route('/create_poll', methods=['GET', 'POST'])
def create_poll():
form = PollForm()
if form.validate_on_submit():
# 将投票信息存入数据库
# ...
return redirect(url_for('view_poll', poll_id=1))
return render_template('create_poll.html', form=form)
# 路由:参与投票
@app.route('/poll/<int:poll_id>', methods=['GET', 'POST'])
def view_poll(poll_id):
# 从数据库获取投票信息
poll = {
'id': poll_id,
'title': 'What is your favorite color?',
'choices': [
{'id': 1, 'text': 'Red', 'votes': 3},
{'id': 2, 'text': 'Green', 'votes': 2},
{'id': 3, 'text': 'Blue', 'votes': 1},
]
}
form = VoteForm()
form.choice.choices = [(str(choice['id']), choice['text']) for choice in poll['choices']]
if form.validate_on_submit():
# 更新投票结果
# ...
return redirect(url_for('view_results', poll_id=poll_id))
return render_template('view_poll.html', poll=poll, form=form)
# 路由:查看投票结果
@app.route('/poll/<int:poll_id>/results')
def view_results(poll_id):
# 从数据库获取投票信息
poll = {
'id': poll_id,
'title': 'What is your favorite color?',
'choices': [
{'id': 1, 'text': 'Red', 'votes': 3},
{'id': 2, 'text': 'Green', 'votes': 2},
{'id': 3, 'text': 'Blue', 'votes': 1},
]
}
return render_template('view_results.html', poll=poll)
该应用使用 Flask-WTF 扩展来处理表单,包括创建投票表单、参与投票表单和查看投票结果页面。在创建投票时,用户需要输入投票主题和选项。在参与投票时,用户需要选择一个选项进行投票。在查看
投票结果时,用户可以看到每个选项的投票数。这些信息可以存储在数据库中,但为了简化示例,我们直接在代码中硬编码了投票信息。
接下来,我们需要创建三个 HTML 模板文件来渲染这些视图:create_poll.html
、view_poll.html
和 view_results.html
。这些模板文件使用 Jinja2 模板引擎,可以使用 Flask 的模板自动查找功能来自动加载。在应用根目录下创建 templates
文件夹,并在该文件夹中创建这些模板文件。
create_poll.html
模板文件用于创建投票:
{% extends 'base.html' %}
{% block content %}
<h1>Create Poll</h1>
<form method="post" action="{{ url_for('create_poll') }}">
{{ form.csrf_token }}
{{ form.title.label }} {{ form.title }}<br>
{% for choice in form.choices %}
{{ choice.choice.label }} {{ choice.choice }}<br>
{% endfor %}
<button type="submit">Create</button>
</form>
{% endblock %}
view_poll.html
模板文件用于参与投票:
{% extends 'base.html' %}
{% block content %}
<h1>{{ poll.title }}</h1>
<form method="post" action="{{ url_for('view_poll', poll_id=poll.id) }}">
{{ form.csrf_token }}
{% for choice in form.choice %}
{{ choice }} {{ choice.label }}<br>
{% endfor %}
<button type="submit">Vote</button>
</form>
{% endblock %}
view_results.html
模板文件用于查看投票结果:
{% extends 'base.html' %}
{% block content %}
<h1>{{ poll.title }}</h1>
<ul>
{% for choice in poll.choices %}
<li>{{ choice.text }}: {{ choice.votes }}</li>
{% endfor %}
</ul>
{% endblock %}
最后,我们需要创建一个基础模板文件 base.html
,包含应用的样式和布局:
<!doctype html>
<html>
<head>
<title>{% block title %}Poll App{% endblock %}</title>
</head>
<body>
<div class="container">
{% block content %}{% endblock %}
</div>
</body>
</html>
现在,我们可以启动应用并访问它。在应用根目录下创建 app.py
文件,包含以下代码:
from app import app
if __name__ == '__main__':
app.run(debug=True)
在命令行中执行以下命令:
export FLASK_APP=app.py
flask run