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入门_条件控制(详解)
May 16 Python
python对配置文件.ini进行增删改查操作的方法示例
Jul 28 Python
Python人脸识别初探
Dec 21 Python
python修改list中所有元素类型的三种方法
Apr 09 Python
Python高级用法总结
May 26 Python
python读取图片并修改格式与大小的方法
Jul 24 Python
解决安装pycharm后不能执行python脚本的问题
Jan 19 Python
Python实现K折交叉验证法的方法步骤
Jul 11 Python
Pandas时间序列重采样(resample)方法中closed、label的作用详解
Dec 10 Python
如何在django中添加日志功能
Feb 06 Python
Python IDLE或shell中切换路径的操作
Mar 09 Python
Python中的xlrd模块使用整理
Jun 15 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
PHP正则表达式 /i, /is, /s, /isU等介绍
2014/10/23 PHP
php实现word转html的方法
2016/01/22 PHP
PHP is_array() 检测变量是否是数组的实现方法
2016/06/13 PHP
php微信开发之上传临时素材
2016/06/24 PHP
Laravel5.5 动态切换多语言的操作方式
2019/10/25 PHP
不错的JS中变量相关的细节分析
2007/08/13 Javascript
javascript中的作用域scope介绍
2010/12/28 Javascript
javascript仿php的print_r函数输出json数据
2013/09/13 Javascript
JS实现很酷的水波文字特效实例
2015/02/26 Javascript
微信小程序 wxapp地图 map详解
2016/10/31 Javascript
利用jquery实现验证输入的是否是数字、小数,包含保留几位小数
2016/12/07 Javascript
浅谈Vue的基本应用
2016/12/27 Javascript
JavaScript字符串对象(string)基本用法示例
2017/01/18 Javascript
Js apply方法详解
2017/02/16 Javascript
js转换对象为xml
2017/02/17 Javascript
javascript 秒表计时器实现代码
2017/03/09 Javascript
Mongoose实现虚拟字段查询的方法详解
2017/08/15 Javascript
从对象列表中获取一个对象的方法,依据关键字和值
2017/09/20 Javascript
node.js用fs.rename强制重命名或移动文件夹的方法
2017/12/27 Javascript
jQuery实现的网站banner图片无缝轮播效果完整实例
2019/01/28 jQuery
Flutter实现仿微信底部菜单栏功能
2019/09/18 Javascript
在Python中使用lambda高效操作列表的教程
2015/04/24 Python
Python tkinter模块中类继承的三种方式分析
2017/08/08 Python
python爬虫 使用真实浏览器打开网页的两种方法总结
2018/04/21 Python
python2与python3爬虫中get与post对比解析
2019/09/18 Python
HTML5 CSS3新的WEB标准和浏览器支持
2009/07/16 HTML / CSS
我的applet原先好好的, 一放到web server就会有问题,为什么?
2016/05/10 面试题
介绍一下.NET构架下remoting和webservice
2014/05/08 面试题
化妆品店促销方案
2014/02/24 职场文书
党校培训自我鉴定范文
2014/04/10 职场文书
《有趣的发现》教学反思
2014/04/15 职场文书
幼儿园2014年度工作总结
2014/11/10 职场文书
2014年计划生育协会工作总结
2014/11/14 职场文书
刑事案件上诉状
2015/05/23 职场文书
关于环保的广播稿
2015/12/17 职场文书
mysql5.7的安装及Navicate长久免费使用的实现过程
2021/11/17 MySQL