app == Flask(name)
app.route()原理参考网页:http://python.jobbole.com/80956/
利用装饰器将Url和函数关联起来
# -*- coding:utf-8 -*-
class NotFlask():
def __init__(self):
self.routes = {}
def route(self,route_str): #用装饰器函数的副产品去保存一个提供给我们的路径
#之间的链接,装饰器函数应该与它关联起来。
#NotFlask对象加一个“routes”字典,当我们的“decorator”函数被调用,
#路径将被插入新字典中函数对应的位置。
def decorator(f):
self.routes[route_str] = f
return f
return decorator
def serve(self,path): #增加serve(path)函数:当路径存在时返回结果,不然就报错
view_function = self.routes.get(path)
if view_function:
return view_function()
else:
raise ValueError('Route"{}""has not been registered')
app = NotFlask()
@app.route('/')
def hello():
return 'Hello,world'
print(app.serve('/'))
运行结果: Hello,world
MVC:Model-View-Controller,中文名“模型-视图-控制器”
我理解为将html视为对象,更改对象内容和python内函数分开,非常方便
from flask import Flask, request, render_template
app = Flask(__name__)
@app.route('/', methods=['GET', 'POST'])
def home():
return render_template('home.html')
@app.route('/signin', methods=['GET'])
def signin_form():
return render_template('form.html')
@app.route('/signin', methods=['POST'])
def signin():
username = request.form['username']
password = request.form['password']
if username=='admin' and password=='password':
return render_template('signin-ok.html', username=username)
return render_template('form.html', message='Bad username or password', username=username)
if __name__ == '__main__':
app.run()
home.html
<html>
<head>
<title>Home</title>
</head>
<body>
<h1 style="font-style:italic">Home</h1> //斜线
</body>
</html>
form.html
<html>
<head>
<title>Please Sign In</title>
</head>
<body>
{% if message %}
<p style="color: red">{{message}}</p>
{% endif %}
<form action="/signin" method="post">
<legend>Please sign in:</legend>
<p><input name="username" placeholder="Username" value="{{ username }}"></p>
<p><input name = "password" placeholder="Password" type="password"></p>
<p><button type="submit">Sign In</button></p>
</form>
</body>
</html>
signin-ok.html
<html>
<head>
<title>Welcome,{{ username }}</title> //{{ name }}内是可以替换的变量
</head>
<body>
<p>Welcome,{{ username }}!</p>
</body>
</html>