flask+mongodb实现简单todolist应用

来源:互联网 发布:java nio与io的区别 编辑:程序博客网 时间:2024/06/06 20:01

学习mongodb的小练习
效果
点击submit,显示如下列表
这里写图片描述
点击done,unifinished 变为 finished
这里写图片描述
点击delete删除
这里写图片描述
结构
todolist/
├── app.py
└── templates
├── base.html
└── index.html

代码
app.py

from flask import Flask, jsonify, request, abort,url_for,render_template,redirectfrom time import timefrom bson.objectid import ObjectIdfrom bson.json_util import dumpsimport pymongoapp = Flask(__name__)mongo = pymongo.MongoClient('127.0.0.1', 27017)db = mongo.todosclass 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/<content>/finished')def finish(content):    result = db.todos.update_one(        {'content':content},        {            '$set': {                'is_finished': True,                'finished_at': time()            }        }        )    return redirect('/todo/')@app.route('/todo/<content>')def delete(content):    result = db.todos.delete_one(        {'content':content}    )    return redirect('/todo/')if __name__ == '__main__':    app.run(debug=True)

templates/base.html

<!DOCTYPE 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)}}">delete</a>&nbsp&nbsp<a href="{{ url_for('finish',content=todo.content)}}">done</a></p>        {%- if todo.is_finished -%}                <p>finished</p>        {%- else-%}                <p>unfinished</p>        {%- endif %}    </li>    {% endfor %}</ul>{% endblock %}
原创粉丝点击