Source

MyHost / src / database / couchdb.py

#!/usr/bin/env python

# -*- coding: utf-8 -*-

"""
Tools to deal with data from external data bases
"""
__author__ = "Frank Becker <fb@alien8.de>"
__version__ = "$Revision: 0.0 $"
__date__ = "$Date: YDATE $"
__copyright__ = "Copyright (c) 2010 Frank Becker"
__license__ = "Python"

from datetime import datetime
import couchdbkit

class Host(couchdbkit.Document):
    """CouchDB doc for Host"""

    def save(self):
        self.date_updated = datetime.utcnow()
        if not self.date_created:
            self.date_created = datetime.utcnow()
        super(Host, self).save()

    name = couchdbkit.StringProperty()
    date_updated = couchdbkit.DateTimeProperty()
    date_created = couchdbkit.DateTimeProperty()


def db_connect():
    """connect to db"""

    try:
        server = couchdbkit.Server(uri="http://alzey.osrc.amd.com:5984")
    except:
        return False

    db = server.get_or_create_db("myhost_hosts")

    return db

def db_register(doc_class, db):
    """Register Document class to DB and return it

    FIXME (a8): This doesn't work, take care in what namespace Host() is
    """

    try:
        setattr(doc_class, 'set_db', db)
    except:
        return False

    return doc_class

def save_or_create_host(cls, name=None, **kwargs):
    """

    Args:
        cls registered Host() class
        name=None, **kwargs

    Returns:

        host obj

    """
    if not name:
        return False

    host = cls(name=name, date_created=datetime.utcnow())
    for key, value in kwargs.items():
        setattr(host, key, value)
    try:
        host.save()
    except:
        return False

    return host

def send_view(path):
    """
    send design document to db
    """
    couchdbkit.designer.push(path, db_connect())

def get_all_hosts():
    """

    Args:


    Returns:

    """
    return Host.view("hosts/all")

def get_hosts_by_filter(**kwargs):
    """

    Returns a list of filtered hosts. Make sure Host() is in the namespace and
    it has a db set. The list is sorted by the last update of the host in the
    db.

    Example:
    * all hosts w/ the name eris
        get_hosts_by_filter(name='eris')
    * the last updated hosts w/ the name eris
        get_hosts_by_filter(name='eris')[0]

    Args:
        filter are key=value requirements


    Returns:
        list of hosts sorted by Host.date_updated

    """

    if kwargs:
        hosts = Host.view("hosts/all").all()

        for key, value in kwargs.items():
            hosts = filter(
                lambda h: hasattr(h, key) and getattr(h, key) == value, hosts
            )
    else:
        hosts = []

    return sorted(hosts, key=lambda host: host.date_updated)


def main():
    """ main
    """
    db_connect()

if __name__ == '__main__':
    main()

# vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4 fileencoding=utf-8 :