美文网首页
Python || 模板

Python || 模板

作者: 有个水友 | 来源:发表于2017-02-13 16:40 被阅读89次

    总结:

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

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

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

    一、模板技术

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

    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

    <!DOCTYPE html>
    <html>
    <head>
        <title>Home</title>
    </head>
    <body>
        <h1 style="color: red;">Home</h1>
    </body>
    </html>
    

    View:form.html

    <!DOCTYPE html>
    <html>
    <head>
        <title>Please Sign In</title>
    </head>
    <body>
        {% if message %}
            <p>{{ message }}</p>
        {% endif %}
    
        <form action="/signin" method="post">
            <leagend>Please Sign In</leagend>
            <p><input type="text" name="username" placeholder="Username" value="{{ username }}"/></p>
            <p><input type="password" name="password" placeholder="Password" /></p>
            <p><button type="submit">Sign In</button></p>
        </form>
    </body>
    </html>
    

    View:form_ok.html

    <!DOCTYPE html>
    <html>
    <head>
        <title>Hello, {{ username }}</title>
    </head>
    <body>
        <p>Welcome, {{ username }}!</p>
    </body>
    </html>
    

    相关文章

      网友评论

          本文标题:Python || 模板

          本文链接:https://www.haomeiwen.com/subject/qjhtwttx.html