flask mongodb code example

Example 1: mongoalchemy flask

from flask import Flask
from flask.ext.mongoalchemy import MongoAlchemy
app = Flask(__name__)
app.config['MONGOALCHEMY_DATABASE'] = 'library'
db = MongoAlchemy(app)

class Author(db.Document):
    name = db.StringField()

class Book(db.Document):
    title = db.StringField()
    author = db.DocumentField(Author)
    year = db.IntField()

Example 2: mongoalchemy flask

$ [sudo] pip install Flask-MongoAlchemy

Example 3: mongodb flask tutorial

#!/usr/bin/env python# encoding: utf-8import jsonfrom flask import Flask, request, jsonifyfrom flask_mongoengine import MongoEngineapp = Flask(__name__)app.config['MONGODB_SETTINGS'] = {    'db': 'your_database',    'host': 'localhost',    'port': 27017}db = MongoEngine()db.init_app(app)class User(db.Document):    name = db.StringField()    email = db.StringField()    def to_json(self):        return {"name": self.name,                "email": self.email}@app.route('/', methods=['GET'])def query_records():    name = request.args.get('name')    user = User.objects(name=name).first()    if not user:        return jsonify({'error': 'data not found'})    else:        return jsonify(user.to_json())@app.route('/', methods=['PUT'])def create_record():    record = json.loads(request.data)    user = User(name=record['name'],                email=record['email'])    user.save()    return jsonify(user.to_json())@app.route('/', methods=['POST'])def update_record():    record = json.loads(request.data)    user = User.objects(name=record['name']).first()    if not user:        return jsonify({'error': 'data not found'})    else:        user.update(email=record['email'])    return jsonify(user.to_json())@app.route('/', methods=['DELETE'])def delete_record():    record = json.loads(request.data)    user = User.objects(name=record['name']).first()    if not user:        return jsonify({'error': 'data not found'})    else:        user.delete()    return jsonify(user.to_json())if __name__ == "__main__":    app.run(debug=True)