Todo:
from functools import wraps
from werkzeug.security import check_password_hash
from models import app, Todo, db, Department, User, UserLog
from flask import render_template, redirect, url_for, request, session, flash
def is_login(f):
@wraps(f)
def wrapper(*args,**kwargs):
if not "user" in session:
return redirect(url_for('login'))
return f(*args,**kwargs)
return wrapper
@app.route('/list/')
@app.route('/list/')
# @is_login
def list(page=1):
todos = Todo.query.paginate(page,per_page=4)
parts = Department.query.all()
return render_template('list.html', todos=todos, parts=parts)
@app.route('/done/')
def done(todo_id):
todo = Todo.query.filter_by(id=todo_id).first()
todo.status = True
try:
db.session.add(todo)
db.session.commit()
except Exception as e:
db.session.rollback()
return e
return redirect(url_for('list',page=1))
@app.route('/undone//')
@is_login
def undone(todo_id):
todo = Todo.query.filter_by(id=todo_id).first()
todo.status = False
try:
db.session.add(todo)
db.session.commit()
except Exception as e:
db.session.rollback()
return e
return redirect(url_for('list',page=1))
@app.route('/delete///')
@is_login
def delete(todo_id,page=1):
u = Todo.query.filter_by(id=todo_id).first()
db.session.delete(u)
db.session.commit()
return redirect(url_for('list',page=page))
@app.route('/add/',methods=['POST'])
def add():
data = request.form
name = data['todo_name']
part = data['part']
todo = Todo(name=name,department_id=part)
db.session.add(todo)
db.session.commit()
return redirect(url_for('list'))
@app.route('/login/',methods=['POST','GET'])
def login():
if request.method == 'POST':
data = request.form
name = data['name']
pwd = data['pwd']
u = User.query.filter_by(name=name).first()
if u and check_password_hash(u.pwd,pwd):
session['user'] = u.name
session['user_id'] = u.id
userlog = UserLog(
user_id=u.id,
ip=request.remote_addr,
area="西安"
)
db.session.add(userlog)
db.session.commit()
return redirect(url_for('list'))
else:
flash("密码不正确")
return redirect(url_for('login'))
else:
return render_template('login.html')
@app.route('/logout/')
def logout():
session.pop('user',None)
session.pop('user_id',None)
return redirect(url_for('login'))
@app.route('/')
def index():
return render_template('base.html')
if __name__ == '__main__':
app.run(port=8888)
models:该部分会往数据库中添加信息,首先应建立todoflask在数据库中,并且密码必须正确。
添加信息成功后,可以去数据库中查看以下信息。如果信息存在就必须把相应的代码注释掉,
重复添加则会报错。
import random
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from datetime import datetime
from flask_bootstrap import Bootstrap
from werkzeug.security import generate_password_hash
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://root:redhat@localhost/todoflask'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True
app.config['SECRET_KEY']='redhat'
Bootstrap(app)
db = SQLAlchemy(app)
class Todo(db.Model):
id = db.Column(db.Integer, autoincrement=True, primary_key=True)
name = db.Column(db.String(50))
add_time = db.Column(db.DateTime, default=datetime.now())
status = db.Column(db.Boolean, default=False)
department_id = db.Column(db.Integer,db.ForeignKey('department.id'))
class Department(db.Model):
id = db.Column(db.Integer, autoincrement=True, primary_key=True)
name = db.Column(db.String(50),unique=True)
todos = db.relationship('Todo', backref='department')
users = db.relationship('User', backref ='department')
class User(db.Model):
id = db.Column(db.Integer, autoincrement=True, primary_key=True)
name = db.Column(db.String(50),unique=True)
pwd = db.Column(db.String(100))
email = db.Column(db.String(20),unique=True)
phone = db.Column(db.String(20),unique=True)
info = db.Column(db.Text)
addtime = db.Column(db.DateTime, default=datetime.now())
department_id = db.Column(db.Integer, db.ForeignKey('department.id'))
userlogs = db.relationship('UserLog',backref="user")
class UserLog(db.Model):
id = db.Column(db.Integer, autoincrement=True, primary_key=True)
user_id = db.Column(db.Integer,db.ForeignKey('user.id'))
ip = db.Column(db.String(100))
add_time = db.Column(db.DateTime, default=datetime.now())
area = db.Column(db.String(100))
if __name__ == '__main__':
pass
# db.create_all() (添加部门)
# parts = ['开发部','运维部','人事部']
# partObj = [Department(name=part) for part in parts]
# db.session.add_all(partObj)
# db.session.commit()
# todos = ['管理', '维护', '升级'] (添加功能)
# todoObj = [Todo(name=todo,department_id=random.choice([1,2,3])) for todo in todos]
# db.session.add_all(todoObj)
# db.session.commit()
加密密码
# u1 = User(name="redhat1",pwd=generate_password_hash('redhat'), department_id=1)
# u2 = User(name="redhat2",pwd=generate_password_hash('redhat'), department_id=2)
# u2 = User(name="redhat3",pwd=generate_password_hash('redhat'), department_id=2)
# db.session.add(u2)
# db.session.commit()
分页标签写在文件夹macro里
{% macro paginate(fname, dataObj )%}
{# 分页信息 #}
{# 首页 #}
- 首页
{# 上一页信息
1). 判断是否有上一页信息;
2). 如果有, 创建链接;
3). 如果没有, 该链接设为不可点击的链接
使用的方法:
dataObj.has_prev: 判断用户是否有上一页? 如果有,返回True; 如果没有,返回False;
dataObj.prev_num: 获取上一页的页数编号;
#}
{% if dataObj.has_prev %}
- «
{% else %}
- «
{% endif %}
{# 分布的页数
1). 当构造页面时, 判断是否为用户访问的页数, 如果是, 则加深颜色
2). disable代表用户不可点击的链接
#}
{% for v in dataObj.iter_pages() %}
{% if v == dataObj.page %}
- {{ v }}
{% elif v == None %}
- ...
{% else %}
- {{ v }}
{% endif %}
{% endfor %}
{# 下一页信息
1). 判断是否有下一页信息;
2). 如果有, 创建链接;
3). 如果没有, 该链接设为不可点击的链接
使用的方法:
dataObj.has_next: 判断用户是否有下一页? 如果有,返回True; 如果没有,返回False;
dataObj.next_num: 获取下一页的页数编号;
#}
{% if dataObj.has_next %}
- »
{% else %}
- »
{% endif %}
{# 尾页 #}
- 尾页
{% endmacro %}
前端页面写在文件夹templates内
base.html
{% extends 'bootstrap/base.html' %}
{% block title %}
首页
{% endblock %}
{% block styles %}
{{ super() }}
{% endblock %}
{% block navbar %}
{% endblock %}
{% block content %}
{% endblock %}
list.hml
{% extends 'bootstrap/base.html' %}
{% block title %}用户显示{% endblock %}
{% block content %}
{% endblock %}
login.html
{% extends 'bootstrap/base.html' %}
{% block title %}用户登录{% endblock %}
{% block content %}
{% endblock %}