Commits

Marc-Alexandre Chan committed 80faf45

fixed several bugs in db module; add methods for status changes in DB objects

Comments (0)

Files changed (1)

     registered= Column(Boolean(), nullable=False, default=False)
     email     = Column(String(64), nullable=True, default='')
 
-    # use setPassword() to hash and set the password in the DB
+    # use set_password() to hash and set the password in the DB
     _password = Column('password', String(64),
                     CheckConstraint('LENGTH(password) == 64'), nullable=False)
 
     # posts - from Prompt.approver relationship
 
-    def __init__(self, r_id, uname, plain_password=None, email=None):
+    def __init__(self, r_id, uname, plain_password=None, email=None, salt=''):
         self.r_id = r_id
         self.uname = uname
         if plain_password:
             self.registered = True
-            self.setPassword(plain_password)
+            self.set_password(plain_password, salt)
         else:
             self.registered = False
-            self.setPassword('default') # won't be usable, registered=False
+            self.set_password('default') # won't be usable, registered=False
 
         if email:
             self.email = email
 
-    def setPassword(self, password, salt=''):
-        self.password = sha256(salt + password).hexdigest()
+    def set_password(self, password, salt=''):
+        self._password = sha256(salt + password).hexdigest()
+
+    def check_password(self, password, salt=''):
+        pwhash = sha256(salt + password).hexdigest()
+        return (pwhash == self._password)
 
     def __repr__(self):
         """ Return a human-readable representation of the User row. """
-        return "<User({r_id}, '{uname}', 'email', {reg})>".format(
+        return "<User({r_id}, '{uname}', '{email}', {reg})>".format(
                 r_id=self.r_id, uname=self.uname, email=self.email,
                 reg='registered' if self.registered else 'unregistered')
 
 
     def __unicode__(self):
         """ Return a friendly string representing a User row. """
-        return "/u/{uname}{email}{reg}".format(
-            uname=self.uname,
-            email=''.join([' <', self.email, '>']) if self.email else '',
-            reg=' (unregistered)' if not self.registered else '')
+        parts = []
+        parts.append(u"/u/{}".format(self.uname))
+        if self.email:
+            parts.append(u"<{}>".format(self.email))
+        if not self.registered:
+            parts.append(u"(unregistered)")
+        return ' '.join(parts)
 
 
 class Prompt(Base):
     def __init__(self, title, text, approver_id, submit_time=None,\
                  user=None, user_id=None, source_url=None, source_thread=None,
                  source_id=None):
-        self.status        = 0
+        self.status        = self.STATUS_NEW
         self.title         = title
         self.text          = text
         self.submit_time   = submit_time if submit_time is not None\
     def get_status_string(self):
         return self.STATUS_TEXT[self.status]
 
+    def set_new(self):
+        """ Set the prompt entry as unqueued. """
+        self.status = self.STATUS_NEW
+    def accept(self):
+        """ Set the prompt entry as accepted for later queuing. """
+        self.status = self.STATUS_ACCEPTED
+
+    def reject(self):
+        """ Set the prompt entry as rejected. """
+        self.status = self.STATUS_REJECTED
+
+    def queue(self, post_time):
+        """ Set the prompt entry as queued for posting at the specified time. """
+        self.status = self.STATUS_QUEUED
+        self.post_time = post_time
+        self.r_post_id = None
+
+    def set_posted(self, post_id):
+        """ Set the prompt entry as posted and store the post id. """
+        self.status = self.STATUS_POSTED
+        self.r_post_id = post_id
+
     def __repr__(self):
         """ Return a human-readable representation of the Prompt row. """
         return "<Prompt(id={id_:d}, status={status}, post_time={tpost}, "\
         else:
             self.status = self.STATUS_QUEUED
 
+    def get_status_string(self):
+        return self.STATUS_TEXT[self.status]
+
+    def set_posted(self, post_id):
+        """ Sets status as posted and records post data. """
+        if not isinstance(post_id, basestring):
+            raise ValueError('post_id must be a string')
+        self.status = self.STATUS_ACTIVE
+        self.r_post_id = post_id
+
+    def set_archived(self):
+        """ Sets status as archived. """
+        self.status = self.STATUS_ARCHIV
+
     def __repr__(self):
         return "<SuggestionThread({time_}, {status}, '{post_id}', {scan_time}, "\
                "'{title}', '{excerpt}')>".format(time_=self.time.__str__(),
         .. _`SQLAlchemy documentation`: http://docs.sqlalchemy.org/en/rel_0_7/core/engines.html#configuring-logging
 
         logformat
-            *Default: '%(asctime)s (%process)d:%(thread)d) [%(name)d:%(levelname)s] %(message)s'
+            *Default: '%(asctime)s (%(process)d:%(thread)d) [%(name)s:%(levelname)s] %(message)s'
 
             Format for log entries. See the Python library's
             ``logging.Formatter`` documentation.
         self._loglevel = kwargs.get('loglevel', logging.WARN)
 
         # create engine, base, session; bind as needed
-        self.base = Declarative
+        self.base = Base
         self.engine = create_engine('sqlite:///' + dbfile, echo=False)
         self.base.metadata.bind = self.engine
 
         # set up logging
         self._loghandler = logging.FileHandler(self._logfile, encoding='utf8')
         fmtr = logging.Formatter(kwargs.get('logformat',\
-            '%(asctime)s (%process)d:%(thread)d) '
-            '[%(name)d:%(levelname)s] %(message)s'),\
+            '%(asctime)s (%(process)d:%(thread)d) '
+            '[%(name)s:%(levelname)s] %(message)s'),\
             kwargs.get('dateformat', '%Y-%m-%d %H:%M:%S'))
         self._loghandler.setFormatter(fmtr)
 
             theLogger = logging.getLogger('sqlalchemy')
             theLogger.removeHandler(self._loghandler)
 
+
     def create_tables(self, table_classes=None):
         """ Create the specified tables.
 
         table_classes
             List of mapped classes. If None, all mapped tables are created.
         """
-        # table_classes = None (creates all); tables = [list of mapped classes]
         table_objects = self._get_table_objects(table_classes)
         self.base.metadata.create_all(tables=table_objects)
 
             List of mapped classes. If None, None is returned.
 
         """
-        tables = None
-
-        if table_classes is not None:
+        if mapped_classes is not None:
             tables = []
             for mapped_class in mapped_classes:
                 tables.append(mapped_class.__table__)
+        else:
+            tables = None
 
         return tables