
Flask框架学习记录
Flask是一个使用Python编写的轻量级Web应用框架。基于Werkzeug WSGI工具箱和Jinja2模板引擎。
主要是为了写edusrc用户信息统计脚本(https://github.com/5ime/edusrc) 写的很浅显,堪堪入门吧…
安装
初始化
先导入一个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
@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
| {% for i in data %} ... {% endfor %}
{% 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()
|