以下是Python生成一个猜大小webapp的详细步骤和完整代码:
步骤
- 安装Python和Flask框架:
pip install flask
- 创建一个新文件,命名为app.py,并编写Flask程序:
from flask import Flask, render_template, request
import random
app = Flask(__name__)
@app.route('/')
def index():
return render_template('index.html')
@app.route('/guess', methods=['POST'])
def guess():
number = int(request.form['number'])
random_number = random.randint(1, 10)
if number == random_number:
result = '猜对了!'
elif number > random_number:
result = '猜大了!'
else:
result = '猜小了!'
return render_template('result.html', result=result)
if __name__ == '__main__':
app.run()
- 创建一个文件夹,命名为templates,并在其中创建两个HTML文件:index.html和result.html:
index.html
<!DOCTYPE html>
<html>
<head>
<title>猜大小</title>
</head>
<body>
<h1>猜大小游戏</h1>
<p>我已经想好了一个1-10之间的数字,你猜吧!</p>
<form action="/guess" method="post">
<input type="number" name="number">
<input type="submit" value="猜">
</form>
</body>
</html>
result.html
<!DOCTYPE html>
<html>
<head>
<title>猜大小</title>
</head>
<body>
<h1>结果</h1>
<p>{{ result }}</p>
<a href="/">再玩一次</a>
</body>
</html>
- 运行Flask程序:
python app.py
- 将程序发布到网上:
可以使用Heroku或其他云服务器将程序发布到网上。
完整代码
app.py
from flask import Flask, render_template, request
import random
app = Flask(__name__)
@app.route('/')
def index():
return render_template('index.html')
@app.route('/guess', methods=['POST'])
def guess():
number = int(request.form['number'])
random_number = random.randint(1, 10)
if number == random_number:
result = '猜对了!'
elif number > random_number:
result = '猜大了!'
else:
result = '猜小了!'
return render_template('result.html', result=result)
if __name__ == '__main__':
app.run()
index.html
<!DOCTYPE html>
<html>
<head>
<title>猜大小</title>
</head>
<body>
<h1>猜大小游戏</h1>
<p>我已经想好了一个1-10之间的数字,你猜吧!</p>
<form action="/guess" method="post">
<input type="number" name="number">
<input type="submit" value="猜">
</form>
</body>
</html>
result.html
<!DOCTYPE html>
<html>
<head>
<title>猜大小</title>
</head>
<body>
<h1>结果</h1>
<p>{{ result }}</p>
<a href="/">再玩一次</a>
</body>
</html>