Flask实践:猜数字

每个学编程的人大概都写过猜数字游戏,今天我们用Flask来做一个Web版本的猜数字。功能很简单,只有两个路由,三个模板和一个表单组成。


项目结构

1
2
3
4
5
6
7
|-GuesstheNumber 项目名称
|-app.py
|-templates/ 模板文件夹
|-index.html
|-guess.html
|-base.html 基模板
|-venv/ 虚拟环境

实现代码

app.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
#-*- coding:UTF-8 -*-

import random
from flask import Flask, render_template, flash, redirect, url_for, session
from flask_wtf import Form
from wtforms import IntegerField, SubmitField
from wtforms.validators import DataRequired, NumberRange
from flask_bootstrap import Bootstrap
import sys

app = Flask(__name__)
app.config['SECRET_KEY'] = 'very hadr to guess string' #设置secret key
bootstrap = Bootstrap(app) #初始化Flask-bootstrap扩展

# 设置编码
if sys.getdefaultencoding() != 'utf-8':
reload(sys)
sys.setdefaultencoding('utf-8')

@app.route('/')
def index():
# 生成一个0~1000的随机数,存储到session变量中
session['number'] = random.randint(0,1000)
session['times'] = 10
return render_template('index.html')

@app.route('/guess', methods=['GET', 'POST'])
def guess():
times = session['times'] #从session变量中获取次数
result = session.get('number') #从session变量中获取随机生成的数字
form = GuessNumberForm()
if form.validate_on_submit():
times -= 1
session['times'] = times
if times < 0:
flash('你输了...o(>_<)o')
return redirect(url_for('index'))
answer = form.number.data
if answer > result:
flash('太大了!你还剩%s次机会' % times)
elif answer < result:
flash('太小了!你还剩%s次机会' % times)
else:
flash('啊哈,你赢了!V(^-^)V')
return redirect(url_for('index'))
return redirect(url_for('guess'))
return render_template('guess.html', form=form)




class GuessNumberForm(Form):
number = IntegerField('输入数字(0~1000):', validators=[DataRequired('输入一个有效的数字!'),
NumberRange(0,1000, '请输入0~1000以内的数字!')])
submit = SubmitField('提交')


if __name__ == '__main__':
app.run()
index.html
1
2
3
4
5
6
{% extends "base.html" %}

{% block page_content %}
<!-- 传入url_for的参数是视图函数的名称 -->
<a class="btn btn-success btn-lg" href="{{ url_for('guess') }}">开始游戏</a>
{% endblock %}
guess.html
1
2
3
4
5
6
7
8

{% extends "base.html" %} <!-- 引入基模板 -->
{% import "bootstrap/wtf.html" as wtf %}

{% block page_content %}
<!-- 使用Flask-Bootstrap提供的函数来生成默认样式的表单 -->
{{ wtf.quick_form(form) }}
{% endblock %}

源码: github

-------------本文结束感谢您的阅读-------------
hao14293 wechat
交流或订阅,请扫描上方微信二维码