园长

学无止境 知行合一

Flask框架基础

这篇文章给我写的很难受,以为文中提到的代码例子跟博客的渲染器有冲突,改了半天……

开始

1
2
3
4
flaskProject
├─static
├─templates
├─app.py

    用 Pycharm 新建一个Flask项目,在生成的文件中,会自动生成如上目录和app.py文件,该文件内容默认为:

1
2
3
4
5
6
7
8
9
10
11
12
13

from flask import Flask,render_template,request

#Flask接受一个__name__参数
app = Flask(__name__)

#@装饰器进行路由映射
@app.route('/') #路由
def hello_world():
return 'Hello World'

if __name__ == '__main__':
app.run()

    该文件就是最简单的Flask项目了,运行,默认在127.0.0.1:5000
/可进行访问

    目录中templates用于存放需要渲染的网页,渲染网页需要导入 render_template,static用于存放css、js等资源文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

#导入,render_template用于渲染网页,request用于请求
from flask import Flask,render_template,request

#Flask接受一个__name__参数
app = Flask(__name__)

#@装饰器进行路由映射
@app.route('/')
def hello_world():
return 'Hello World'

#run()方法启动WEB服务器
if __name__ == '__main__':
app.run()

传入参数

传入字符串

    当我们有 用户访问127.0.0.1/user/xxx,服务器进行响应时:

1
2
3
4

@app.route('/user/<text>')
def welcome(name):
return 'welcome%d'%name

传入整型

    当我们有 用户访问127.0.0.1/id/00001,服务器进行响应时:(当然也有浮点型:<float:xxx>)

1
2
3
4

@app.route('/user/<int:userid>')
def welcome2(userid):
return 'welcome%s'%userid

传入变量:普通变量、列表、字典

    通过flask向网页传递参数例子如下:

1
2
3
4
5
6
@app.route('/')
def index():
title='我是网页标题'
list=['赵','钱','孙','李']
return render_template("index.html",list=list,title=title)
#上一行中render_template就是对index.html进行渲染

    这里我们传入了 字符串 title列表list,那么在网页中:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<!DOCTYPE html>
<html lang="zh_CN">
<head>
<meta charset="UTF-8">
<title>{{ title }}</title>
<h3>Flask学习</h3>
成员:<br/>
{% for name in list %}
<li>{{ name }}</li>
{% endfor %}
</head>
<body>

</body>
</html>

<!--
可以看出,传入的内容在html中用{{ }} 包裹,flask就会对其进行渲染
for循环则用 {% for xxxx in xxx%}, 以{% endfor %}结束。
-->

    还可传入字典dic={'username':'admin','password':'123456'}

    在html中调用:

1
2
3
4
5
6
7
......
{ % for key,values in result.items() %}
{{ user }}
{{ pass }}
<br>
{%endfor%}
......

表单提交

    POST或GET
假设访问登录:
python

1
2
3
4

@app.route("/login")
def login():
return render_template("/login.html")

login.html:action中的url_for('loginre')是自动获取路径下的/loginre

1
2
3
4
5
6
7
......
<form method="post" action="{{ url_for('loginre') }}">
<p>账号:<input type="text" name="username"></p>
<p>密码:<input type="text" name="password"></p>
<p><input type="submit" value="登录"></p>
</form>
......

loginre : 注意其中的 ** methods=[‘POST’,’GET’] , 并使用request**

1
2
3
4
5
6

@app.route("/loginre" ,methods=['POST','GET'])
def loginre():
if request.method=='POST':
result=request.form
return render_template("/loginre.html",result=result)

loginre.html:

1
2
3
4
5
6
7
8
{% for un,pw in result.items() %}
<table border="1">
<tr>
<td>{{ un }}</td>
<td>{{ pw }}</td>
</tr>
</table>
{% endfor%}


 评论




博客内容遵循 署名-非商业性使用-相同方式共享 4.0 国际 (CC BY-NC-SA 4.0) 协议

本站使用 volantis 作为主题 。