Python学习笔记-Flask实现简单的抽奖程序

1.导入flask包和randint包

复制代码
from flask import Flask,render_template
from random import randint

2.初始化 Flask 应用:

复制代码
app = Flask(__name__)

3. 定义英雄列表

复制代码
hero = ['黑暗之女','狂战士','正义巨像','卡牌大师','德邦总管','无畏战车','诡术妖姬','猩红收割者','远古恐惧','正义天使','无极剑圣','牛头酋长','符文法师','亡灵战神','战争女神','众星之子']

4.定义主页路由

当用户访问 /index 路径时,会调用 index 函数。该函数返回渲染的 index.html 模板,并将英雄列表传递给模板

复制代码
@app.route('/index')
def index():
    return render_template('index.html',hero=hero)

5.定义抽奖路由

点击随机抽取时,choujiang 函数会被调用。函数内部使用 randint 函数从英雄列表中随机选择一个英雄(num 是随机选择的英雄的索引)。然后,它将整个英雄列表和随机选择的英雄一起传递给 index.html 模板

复制代码
@app.route('/choujiang')
def choujiang():
    num = randint(0,len(hero)-1)
    return render_template('index.html',hero = hero , h = hero[num])

6.创建index.html

7.启动 Flask 应用

app.run(debug=True)

8.页面显示

9.python源码

python 复制代码
#让我们的电脑支持服务访问,需要一个web框架flask
from flask import Flask,render_template
from random import randint

app = Flask(__name__)

hero = ['黑暗之女','狂战士','正义巨像','卡牌大师','德邦总管','无畏战车','诡术妖姬','猩红收割者','远古恐惧','正义天使','无极剑圣','牛头酋长','符文法师','亡灵战神','战争女神','众星之子']

@app.route('/index')
def index():
    return render_template('index.html',hero=hero)

@app.route('/choujiang')
def choujiang():
    num = randint(0,len(hero)-1)
    return render_template('index.html',hero = hero , h = hero[num])

app.run(debug=True)

10.index源码

html 复制代码
<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    <!--英雄列表-->
    {{ hero }}
    <br>
    <a href="/choujiang">随机抽取</a> <br>
    您抽到了:<strong>{{h}}</strong>
</body>
</html>
相关推荐
Ulyanov3 分钟前
三维战场可视化核心原理(一):从坐标系到运动控制的全景指南
开发语言·前端·python·pyvista·gui开发
爱喝可乐的老王4 分钟前
神经网络的学习
人工智能·神经网络·学习
Cathy Bryant8 分钟前
softmax函数与logits
笔记·神经网络·机器学习·概率论·信息与通信
SNAKEpc1213811 分钟前
PyQtGraph应用(一):常用图表图形绘制
python·qt·pyqt
CSND74014 分钟前
anaconda 安装库,终端手动指定下载源
python
0思必得014 分钟前
[Web自动化] 爬虫基础
运维·爬虫·python·selenium·自动化·html
放飞自我的Coder17 分钟前
【Python 异步编程学习手册】
python
ycydynq18 分钟前
django 数据库 多表操作
数据库·python·django
阿蒙Amon18 分钟前
TypeScript学习-第2章:基础类型
javascript·学习·typescript
m0_5494166618 分钟前
自动化与脚本
jvm·数据库·python