models.py 2.3 KB
Newer Older
1 2 3 4 5 6 7 8
#! /usr/bin/env python
"""
Database models for lolbot.
"""

from __future__ import print_function, unicode_literals

import requests
9
from datetime import datetime
10
from bs4 import BeautifulSoup
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
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:
69 70
            r = requests.get(url)
            if r.status_code == 200:
71 72 73 74 75
                if 'text/html' in r.headers['content-type']:
                    dom = BeautifulSoup(r.content, 'html.parser')
                    self.title = dom.title.string
                else:
                    self.title = r.headers['content-type']
76 77
            else:
                self.title = "Error: HTTP %s" % r.status_code
78 79 80 81 82 83

    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)