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>
相关推荐
TF男孩5 小时前
ARQ:一款低成本的消息队列,实现每秒万级吞吐
后端·python·消息队列
该用户已不存在9 小时前
Mojo vs Python vs Rust: 2025年搞AI,该学哪个?
后端·python·rust
站大爷IP12 小时前
Java调用Python的5种实用方案:从简单到进阶的全场景解析
python
用户83562907805117 小时前
从手动编辑到代码生成:Python 助你高效创建 Word 文档
后端·python
_落纸17 小时前
三大基础无源电子元件——电阻(R)、电感(L)、电容(C)
笔记
c8i17 小时前
python中类的基本结构、特殊属性于MRO理解
python
liwulin050618 小时前
【ESP32-CAM】HELLO WORLD
python
Alice-YUE18 小时前
【CSS学习笔记3】css特性
前端·css·笔记·html
2303_Alpha18 小时前
SpringBoot
笔记·学习
萘柰奈18 小时前
Unity学习----【进阶】TextMeshPro学习(三)--进阶知识点(TMP基础设置,材质球相关,两个辅助工具类)
学习·unity