Last active
September 22, 2015 04:06
-
-
Save jincod/dbe710b5fe5ad9996971 to your computer and use it in GitHub Desktop.
A la Evernote with supporting markdown
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from flask import Flask, request, abort, render_template | |
from bson import ObjectId | |
from flask.ext.pymongo import PyMongo | |
from datetime import datetime | |
import json | |
from flask import Response | |
app = Flask(__name__) | |
mongo = PyMongo(app) | |
class MongoDocumentEncoder(json.JSONEncoder): | |
def default(self, o): | |
if isinstance(o, datetime): | |
return o.isoformat() | |
elif isinstance(o, ObjectId): | |
return str(o) | |
return json.JSONEncoder(self, o) | |
@app.route("/") | |
def main_page(): | |
return render_template("notes.html", notes=mongo.db.notes.find()) | |
@app.route("/note/<ObjectId:note_id>", methods=["GET"]) | |
def one_note_page(note_id): | |
note = mongo.db.notes.find_one({"_id": note_id}) | |
return render_template( | |
"note.html", notes=mongo.db.notes.find(), note=note) | |
# API | |
@app.route("/api/note", methods=["GET"]) | |
def get_notes(): | |
cursor = mongo.db.notes.find() | |
notes = [] | |
for note in cursor: | |
notes.append(note) | |
return Response( | |
json.dumps(notes, cls=MongoDocumentEncoder), | |
mimetype='application/json') | |
@app.route("/api/note/<ObjectId:note_id>", methods=["GET"]) | |
def get_note(note_id): | |
note = mongo.db.notes.find_one({"_id": note_id}) | |
if note: | |
return Response( | |
json.dumps(note, cls=MongoDocumentEncoder), | |
mimetype='application/json') | |
abort(404) | |
@app.route("/api/note/<ObjectId:note_id>", methods=["DELETE"]) | |
def delete_not(note_id): | |
mongo.db.notes.remove({"_id": note_id}) | |
return Response("OK", mimetype='application/json') | |
@app.route("/api/note", methods=["POST"]) | |
def new_note(): | |
note = request.form['note'] | |
title = request.form['title'] | |
mongo.db.notes.save({'title': title, 'note': note, | |
'date_created': datetime.utcnow()}) | |
return Response("OK", mimetype='application/json') | |
if __name__ == "__main__": | |
app.run(debug=True) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment