MVC模式
MVC:Model-View-Controller,中文名“模型-视图-控制器”。
处理URL的函数就是C:Controller,Controller负责业务逻辑,比如检查用户名是否存在,取出用户信息等等;
包含变量{{ name }}的模板就是V:View,View 负责显示逻辑,通过简单地替换一些变量,View最终输出的就是用户看到的HTML。
Model 是用来传给View的,这样View在替换变量的时候,就可以从Model中取出相应的数据。
3个不同界面的html
home 界面
<html>
<head>
<title>
Home
</title>
</head>
<body>
<h1 style = "font-style:italic">
Home
</h1>
</body>
</html>
登陆界面
<html>
<head>
<title>
Loggin
</title>
</head>
<body>
{% if message %}
<p style = "color:red">
{{message}}
</p>
{% endif %}
<form action = "/loggin" method = "post">
<legend>Loggin</legend>
<p><input name="username" placeholder="UserName" value="{{ username }}"></p>
<p><input name="password" placeholder="Password" type="password"></p>
<p><button type="submit">Loggin</button></p>
</form>
</body>
</html>
登陆成功界面
<html>
<head>
<title>Loggin success, {{ username }}</title>
</head>
<body>
<p>Hello, {{ username }}!</p>
</body>
</html>
存放到 templates 文件中
Python控制上述界面
# run.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Python基础-MVC模式
from flask import Flask, request, render_template
app = Flask(__name__)
@app.route('/', methods=['GET', 'POST'])
def home():
return render_template('home.html')
@app.route('/loggin', methods=['GET'])
def signin_form():
return render_template('form.html')
@app.route('/loggin', methods=['POST'])
def signin():
username = request.form['username']
password = request.form['password']
if username=='admin' and password=='123456':
return render_template('loggin-ok.html', username=username)
return render_template('form.html', message='密码或用户名不正确', username=username)
if __name__ == '__main__':
app.run()
运行示例
python run.py
浏览器分别输入
D:\PythonProject\mvc>python run.py
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
127.0.0.1 - - [25/Dec/2017 22:29:04] "GET / HTTP/1.1" 200 -
127.0.0.1 - - [25/Dec/2017 22:29:09] "GET /loggin HTTP/1.1" 200 -
127.0.0.1 - - [25/Dec/2017 22:29:18] "POST /loggin HTTP/1.1" 200 -
127.0.0.1 - - [25/Dec/2017 22:29:21] "GET /loggin HTTP/1.1" 200 -
127.0.0.1 - - [25/Dec/2017 22:29:22] "GET / HTTP/1.1" 200 -
127.0.0.1 - - [25/Dec/2017 22:40:52] "GET /loggin HTTP/1.1" 200 -
127.0.0.1 - - [25/Dec/2017 22:41:26] "POST /loggin HTTP/1.1" 200 -
小结
有了MVC,我们就分离了Python代码和HTML代码。HTML代码全部放到模板里,写起来更有效率。