一、所需模块声明
1、Flask模块
Flask是一个轻量级的Web应用框架,使用Python编写。它提供了一些工具和库,使得开发Web应用变得更加容易和快速。下面是一个简单的Flask应用程序示例:
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello_world():
return 'Hello, World!'
if __name__ == '__main__':
app.run()
"""
这个应用程序定义了一个名为的Flask实例,并使用装饰器将函数绑定到根URL上。当用户访问根URL时,函数将被调用并返回“Hello, World!”字符串。app@app.route('/')hello_world()hello_world()
Flask还提供了许多其他功能,例如模板引擎、表单处理、数据库集成等等。可以通过Flask官方文档来学习更多内容。
"""
二、完整代码
1、python运行函数
from flask import Flask,render_template #render:使成为
from random import randint
hero=['黑暗之女','狂战士','正义巨像','韩信','李白','十号','石昊','陈平安','杨间','陈凯歌','王轩']
app = Flask(__name__) #创建一个外部应用
@app.route('/') #使用装饰器将函数绑定到根URL上,注意,函数传到网页不需要在根目录'/'下加东西
def index():
return render_template('index.html',hero = hero) #前一个hero表示在index.html中的名称
@app.route('/choujiang') #网页所要执行的东西函数需要在根目录下声明,即'/choujiang'
def choujiang():
num = randint(0,len(hero)-1) #(0,9)
return render_template('index.html',hero=hero,h=hero[num])
app.run(debug=True) #debug=True方便后续开发,使以后改写代码时不用反复的重启应用
"""
http://127.0.0.1:5000 http://127.0.0.1:访问到我们自己这台笔记本,:5000表示定位到此时Flask这个服务上来
"""
2、html网页
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
{{ hero }}<br/>
<a href="/choujiang">随机抽取</a><br/>
您抽到了{{ h }}
</body>
</html>
3、整体游览
三、运行结果