models.py 1.95 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
from mechanize import Browser
from datetime import datetime
from sqlalchemy import (Column, String, Text, Integer, DateTime)
from sqlalchemy.ext.declarative import (declarative_base)


Model = declarative_base()


class Log(Model):
    """
    This class represents an event in the log table and inherits from a SQLAlchemy
    convenience ORM class.
    """

    __tablename__ = "log"

    id = Column(Integer, primary_key=True)
    timestamp = Column(DateTime)
    nickname = Column(String(20))
    text = Column(Text)

    def __init__(self, nickname, text, timestamp=None):
        """
        Creates an event log for the IRC logger.
        """
        if timestamp is None:
            timestamp = datetime.now()
        self.timestamp = timestamp
        self.nickname = nickname
        self.text = text

    def __repr__(self):
        return "(%s) %s: %s" % (self.timestamp.strftime("%Y-%m-%d %H:%M:%S"), self.nickname, self.text)


class Url(Model):
    """
    This class represents a saved URL and inherits from a SQLAlchemy convenience
    ORM class.
    """

    __tablename__ = "url"

    id = Column(Integer, primary_key=True)
    timestamp = Column(DateTime)
    nickname = Column(String(20))
    url = Column(String(200), unique=True)
    title = Column(Text)

    def __init__(self, nickname, url, title=None, timestamp=None):
        if timestamp is None:
            timestamp = datetime.now()
        self.timestamp = timestamp
        self.nickname = nickname
        self.url = url
        self.title = title

        # populate the title from the URL if not given.
        if title is None:
            try:
                br = Browser()
                br.open(self.url)
                self.title = br.title()
            except Exception:
                self.title = ''

    def __repr__(self):
        if not self.title:
            return "%s: %s" % (self.nickname, self.url)
        else:
            return "%s: %s - %s" % (self.nickname, self.url, self.title)