python 实现任务管理清单案例


Posted in Python onApril 25, 2020

base.html:

{% extends "bootstrap/base.html" %}

{% block styles %}
  {{ super() }}
  <link rel="stylesheet" href="../static/css/main.css" rel="external nofollow" >
{% endblock %}

{% block navbar %}
  <nav class="navbar navbar-default">
    <div class="container-fluid">
      <!-- Brand and toggle get grouped for better mobile display -->
      <div class="navbar-header">
        <button type="button" class="navbar-toggle collapsed" data-toggle="collapse"
            data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
          <span class="sr-only">Toggle navigation</span>
          <span class="icon-bar"></span>
          <span class="icon-bar"></span>
          <span class="icon-bar"></span>
        </button>
        <a class="navbar-brand" href="index.html" rel="external nofollow" ></a>
      </div>

      <!-- Collect the nav links, forms, and other content for toggling -->
      <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
        <ul class="nav navbar-nav">
           <li><a href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" ></a></li>
           <li><a href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" ></a></li>
          <li><a href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >首页<span class="sr-only">(current)</span></a></li>
          <li><a href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >新闻</a></li>
          <li><a href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >国际</a></li>
          <li><a href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >国内</a></li>
          <li><a href="/sysinfo/" rel="external nofollow" >系统信息</a></li>
          <li><a href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >登陆用户</a></li>
        </ul>
        <ul class="nav navbar-nav navbar-right">

          {% if 'user' in session %}
            <li><a href="login.html" rel="external nofollow" ><span class="glyphicon glyphicon-user"></span>
                 {{ session.user }}</a></li>
            <li><a href="/logout/" rel="external nofollow" ><span class="glyphicon glyphicon-log-in"></span>
                 注销 </a></li>

          {% else %}

            <li><a href="/login/" rel="external nofollow" ><span class="glyphicon glyphicon-log-in"></span>
                登陆</a></li>
            <li><a href="/register/" rel="external nofollow" ><span class="glyphicon glyphicon-log-out"></span>
              注册</a></li>
          {% endif %}



        </ul>
      </div><!-- /.navbar-collapse -->
    </div><!-- /.container-fluid -->
  </nav>
{% endblock %}

{% block content %}
  {#定义属于自己的block#}
  {% block newcontent %}

  {% endblock %}

  {% block footer %}

    <div class="footer">


      京ICP备11008151号京公网安备11010802014853

    </div>

  {% endblock %}
{% endblock %}

list.html:

{% extends 'base.html' %}

{% block newcontent %}
  <div class="row">
    <div class="col-md-6 col-md-offset-3">
      /*添加任务*/
      <form class="form-horizontal" action="/todo/add/" method="post">
        <div class="form-group">
          {# 添加框          #}
          <div class="col-sm-9">
            <input type="text" class="form-control" placeholder="请添加任务" required="required"
                name="todo_name">
          </div>
          {#  选择框       #}
          <div class="col-sm-2">
            <select class="form-control" name="part">
              {% for part in parts %}
                <option value="{{ part.id }}">{{ part.name }}</option>
              {% endfor %}
            </select>
          </div>

          {#  添加的按钮       #}
          <div class="col-sm-1">
            <input type="submit" class="btn btn-success" value="添加任务">
          </div>
        </div>

      </form>

      /*任务显示*/
      <h1>添加任务</h1>
      <table class="table table-bordered">
        <tr>
          <td>任务内容</td>
          <td>创建时间</td>
          <td>状态</td>
          <td>所属部门</td>
          <td>操作</td>
        </tr>
        {% for todo in todos %}
          <tr>
            <td>{{ todo.name }}</td>
            <td>{{ todo.add_time }}</td>
            {#    #}
            <td>
              {% if todo.status %}
                 <a href="/todo/undo/{{ todo.id }}/" rel="external nofollow" class="btn btn-sm btn-success" role="button"><span
              class="glyphicon glyphicon-ok"></span> 已完成</a>

              {% else %}
                <a href="/todo/done/{{ todo.id }}/" rel="external nofollow" class="btn btn-sm btn-warning" role="button"><span
              class="glyphicon glyphicon-remove"></span> 未完成</a>

              {% endif %}

            </td>
            <td>{{ todo.department.name }}</td>
            <td><a href="/todo/delete/{{ todo.id }}/" rel="external nofollow" class="btn btn-sm btn-danger" role="button"><span
              class="glyphicon glyphicon-remove"></span> 删除</a></td>
          </tr>

        {% endfor %}


      </table>
    </div>
  </div>

{% endblock %}

models.py:

from datetime import datetime
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_bootstrap import Bootstrap

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://root:971203@localhost/Todo'
# SQLAlchemy 将会追踪对象的修改并且发送信号。
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True
db = SQLAlchemy(app)
bootstrap = Bootstrap(app)
app.config['SECRET_KEY'] = 'westos'
# 1). 面向对象方式创建表
# 2). 分析关系:
#    部门和用户: 一对多
#    用户和任务: 一对多的关系
#    用户和用户登录日志: 一对多的关系
# 实现一对多(Role(1): User(n))的关系
#  - 多的一端写外键
#  - 少的一端写反向引用

class User(db.Model):
  id = db.Column(db.Integer, autoincrement=True, primary_key=True)
  # unique:用户名唯一, nullable=False指用户名不能为空;
  name = db.Column(db.String(50), unique=True, nullable=False)
  pwd = db.Column(db.String(100))
  email = db.Column(db.String(30), unique=True)
  phone = db.Column(db.String(30), unique=True)
  info = db.Column(db.Text) # 个人简介
  add_time = db.Column(db.DateTime, default=datetime.now())  # 创建时间
  department_id = db.Column(db.Integer, db.ForeignKey('department.id'))
  todos = db.relationship('Todo', backref='user')
  userlogs = db.relationship('Userlog', backref='user')
  # 部门id与其他表关联,不能随便写

  def __repr__(self):
    return '<User: %s>' %(self.name)


# 部门
class Department(db.Model):
  id = db.Column(db.Integer, autoincrement=True, primary_key=True)
  name = db.Column(db.String(50), unique=True, nullable=False)
  # 反向引用: user就包含一个属性, department
  users = db.relationship('User', backref='department')
  todos = db.relationship('Todo', backref='department')
  def __repr__(self):
    return '<Department: %s>' %(self.name)

class Todo(db.Model):
  id = db.Column(db.Integer, autoincrement=True, primary_key=True)
  name = db.Column(db.String(200), nullable=False)
  add_time = db.Column(db.DateTime, default=datetime.now()) # 创建时间
  status = db.Column(db.Boolean, default=False) # 任务状态, 默认为Flase(未完成)
  department_id = db.Column(db.Integer, db.ForeignKey('department.id'))
  user_id = db.Column(db.Integer,db.ForeignKey('user.id') )

  def __repr__(self):
    return '<Todo: %s>' % (self.id)

# 用户登录日志
class Userlog(db.Model):
  id = db.Column(db.Integer, autoincrement=True, primary_key=True)
  add_time = db.Column(db.DateTime, default=datetime.now()) # 创建时间
  ip = db.Column(db.String(200), nullable=False) # 登录ip
  area = db.Column(db.String(200)) # 用户登录地点
  user_id = db.Column(db.Integer, db.ForeignKey('user.id')) # 外键


  def __repr__(self):
    return '<Userlog: %s>' % (self.ip)

views.py:

from flask import render_template, request, redirect, url_for, session

from models import app, Todo, db, Department,User
from mDB import isPasswdOk,isUserExist,addUser
from forms import LoginForm,RegisterForm
@app.route('/')
def index():
  return render_template('base.html')
@app.route('/register/')
def register():
  form = RegisterForm()
  if form.validate_on_submit():
    user = request.form('user')
    passwd = request.form('passwd')
  return render_template('register.html')

@app.route('/login/',methods=['GET','POST'])
def login():
  form = LoginForm()
  # 如果是post方法并且表单验证通过的话, 返回True;
  if form.validate_on_submit():
    # 1). 获取用户提交的表单信息
    # print(form.data) 是字典类型, 内容如下:
    # {'user': 'westos', 'passwd': 'westos', 'submit': True }
    user = form.data['user']
    passwd = form.data['passwd']
    # 2. 判断用户名和密码是否正确

    if isPasswdOk(user, passwd):
      # 将用户名和密码信息存储到session中;
      session['user'] = user
      session['passwd'] = passwd
      # 如果登陆成功, 跳转到主页;
      return redirect(url_for('todo_list'))
    else:
      # 如果登陆失败, 重新登陆;
      return render_template('login.html',form=form, message="用户名或者密码错误")
  return render_template('login.html', form=form)
@app.route('/logout/')
def logout():
  session.pop('user',None)
  session.pop('passwd',None)
  return redirect(url_for('todo_list'))
# 任务的增删改查
@app.route('/todo/add/', methods=['POST'])
def todo_add():
  # 获取提交的任务信息
  name = request.form['todo_name']
  part = request.form['part']
  # 添加完成之后, 返回任务列表显示页面
  u = User.query.filter_by(name=session['user']).first()
  id = u.id
  todo = Todo(name=name, department_id=part, user_id=id)
  db.session.add(todo)
  db.session.commit()

  return redirect(url_for('todo_list'))

@app.route('/todo/delete/<int:id>/')
def todo_delete(id):
  u = Todo.query.filter_by(id=id).first()
  db.session.delete(u)
  db.session.commit()
  return redirect(url_for('todo_list'))

@app.route('/list/')
def todo_list():
  # 1). 从数据库中查询
  todos = Todo.query.all()
  parts = Department.query.all()

  return render_template('list.html',
              todos = todos,
              parts=parts)

# 修改任务的状态(变成已完成状态/变成未完成状态)
@app.route('/todo/undo/<int:id>/')
def undo(id):
  todo = Todo.query.filter_by(id=id).first()
  todo.status = False
  db.session.commit()
  # 更新状态后, 返回任务列表页
  return redirect(url_for('todo_list'))

@app.route('/todo/done/<int:id>/')
def done(id):
  todo = Todo.query.filter_by(id=id).first()
  todo.status = True
  db.session.commit()
  # 更新状态后, 返回任务列表页
  return redirect(url_for('todo_list'))

run.py:

# 项目真实运行脚本

from models import app,db
# 导入编写的视图函数和路由
from views import *

app.run()

python 实现任务管理清单案例

python 实现任务管理清单案例

python 实现任务管理清单案例

以上这篇python 实现任务管理清单案例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持三水点靠木。

Python 相关文章推荐
跟老齐学Python之集合(set)
Sep 24 Python
python下os模块强大的重命名方法renames详解
Mar 07 Python
python 给DataFrame增加index行名和columns列名的实现方法
Jun 08 Python
python 读取文本文件的行数据,文件.splitlines()的方法
Jul 12 Python
python实现C4.5决策树算法
Aug 29 Python
利用anaconda保证64位和32位的python共存
Mar 09 Python
PyQt5重写QComboBox的鼠标点击事件方法
Jun 25 Python
Django中提供的6种缓存方式详解
Aug 05 Python
python使用requests.session模拟登录
Aug 09 Python
Python3 解决读取中文文件txt编码的问题
Dec 20 Python
pycharm安装及如何导入numpy
Apr 03 Python
python操作toml文件的示例代码
Nov 27 Python
python多进程 主进程和子进程间共享和不共享全局变量实例
Apr 25 #Python
python使用Thread的setDaemon启动后台线程教程
Apr 25 #Python
python 在threading中如何处理主进程和子线程的关系
Apr 25 #Python
Python多线程:主线程等待所有子线程结束代码
Apr 25 #Python
解决python父线程关闭后子线程不关闭问题
Apr 25 #Python
Python标准库:内置函数max(iterable, *[, key, default])说明
Apr 25 #Python
python except异常处理之后不退出,解决异常继续执行的实现
Apr 25 #Python
You might like
笑谈配置,使用Smarty技术
2007/01/04 PHP
php检测图片木马多进制编程实践
2013/04/11 PHP
php多个文件及图片上传实例详解
2014/11/10 PHP
php基于curl实现随机ip地址抓取内容的方法
2016/10/11 PHP
ThinkPHP实现图片上传操作的方法详解
2017/05/08 PHP
对JavaScript的eval()中使用函数的进一步讨论
2008/07/26 Javascript
动态创建的表格单元格中的事件实现代码
2008/12/30 Javascript
javascript web页面刷新的方法收集
2009/07/02 Javascript
ExtJS 入门
2010/10/29 Javascript
IE下JS读取xml文件示例代码
2013/08/05 Javascript
Jquery chosen动态设置值实例介绍
2013/08/08 Javascript
Event altKey,ctrlKey,shiftKey属性解析
2013/12/18 Javascript
精通JavaScript的this关键字
2020/05/28 Javascript
微信小程序动态添加分享数据
2017/06/14 Javascript
AngularJS ui-router刷新子页面路由的方法
2018/07/23 Javascript
js基础之事件捕获与冒泡原理
2019/10/09 Javascript
详解Howler.js Web音频播放终极解决方案
2020/08/23 Javascript
[02:08]2014DOTA2国际邀请赛 430专访:力争取得小组前二
2014/07/11 DOTA
python中正则表达式的使用详解
2014/10/17 Python
Centos 升级到python3后pip 无法使用的解决方法
2018/06/12 Python
用Python编写一个高效的端口扫描器的方法
2018/12/20 Python
关于python字符串方法分类详解
2019/08/20 Python
Python datetime 格式化 明天,昨天实例
2020/03/02 Python
IDLE下Python文件编辑和运行操作
2020/04/25 Python
html5 冒号分隔符对齐的实现
2019/07/31 HTML / CSS
国际知名军事风格休闲装品牌:Alpha Industries(阿尔法工业)
2017/05/24 全球购物
咖啡店自主创业商业计划书
2014/01/22 职场文书
商务英语广告词大全
2014/03/18 职场文书
主持人演讲稿
2014/05/13 职场文书
竞聘演讲稿开场白
2014/08/25 职场文书
土建施工员岗位职责
2015/04/11 职场文书
拒绝盗图!教你怎么用python给图片加水印
2021/06/04 Python
windows11怎么查看wifi密码? win11查看wifi密码的技巧
2021/11/21 数码科技
一文搞懂MySQL索引页结构
2022/02/28 MySQL
vue+echarts实现多条折线图
2022/03/21 Vue.js
基于Python实现对比Exce的工具
2022/04/07 Python