flask.py
# 导入Flask类
from flask import Flask,render_template,request
import datetime
#Flask类接受一个参数 __name__
# 定义一个变量app
app = Flask(__name__)
#装饰器的作用是将路由映射到视图函数index
@app.route('/')
def index():
return "hello world"
@app.route('/index')
def index():
return "你好"
# 通过访问路径,获取用户的字符串参数
@app.route('/user/<int:id>')#还可以是float
def welcome(id):
return "hello,%d"%id+"号会员"
# 路由路径不能重复,用户通过唯一路径访问特定的函数
# html文件必须在template文件夹里
@app.route('/')
def index2():
return render_template("index.html")
# 向页面传递一个参数
@app.route()
def index3():
time = datetime.date.today()#普通变量
name = ["小张","小王","小赵"] #列表类型
task = {"任务":"打扫卫生","时间":"三小时"}
return render_template("index.html",var = time,list = name ,task = task)
# 表单提交
@app.route('/test/register')
def register():
return render_template("test/register.html")
# 接收表单提交的路由,需要指定methods为POST
@app.route('/result',methods=['POST','GET'])
def result():
if request.method == 'POST':
result = request.form#把表单所有内容当作字典返回给result
return render_template("test/result.html",result = result)
# 动态获得网址路径 封装路径
@app.route('/result',methods=['POST','GET'])
def result():
if request.method == 'POST':
result = request.form#把表单所有内容当作字典返回给result
return render_template("test/result.html",result = result)
#Flask应用程序实例的run方法启动Web服务器
if _name_ == '__main__':
app.run(debug=True)
register.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form action="http://localhost:5000/result" method="post"><!--点击提交之后要访问http://localhost:5000/result这个路径-->
<p>姓名:<input type="text" name = "姓名"></p>
<p>年龄:<input type="text" name = "年龄"></p>
<p>性别:<input type="text" name = "性别"></p>
<p>地址:<input type="text" name = "地址"></p>
<p><input type="submit" value="提交"></p>
</form>
<form action="url_for('result') method="post"><!--url_for('这里写要访问的除IP和域名后的路径')-->
<p>姓名:<input type="text" name = "姓名"></p>
<p>年龄:<input type="text" name = "年龄"></p>
<p>性别:<input type="text" name = "性别"></p>
<p>地址:<input type="text" name = "地址"></p>
<p><input type="submit" value="提交"></p>
</form>
</body>
</html>
result.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<table border="1">
{% for key,value in result.items() %}<!--items()方法使得字典转换成数组[(key,value),(key,value),(key,value)]-->
<tr>
<th>{{ key }}</th>
<td>{{ value }}</td>
</tr>
{% forend %}
</table>
</body>
</html>
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
今天是{{ var }},欢迎光临
今天值班的有:<br/>
{% for data in list %}#用大括号和百分号括起来的是控制结构,还有if
<!-- {{ data }}-->
<li>{{ data }}</li>
{% forend%}
任务:<br/><!--了解一下如何在页打印表格,以及如何迭代-->
<table border=""1>
{% for key,value in task.items() %}<!--items()方法使得字典转换成数组[(key,value),(key,value),(key,value)]-->
<tr>
<td>{{ key }}</td>
<td>{{ value }}</td>
</tr>
{% forend %}
</table>
</body>
</html>