#笔者使用的Python IDE是Thonny,系统是win11
首先创建一个简单的web应用我们需要引入Flask框架,同时引入render_template来渲染HTML模板,pywsgi模块提供了gevent的WSGI服务器,randint函数用于生成随机数。所以先导入相应的包
from flask import Flask,render_template
from gevent import pywsgi
from random import randint
通过实例化Flask类创建了一个名为app的应用程序实例。
app = Flask(__name__)
然后我们应该创建一个抽奖奖项名单
这里我们定义一个商品列表变量:
commodity = ['大米','食用油','方便面','洗洁精','洗衣粉']
要使网页上显示我们需要创建一个网页,其名为index.html
网页代码如下
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
{{hero}}
<a href="/choujiang">随机抽取</a><br>
您选中了{{h}}
</body>
</html>
定义一个index函数,函数会渲染名为index.html的模板,并将hero列表传递给模板
用@app.route装饰器定义了路由
@app.route('/index')
def index():
return render_template('index.html',commodity=commodity)
定义一个choujiang函数,当访问/choujiang时,会调用choujiang函数,该函数会生成一个随机数,并将对应的英雄名称传递给模板。
@app.route('/choujiang')
def choujiang():
num = randint(0,len(commodity)-1)#随机在0到列表长度减一间生成整数
return render_template('index.html',commodity=commodity,h = commodity[num])
server = pywsgi.WSGIServer(('127.0.0.1', 5005), app)
server.serve_forever()
通过pywsgi.WSGIServer创建了一个WSGI服务器,绑定在本地IP地址127.0.0.1和端口号5005上,并将应用程序实例app传递给服务器。最后,使用serve_forever()方法来启动服务器,使其一直运行。(端口可改变)
通过访问127.0.0.1:5005/index显示
源代码如下
from flask import Flask,render_template
from gevent import pywsgi
from random import randint
app = Flask(__name__)
commodity=['大米','食用油','方便面','洗洁精','洗衣粉']
@app.route('/index')
def index():
return render_template('index.html',commodity= commodity)
@app.route('/choujiang')
def choujiang():
num = randint(0,len(commodity)-1)
return render_template('index.html',commodity= commodity,h = commodity[num])
server = pywsgi.WSGIServer(('127.0.0.1', 5005), app)
server.serve_forever()