- 设定奖项
python
PRIZES = ['特等奖', '一等奖', '二等奖', '三等奖', '安慰奖', '谢谢参与']
- 设定概率
python
PRIZES_PROBABILITIES = [0.01, 0.05, 0.1, 0.2, 0.3, 0.34]
- 功能实现
核心代码:
python
@app.route('/choujiang')
def choujiang():
your_prize = random.choice(PRIZES, p=PRIZES_PROBABILITIES)
return render_template('choujiang.html', prizes=PRIZES, your_prize=your_prize)
注:此处的 choice 是 numpy.random 下的 choice ,而非内置的 random 下的 choice 。
choujiang.html
html
所有奖项 :{{ prizes }}<br>
你的奖项 : {{ your_prize }}
- 功能优化
原始代码需要每次刷新才能实现一次抽奖,实际用户不可能如此操作。现增加抽奖链接,点击即可实现一次抽奖。
html
所有奖项 :{{ prizes }}<br>
<a href="/choujiang">点击抽奖</a><br>
{{ your_prize}}
