详解python Todo清单实战


Posted in Python onNovember 01, 2018

Todo清单

需要实现的功能有添加任务、删除任务、编辑任务,操作要关联数据库。

任务需要绑定用户,部门。用户需要绑定部门。

{#自己编写一个基类模板#}
{% 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" >首页<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" >新闻</a></li>
        <li><a href="#" 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" >国内</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" >登陆用户</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>
        {% endif %}


        <li><a href="/register/" rel="external nofollow" ><span class="glyphicon glyphicon-log-out"></span>
            注册</a></li>
      </ul>
    </div><!-- /.navbar-collapse -->
  </div><!-- /.container-fluid -->
</nav>
{% endblock %}

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


  {% endblock %}

  {% block footer %}
<div class="footer" style="margin: 0 auto">

    宇宙大魔王

</div>
{% endblock %}
{% endblock %}
{#列表清单#}
{% 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-remove"></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.depart.name }}</td>
            <td>
{#              <a href="/todo/delete/{{ todo.id }}/" rel="external nofollow" rel="external nofollow" role="button">删除</a>#}
{#              <a href="/todo/delete/{{ todo.id }}/" rel="external nofollow" rel="external nofollow" class="btn btn-primary btn-lg active" role="button">删除</a>#}
                <a href="/todo/delete/{{ todo.id }}/" rel="external nofollow" class="btn btn-danger" role="button"><span
              class="glyphicon glyphicon-remove"></span> 删除</a>
            </td>
          </tr>

        {% endfor %}


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

{% endblock %}
# 数据库操作文件 todo_models.py
from datetime import datetime
import pymysql
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:sheen@localhost/todo'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True
db = SQLAlchemy(app)
bootstrap = Bootstrap(app)

class User(db.Model):
  id = db.Column(db.INTEGER,autoincrement=True,primary_key=True)
  name = db.Column(db.String(30),unique=True)
  pwd = db.Column(db.String(30))
  add_time = db.Column(db.DateTime, default=datetime.now())
  phone = db.Column(db.String(11))
  email = db.Column(db.String(18),unique=True)
  info = db.Column(db.TEXT)
  department_id = db.Column(db.INTEGER,db.ForeignKey('department.id'))  #部门id与其他表关联
  todo_id = db.relationship('Todo',backref = 'user')
  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(30),unique=True)
  users = db.relationship('User',backref = 'depart')
  todos = db.relationship('Todo',backref = 'depart')
  def __repr__(self):
    return '<Depart:%s>' %(self.name)

class Todo(db.Model):
  id = db.Column(db.INTEGER,autoincrement=True,primary_key=True)
  name = db.Column(db.String(30))
  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'))  #部门id与其他表关联
  user_id = db.Column(db.INTEGER,db.ForeignKey('user.id'))
  def __repr__(self):
    return '<Todo:%s>' % (self.name)
if __name__ == '__main__':
  db.drop_all()
  db.create_all()
  parts = ['人事部','Python开发部','Java开发部']
  partObj = [Department(name=part) for part in parts]
  db.session.add_all(partObj)
  db.session.commit()

  user_1 = User(name='sheen',pwd='123',department_id=2)
  db.session.add(user_1)
  db.session.commit()
# 试图函数程序 todo_views.py
from flask import render_template, url_for, request, redirect
from todo_models import app,Todo,Department,db

@app.route('/')
def index():
  return render_template('base.html')

@app.route('/login/')
def login():
  return render_template('todo_login.html')
@app.route('/list/')
def todo_list():
  todos = Todo.query.all()
  parts = Department.query.all()
  return render_template('todo_list.html',todos=todos,parts=parts)
@app.route('/todo/add/',methods=['POST'])
def add():
  name = request.form['todo_name']  #在todo_list.html文件中表单定义的添加任务input属性name="todo_name"。
  part = request.form['part']
  todo = Todo(name=name,department_id=part,user_id=1)
  db.session.add(todo)
  db.session.commit()
  print('ok')
  return redirect(url_for('todo_list'))
@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'))

@app.route('/todo/delete/<int:id>/')
def todo_del(id):
  todo = Todo.query.filter_by(id=id).first()
  db.session.delete(todo)
  db.session.commit()
  return redirect(url_for('todo_list'))
# 主程序 run.py
from flask import Flask
from todo_models import app
from todo_views import *

if __name__ == '__main__':
  app.run()

list 页面最初显示图

详解python Todo清单实战

当添加任务后,页面显示如下

详解python Todo清单实战

当鼠标点击任务状态时,会发生改变

详解python Todo清单实战

当点击删除按钮时,任务从数据库中删除,也不在页面中显示

详解python Todo清单实战

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。

Python 相关文章推荐
跨平台python异步回调机制实现和使用方法
Nov 26 Python
使用Python的web.py框架实现类似Django的ORM查询的教程
May 02 Python
Python实现计算两个时间之间相差天数的方法
May 10 Python
Python实现的简单dns查询功能示例
May 24 Python
深入浅析Python中的yield关键字
Jan 24 Python
python opencv 图像尺寸变换方法
Apr 02 Python
django缓存配置的几种方法详解
Jul 16 Python
python小程序实现刷票功能详解
Jul 17 Python
Python单元测试与测试用例简析
Nov 09 Python
Tensorflow: 从checkpoint文件中读取tensor方式
Feb 10 Python
python GUI库图形界面开发之PyQt5滚动条控件QScrollBar详细使用方法与实例
Mar 06 Python
python中tkinter复选框使用操作
Nov 11 Python
在Mac下使用python实现简单的目录树展示方法
Nov 01 #Python
对numpy中二进制格式的数据存储与读取方法详解
Nov 01 #Python
使用python获取电脑的磁盘信息方法
Nov 01 #Python
在IPython中执行Python程序文件的示例
Nov 01 #Python
在IPython中进行Python程序执行时间的测量方法
Nov 01 #Python
Python找出微信上删除你好友的人脚本写法
Nov 01 #Python
[原创]Python入门教程4. 元组基本操作
Oct 31 #Python
You might like
php调用mysql存储过程
2007/02/14 PHP
php zend解密软件绿色版测试可用
2008/04/14 PHP
PHP把小数转成整数3种方法
2014/06/30 PHP
php 生成签名及验证签名详解
2016/10/26 PHP
JS仿flash上传头像效果实现代码
2011/07/18 Javascript
js不完美解决click和dblclick事件冲突问题
2012/07/16 Javascript
jQuery 淡入淡出 png图在ie8下有黑色边框的解决方法
2013/03/05 Javascript
纯JavaScript实现的分页插件实例
2015/07/14 Javascript
jQuery Ajax 加载数据时异步显示加载动画
2016/08/01 Javascript
JavaScript面试题大全(推荐)
2016/09/22 Javascript
jQuery排序插件tableSorter使用方法
2017/02/10 Javascript
基于JS实现移动端向左滑动出现删除按钮功能
2017/02/22 Javascript
微信小程序中顶部导航栏的实现代码
2017/03/30 Javascript
Node.js中使用mongoose操作mongodb数据库的方法
2017/09/12 Javascript
js中script的上下放置区别,Dom的增删改创建操作实例分析
2019/12/16 Javascript
antd Select下拉菜单动态添加option里的内容操作
2020/11/02 Javascript
Python多进程编程技术实例分析
2014/09/16 Python
浅谈django2.0 ForeignKey参数的变化
2019/08/06 Python
python3实现带多张图片、附件的邮件发送
2019/08/10 Python
python禁用键鼠与提权代码实例
2019/08/16 Python
python函数装饰器之带参数的函数和带参数的装饰器用法示例
2019/11/06 Python
Python属性和内建属性实例解析
2020/01/14 Python
Python自动登录QQ的实现示例
2020/08/28 Python
Html5 实现微信分享及自定义内容的流程
2019/08/20 HTML / CSS
基于HTML5 的人脸识别活体认证的实现方法
2016/06/22 HTML / CSS
HTML5+CSS3实现机器猫
2016/10/17 HTML / CSS
有机童装:Toby Tiger
2018/05/23 全球购物
舞会礼服和舞会鞋:PromGirl
2019/04/22 全球购物
实习生的自我评价
2014/01/08 职场文书
最新奶茶店创业计划书范文
2014/02/08 职场文书
大班下学期个人总结
2015/02/13 职场文书
婚礼领导致辞大全
2015/07/28 职场文书
2019年聘任书的写作格式及范文!
2019/07/03 职场文书
英语版自我评价,35句话轻松搞定
2019/10/08 职场文书
selenium.webdriver中add_argument方法常用参数表
2021/04/08 Python
如何设计高效合理的MySQL查询语句
2021/05/26 MySQL