Python || 模板

总结:

  • 通过MVC,在Python代码中处理Controller和Model;通过View模板处理HTML,最大限度实现了Python代码与HTML代码的分离。
  • HTML代码全部放在模板中,可以非常方便的修改,并且刷新浏览器即可看到效果;
  • Flask默认使用Jinja2模板,其中{{ name }}表示变量;{% %}表示循环、条件判断等指令。

Web框架解决了URL与处理函数的映射问题。但是在Web App中,前端展示同样重要。

在处理函数中返回HTML代码,对于简单的页面还可以接受;但是对于复杂页面,需要在Python代码中嵌入大量HTML代码,导致维护困难

一、模板技术

在Python中拼接字符串实现太繁复,所以诞生了模板技术。模板是嵌入了变量和指令的HTML文档,然后根据传入的数据替换模板中的变量和指令,最后输出HTML文件,发送给用户

Python || 模板_第1张图片
MVC

MVC
模板技术的实现,Web App同样实现了MVC(Model-View-Controller)的开发模式。

  • Python处理URL的函数是C:Controller,负责业务逻辑,比如检查用户名是否存在、取出用户信息等;
  • 包含变量{{ name }}的模板是V:View,负责显示逻辑,通过变量替换,输出HTML代码。
  • M:Model是数据模型,通过Controller将Model传递给View,View在变量替换时,从Model中取出数据,渲染到HTML页面中。

因为Python支持关键字参数,所以许多Web框架允许传入关键字参数,然后在框架内部组装出一个dict作为Model。

二、利用MVC重写app.py

Controller:

from flask import Flask
from flask import render_template
from flask import request

app = Flask(__name__)

#====================================
#Home Page
@app.route("/", methods=["GET", "POST"])
def home():
    return render_template("home.html")

#====================================
#Login Page
@app.route("/signin", methods=["GET"])
def signin_form():
    return render_template("form.html")

#====================================
#Login Status
@app.route("/signin", methods=["POST"])
def form():
    username = request.form["username"]
    password = request.form["password"]
    if username=="admin" and password=="password":
        return render_template("form_ok.html", username=username)
    return render_template("form.html", message="Bad username or password", username=username)

#====================================
#run app
if __name__ == "__main__":
    app.run()

View:home.html




    Home


    

Home

View:form.html




    Please Sign In


    {% if message %}
        

{{ message }}

{% endif %}
Please Sign In

View:form_ok.html




    Hello, {{ username }}


    

Welcome, {{ username }}!

你可能感兴趣的:(Python || 模板)