在templates
文件夹下面
语法是{{ }}
获取参数
<html lang="en">
<head>
<meta charset="UTF-8">
<title>title>
head>
<body>
{{ context }}
welcome {{ user.getName() }}
body>
html>
__author__ = 'Nicholas'
class User():
def __init__(self,name,password):
self.name = name
self.password = password
def getName(self):
return self.name
def setName(self,name):
self.name = name
def setPassword(self,password):
self.password = password
__author__ = 'Nicholas'
from flask import Flask,render_template
from model import User
app = Flask(__name__)
@app.route('/')
def hello():
context = 'hello template'
return render_template('index.html',context = context)
@app.route('/user')
def user():
user = User('zhangsan','zhangsan')
return render_template('index.html',user = user)
if __name__=='__main__':
app.run()
语法格式
{% if condition %}
{% else %}
{% endif %}
{% if user %}
hello ,{{ user.getName() }}
{% else %}
sorry,no such user !
{% endif %}
语法格式
{% for user in users %}
{% endfor %}
{% for user in users %}
{{ user.getName() }} -- {{ user.password }}
{% endfor %}
把一个页面中,不变的部分抽象成一个基类,变化的部分在子类中实现
基类 base.html
<html lang="en">
<head>
<meta charset="UTF-8">
<title>title>
head>
<body>
<div>
<h1>头部信息栏,每个页面都是一样的部分h1>
div>
{% block context %}
{% endblock %}
<div>
<h1>底部信息栏,每个页面都是一样的部分h1>
div>
body>
html>
子类
one.html
{% extends "base.html" %}
{% block context%}
<h2> 这是子类h2>
{% endblock %}
app.secret_key
= ‘123’from flask import Flask, flash, render_template, request,abort
app = Flask(__name__)
app.secret_key = '123'
@app.route('/')
def hello_world():
flash("hello")
return render_template("index.html")
@app.route('/login', methods=['POST'])
def login():
form = request.form
username = form.get('username')
password = form.get('password')
if not username:
flash("please input username")
return render_template("index.html")
if not password:
flash("please input password")
return render_template("index.html")
if username == 'weixuan' and password == '123456':
flash("login success")
return render_template("index.html")
else:
flash("username or password is wrong")
return render_template("index.html")
if __name__ == '__main__':
app.run()
<html>
<head lang="en">
<meta charset="UTF-8">
<title>title>
head>
<body>
<h1>Hello Loginh1>
<form action="/login" method="post">
<input type="text" name="username">
<input type="password" name="password">
<input type="submit" value="Submit">
form>
<h2>{{ get_flashed_messages()[0] }}h2>
body>
html>
@app.errorhandler(404)
处理异常
@app.errorhandler(404)
def not_found(e):
return render_template("404.html")
@app.route('/users/')
def users(user_id):
if int(user_id) == 1:
return render_template("user.html")
else:
abort(404)
<html lang="en">
<head>
<meta charset="UTF-8">
<title>title>
head>
<body>
<h1>该页面不存在h1>
body>
html>