Source

rankademy / www / app.py

import os
from flask import Flask, g
import simplejson as json
from werkzeug import secure_filename

try:
    import mongokit as mongo
    from models import models
except:
    import pymongo as mongo

#import views
from lectures import LecturesAPI
from courses.course_view import course
from users.user_view import user

from main_view import main

LOCAL_CONFIG_FILE = "configlocal.json"
PROD_CONFIG_FILE = "/home/dotcloud/current/config.json"


application = Flask(__name__) #it has such name to separate app-name from module has
application.g = g

def init_settings():
    '''reads configs and initialize api settings object '''
    settings = None
    if os.environ.has_key("RANKADEMY") and os.environ["RANKADEMY"] == 'production':
        data = json.load(open(PROD_CONFIG_FILE, 'r'))
        settings = data["settings"]
    else:
        data = json.load(open(LOCAL_CONFIG_FILE, 'r'))
        settings = data["settings"]
    #filter out keys with None value
    map(settings.pop,
            [key for key, val in settings.iteritems() if val is None ])
    if settings:
        application.config.update(settings)

def connect_db():
    ''' connects to db and inits db connection'''
    db = None
    if application.config.has_key("DATABASE"):
        dbconf = application.config["DATABASE"]
        conn = mongo.Connection(dbconf['host'], dbconf['port'])
        db = conn[dbconf['db']]
        if dbconf.has_key('user'):
            db.authenticate(dbconf['user'], dbconf['password'])
        models.register(conn)
    return db, models

@application.before_request
def before_request():
    g.db, g.models = connect_db()

@application.teardown_request
def teardown_request(exception):
    if hasattr(application.g, 'db'):
       g.db.connection.disconnect()

def register_api(view, endpoint, url, pk='id', pk_type='int'):
    view_func = view.as_view(endpoint)
    application.add_url_rule(url, defaults={pk: None},
                    view_func=view_func, methods=['GET', 'POST'])
    application.add_url_rule('%s<%s:%s>' % (url, pk_type, pk),
                    view_func=view_func,
                    methods=['GET', 'PUT', 'DELETE'])

#init api settings:
init_settings()

#register api-views
register_api(LecturesAPI, 'lectures_api', '/lectures/', pk='lid')

#register blueprints - url_for('main.index') or url_for('course.index')
application.register_blueprint(main)
application.register_blueprint(course, prefix='/course')
application.register_blueprint(user, prefix='/user')