1. Benoit Chesneau
  2. Pypaste

Source

Pypaste / friendpaste / loader.py

The default branch has multiple heads

# -*- coding: utf-8 -
#
# Copyright 2008 by Benoît Chesneau <benoict@e-engura.com>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

from glob import glob
import os
import sys

from friendpaste import settings

_install_hooks = []
def install_hook(f):
    """Decorator to register install hook.
    ex. 
        @install_hook
        def custom_setup():
            ...
    """
    _install_hooks.append(f)
    return f

def install():
    """ execute each install hooks registered by
    the decorator """
    global _install_hooks
    print "Setup QuickNap"
    for a in _install_hooks:
        sys.stderr.write("do %s\n" % a.__name__)
        a()

@install_hook
def create_db():
    """create the db if it don't exist"""
    from couchdb import Server
    couchdb_server = Server(settings.SERVER_URI)
    try:
        db = couchdb_server.create(settings.DATABASE_NAME)
    except:
        pass
        
def load_file(fname):
    f = file(fname, 'r')
    data = f.read()
    f.close
    return data
        
def load_views():
    from couchdb import Server
    
    couchdb_server = Server(settings.SERVER_URI)
    db = couchdb_server[settings.DATABASE_NAME]
    
    design_path = os.path.join(os.path.dirname(__file__), '_design')
    print "\nLoad CouchDB views ..."
    for name in os.listdir(design_path):
        path = os.path.join(design_path,name)
        views = {}
        for view in os.listdir(path):
            views[view] = {}
            for js in glob(os.path.join(path, view, '*.js')):
                if os.path.basename(js) == 'map.js':
                    views[view]['map'] = load_file(js)
                if os.path.basename(js) == 'reduce.js':
                    views[view]['reduce'] = load_file(js)
            print "add %s/%s" % (name, view)
        try:
            db['_design/%s' % name] = {
                'language': 'javascript',
                'views': views
            }
        except:
            v = db['_design/%s' % name] 
            v['views'] = views
            db['_design/%s' % name] = v