iami233
iami233
文章175
标签37
分类4

文章分类

文章归档

Flask框架学习记录

Flask框架学习记录

Flask是一个使用Python编写的轻量级Web应用框架。基于Werkzeug WSGI工具箱和Jinja2模板引擎。

主要是为了写edusrc用户信息统计脚本(https://github.com/5ime/edusrc) 写的很浅显,堪堪入门吧…

安装

1
pip install flask

初始化

先导入一个Flask类的对象,并创建一个该类的实例

1
2
from flask import Flask
app = Flask(__name__)

路由

路由就不用多说了,用来把为用户请求的URL找出其对应的视图函数

1
2
3
@app.route('/')
def index():
return 'Hello,flask!'

当我们访问主页/的时候,页面就会自动调用index()函数,显示Hello,flask!

路径传参

格式:url/参数,然后再视图函数中接收参数

1
2
3
4
5
6
7
@app.route('/')
def index():
return 'Hello,flask!'

@app.route('/<username>')
def name(username):
return 'Hello,' + str(username)

这样访问url/iami233的时候页面就会显示Hello,iami233,当然我们也可以限制<username>的传入类型(<int:userid>)。

  • string(缺省值) 接受任何不包含斜杠的文本

  • int 接受正整数

  • float 接受正浮点数

  • path 类似string,但可以包含斜杠

  • uuid 接受UUID字符串

HTTP方法

默认情况下路由只响应GET请求。 不过可以使用route()装饰器的methods参数来处理不同的HTTP方法。

1
2
3
4
5
6
@app.route('/login', methods=['GET', 'POST'])
def login():
if request.method == 'POST':
return do_the_login()
else:
return show_the_login_form()

渲染模板

使用render_template()方法可以渲染模板,我们只要提供模板名称和需要作为参数传递给模板的变量即可。

1
2
3
4
5
6
7
8
from flask import render_template
# 注意我们要导入render_template

@app.route('/hello/<username>')
def hello(username):
return render_template('hello.html',
username = username
)

html模板需要放在templates目录中

1
2
3
/main.py
/templates
/hello.html

模板示例

1
2
3
<!doctype html>
<title>Hello Flask</title>
<h1>Hello, {{username}}</h1>

jinja2

Flask使用Jinja 2作为模板引擎,在Jinja 2中,存在三种语法

1
2
3
{% %} 控制结构
{{ }} 变量取值
{# #}

一些博主常用操作

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# 循环输出变量data
{% for i in data %}
...
{% endfor %}

# 判断变量data的长度是否小于五
# 如果小于则根据实际长度与5的差值进行循环
{% if data | length < 5 %}
{% for i in range(5 - data | length) %}
...
{% endfor %}
{% endif %}

# 条件控制

{% if 条件1 %}
...
{% elif 条件2 %}
...
{% else %}
...
{% endif %}

# 循环控制

{% for i in data %}
...
{% else %}
...
{% endfor %}

完整示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
from flask import Flask, render_template

@app.route('/')
def index():
return 'Hello,flask!'

@app.route('/<username>')
def name(username):
return 'Hello,' + str(username)

@app.route('/hello/<username>')
def hello(username):
return render_template('hello.html',
username = username
)

if __name__ == '__main__':
app.run()
本文作者:iami233
本文链接:https://5ime.cn/flask.html
版权声明:本文采用 CC BY-NC-SA 3.0 CN 协议进行许可