flask+mongodb实现简单todolist应用

学习mongodb的小练习
效果
点击submit,显示如下列表
flask+mongodb实现简单todolist应用_第1张图片
点击done,unifinished 变为 finished
flask+mongodb实现简单todolist应用_第2张图片
点击delete删除
flask+mongodb实现简单todolist应用_第3张图片
结构
todolist/
├── app.py
└── templates
├── base.html
└── index.html

代码
app.py

from flask import Flask, jsonify, request, abort,url_for,render_template,redirect
from time import time
from bson.objectid import ObjectId
from bson.json_util import dumps
import pymongo

app = Flask(__name__)

mongo = pymongo.MongoClient('127.0.0.1', 27017)
db = mongo.todos

class Todo(object):
    @classmethod
    def create_doc(cls, content):
        return {
            'content': content,
            'created_at': time(),
            'is_finished': False,
            'finished_at': None
        }

@app.route('/todo/',methods=['GET'])
def index():
    todos = db.todos.find({})
    return  render_template('index.html',todos=todos)

@app.route('/todo/', methods=['POST'])
def add():
    content = request.form.get('content', None)
    if not content:
        abort(400)
    db.todos.insert(Todo.create_doc(content))
    return redirect('/todo/')

@app.route('/todo//finished')
def finish(content):
    result = db.todos.update_one(
        {'content':content},
        {
            '$set': {
                'is_finished': True,
                'finished_at': time()
            }
        }    
    )
    return redirect('/todo/')

@app.route('/todo/')
def delete(content):
    result = db.todos.delete_one(
        {'content':content}
    )
    return redirect('/todo/')

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

templates/base.html


<html>
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta content="width=device-width, initial-scale=1.0" name="viewport"/>
head>
<body>
   {% block content %}
   {% endblock  %}
body>
html>

templates/index.html

{% extends 'base.html' %}
{% block content %}
<form action="{{ url_for('index') }}" method=post class=add-entry>
    <h2>todo list:h2>
       <textarea name=content rows=2 cols=20>textarea>
       <input type=submit value=submit>
form>
<ul>
    {% for todo in todos %}
    <li><p>{{todo.content}}
        <a href="{{ url_for('delete',content=todo.content)}}">deletea>  <a href="{{ url_for('finish',content=todo.content)}}">donea>p>
        {%- if todo.is_finished -%}
                <p>finishedp>
        {%- else-%}
                <p>unfinishedp>
        {%- endif %}
    li>
    {% endfor %}
ul>
{% endblock %}

你可能感兴趣的:(python,python,web)