學習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,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/<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>  <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 %}