Flask 入门
Flask是一个轻量级Web框架,Flask框架的核心就是Werkzeug和Jinjia2
python最出名的框架是Django,此外还有Flask,Tornado等框架。
功能:
- 使用Werkzeug路由转发。根据每个URL请求,找到具体的视图函数。
- 模板渲染
pycharm开发版可以直接创建flask项目,社区版需要自己手敲如下基础代码:
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello_word():
return 'hello,world!'
if __name__ =='__main__':
app.run(debug=True)
debug = True是开启调试模式,即不需要重新运行能自动根据修改后的代码网页进行更改。在不同的开发模式中有的有效有的无效。
路由转发
from flask import Flask
app = Flask(__name__)
# 通过访问路径,获取用户的字符串参数
@app.route('/user/<name>')
def hello_word(name):
return 'hello,%s!'%name
# 通过访问路径,获取用户的整型参数 此外,还有float类型
@app.route('/user/<int:id>')
def hello_word2(id):
return 'hello,%d号的会员!'%id
# 路由路径不能重复,用户通过唯一路径访问特定的函数
if __name__ =='__main__':
app.run(debug=True)
结果:可以返回用户在网址后加的字段
网页渲染
结果
向网页里传递变量
在html中使用{{ }}传递
from flask import Flask, render_template
# render_template 渲染模板
import datetime
app = Flask(__name__)
@app.route('/')
def index():
time = datetime.date.today() # 普通变量
name = ['小宋', '丸子'] # 列表类型
task = {"任务": "舞台表演", "时间": "5分钟", \
"节目名称": "世界上的另一个我"} # 字典类型
return render_template("index.html", var=time, list=name, task=task)
if __name__ == '__main__':
app.run(debug=True)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
今天是{{var}},看的到太阳吗?<br/>
今天在线的有:<br/>
{% for data in list %} <!--用大括号和百分号括起来是控制结构,还有if-->
<li>{{data}}</li>
{% endfor %}
任务:<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>
{% endfor %}
</table>
</body>
</html>
结果:
main.py
from flask import Flask, render_template, request
# render_template 渲染模板
app = Flask(__name__)
# 表单提交
@app.route('/register')
def index():
return render_template("register.html")
# 接收表单提交的路由,需要指定methods为post
@app.route('/result', methods=['post', 'get'])
def index2():
if request.method == 'POST':
result = request.form
return render_template("result.html", result=result)
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">
<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>
{% endfor %}
</table>
</body>
</html>
点击提交后
bug记录
使用**url_for()**代替写死的路由,register页面报错
报错信息:
bug修复:在url_for中添加参数static,并且在main.py中将跳转链接改成’/static/result’,如下: