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>
相关推荐
思成不止于此3 分钟前
【MySQL 零基础入门】DQL 核心语法(四):执行顺序与综合实战 + DCL 预告篇
数据库·笔记·学习·mysql
测试人社区-千羽16 分钟前
边缘计算场景下的智能测试挑战
人工智能·python·安全·开源·智能合约·边缘计算·分布式账本
抽象带篮子19 分钟前
Pytorch Lightning 框架运行顺序
人工智能·pytorch·python
哇哈哈&34 分钟前
安装wxWidgets3.2.0(编译高版本erlang的时候用,不如用rpm包),而且还需要高版本的gcc++19以上,已基本舍弃
linux·数据库·python
Nan_Shu_61434 分钟前
学习:Vuex (1)
学习
GoogleDocs1 小时前
基于[api-football]数据学习示例
java·学习
李小星同志1 小时前
DPO,PPO,GRPO的学习
人工智能·深度学习·学习
luod1 小时前
pymysql执行DDL语句
python
song5012 小时前
鸿蒙 Flutter 图像识别进阶:物体分类与花卉识别(含离线模型)
人工智能·分布式·python·flutter·3d·华为·分类
Mqh1807622 小时前
day 35 文件的拆分和使用
python