Created
June 2, 2015 20:10
-
-
Save a-h/e32024a2751fbb3b6755 to your computer and use it in GitHub Desktop.
Flask and Mongo
This file contains hidden or 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
import json | |
from bson import json_util, ObjectId | |
from flask import Flask | |
from flask import request | |
import flask | |
from pymongo import MongoClient | |
app = Flask(__name__) | |
app.debug = True | |
client = MongoClient() | |
json_mime_type = "application/json" | |
@app.route('/applications/', methods=['GET', 'POST', 'PUT']) | |
def applications_list(): | |
db = client.applications | |
applications = db.applications | |
if request.method == 'GET': | |
result = applications_list_json(applications) | |
return flask.Response(response=result, status=200, content_type=json_mime_type) | |
elif request.method == 'POST' or request.method == "PUT": | |
application = request.get_json() | |
application_id = applications_put_json(applications, application) | |
return flask.jsonify(id=application_id) | |
def applications_list_json(applications): | |
result = list(applications.find()) | |
return flask.json.dumps(result, default=json_util.default) | |
def applications_put_json(applications, application): | |
result = applications.insert_one(application) | |
return result.inserted_id | |
@app.route("/applications/<application_id>") | |
def applications_get(application_id): | |
db = client.applications | |
applications = db.applications | |
result = list(applications.find({"_id": ObjectId(application_id)})) | |
if len(result) > 0: | |
json_result = flask.json.dumps(result, default=json_util.default) | |
return flask.Response(response=json_result, status=200, content_type=json_mime_type) | |
else: | |
return flask.abort(404) | |
@app.route("/applications/clear") | |
def applications_clear(): | |
db = client.applications | |
applications = db.applications | |
applications.remove() | |
return flask.json.jsonify(success="OK") | |
if __name__ == '__main__': | |
app.run() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment