Flask

一. flask在哪里找模板?

  1. from flask import Flask
  2. 从Flask中查看源码,会跳转到app.py,app.py里有class Flask,class Flask里面有__init__
  3. 从源码可见,默认模板路径是当前路径的templates目录
  4. from flask import render_template
  5. 在@app.route('path')装饰的view function中 return render_template('xxx.html')
  6. 请求都存进request对象中。 from flask import request
  7. from flask import redidect为重定向,例如登录成功重定向到另一个页面
  8. 在render_template第二个参数中写要传入模板的对象,然后在模板的{{xxx}}就是替换参数的位置
    def __init__(
        self,
        import_name,
        static_url_path=None,
        static_folder='static',
        static_host=None,
        host_matching=False,
        subdomain_matching=False,
        template_folder='templates',
        instance_path=None,
        instance_relative_config=False,
        root_path=None
    ):

/templates/login.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Login</title>
</head>
<body>
    <h1>用户登录</h1>
    <form method="post">
        <input type="text" name="user">
        <input type="password" name="password">
        <input type="submit" value="login">
        {{error}}
    </form>
</body>
</html>

hello.py

from flask import Flask, render_template, request, redirect

app = Flask(__name__)


@app.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'GET':
        return render_template('login.html')
    else:
        # request.query_string
        user = request.form.get('user')
        password = request.form.get('password')
        if user == 'allin' and password == '123456':
            return redirect('https://www.baidu.com')
        return render_template('login.html', error='user or password is wrong')

二. 前端模板与后台交互

  1. 如果后台不用Markup或在前端使用{{xxx() | safe}},那么会生成纯字符串。(生成纯字符串不可以使用后台传过来的代码在前端语义化,可以防止XSS攻击)
  2. 在render_template()的第二个参数写要传入模板的对象
  3. Flask中的Markup等价Django的mark_safe
    html模板
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <!--1.如果后台没有用Markup,那么就打印纯字符串(防止XSS攻击)。
    2. 要免除这种纯字符串,第一种方法是用后台用Markup;后台没有用Markup的话,可以在前端用{{ff('大家好') | safe}}来生成。-->
    {{ff('大家好')}}

    <!--宏定义,Jinja2自带的-->
    {% macro xx(name, type='text', value='') %}
        <input type="{{ type }}" name="{{ name }}1" value="{{ value }}">
        <input type="{{ type }}" name="{{ name }}2" value="{{ value }}">
        <input type="{{ type }}" name="{{ name }}3" value="{{ value }}">
        <input type="{{ type }}" name="{{ name }}4" value="{{ value }}">
    {% endmacro %}
    <!--执行宏定义,相当于执行方法,前端自动生成<input>-->
    {{ xx('n') }}

</body>
</html>

py主文件

from flask import Flask,render_template,Markup,jsonify,make_response
app = Flask(__name__)


def func1(arg):
    return Markup("<input type='text' value='%s' />" %(arg,))

@app.route('/')
def index():
    return render_template('index.html',ff = func1)


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

三. 在后台写模板可以调用的函数,定制模板方法

@app.template_global()
def func1(a1, a2):
    return a1 + a2


@app.template_filter()
def func2(a1, a2, a3):
    return a1 + a2 + a3

调用方式:第一个为{{func1(1, 2)}},第二个为{{1 | func2(2, 3,)}},1为参数a1

原文地址:https://www.cnblogs.com/allen2333/p/9008316.html