4

Flask框架学习记录

 2 years ago
source link: https://5ime.cn/flask.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
Flask框架学习记录

Flask框架学习记录

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

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

pip install flask

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

from flask import Flask
app = Flask(__name__)

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

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

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

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

@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方法。

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

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

from flask import render_template
# 注意我们要导入render_template

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

html模板需要放在templates目录中

/main.py
/templates
    /hello.html
<!doctype html>
<title>Hello Flask</title>
<h1>Hello, {{username}}</h1>

jinja2

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

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

一些博主常用操作

# 循环输出变量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 %}
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()

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK