Source

bPlog / utils.py

#!/usr/bin/python
# -*- coding: utf-8 -*-

# project - description
# Copyright (C) 2010  Cédric Bonhomme - http://cedricbonhomme.org/
#
# For more information : http://bitbucket.org/cedricbonhomme/
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>

__author__ = "Cedric Bonhomme"
__version__ = "$Revision: 0.1 $"
__date__ = "$Date: 2011/02/25 $"
__copyright__ = "Copyright (c) Cedric Bonhomme"
__license__ = "GPLv3"

import sqlite3
from operator import itemgetter

def create_base():
    """
    Create the base of locations if not exists.
    """
    sqlite3.register_adapter(str, lambda s : s.decode('utf-8'))
    conn = sqlite3.connect("./locations.db", isolation_level = None)
    c = conn.cursor()
    c.execute('''create table if not exists longitude (longitude text, latitude text, utime text PRIMARY KEY)''')
    conn.commit()
    c.close()

def add_location(longitude, latitude, utime):
    """
    Add a new location to the database.
    """
    c = None
    try:
        conn = sqlite3.connect("./locations.db", isolation_level = None)
        c = conn.cursor()
        c.execute('insert into longitude values (?,?,?)', (longitude, latitude, utime))
    except sqlite3.IntegrityError:
        # feed already in the base
        pass
    finally:
        conn.commit()
        c.close()

def get_locations():
    """
    Return the list of locations.
    """
    locations = []
    try:
        conn = sqlite3.connect("./locations.db", isolation_level = None)
        c = conn.cursor()
        locations = c.execute("SELECT * FROM longitude").fetchall()
    except:
        pass
    return sorted(locations, key=itemgetter(2), reverse=True)