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>
相关推荐
iamohenry1 小时前
古早味的心理咨询聊天机器人
python·自然语言处理
早睡冠军候选人2 小时前
Ansible学习----管理复杂的 Play 和 Playbook 内容
运维·学习·云原生·ansible
LBuffer3 小时前
破解入门学习笔记题四十六
数据库·笔记·学习
Blossom.1185 小时前
移动端部署噩梦终结者:动态稀疏视觉Transformer的量化实战
java·人工智能·python·深度学习·算法·机器学习·transformer
Yurko135 小时前
【计网】基于三层交换机的多 VLAN 局域网组建
网络·学习·计算机网络·智能路由器
AiXed5 小时前
PC微信协议之AES-192-GCM算法
前端·数据库·python
月下倩影时5 小时前
视觉进阶篇——机器学习训练过程(手写数字识别,量大管饱需要耐心)
人工智能·学习·机器学习
灵光通码6 小时前
神经网络基本概念
python·神经网络
Petrichor_H_7 小时前
DAY 31 文件的规范拆分和写法
python
MasterLi80238 小时前
我的读书清单
android·linux·学习