0
点赞
收藏
分享

微信扫一扫

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

安七月读书 03-08 07:00 阅读 2

 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源码

#让我们的电脑支持服务访问,需要一个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源码

<!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>
举报

相关推荐

0 条评论