Commits

Marc-Alexandre Chan committed 283296d

Fixed Unicode issue

  • Participants
  • Parent commits 1e9a4fe

Comments (0)

Files changed (2)

 
     def __repr__(self):
         """ Return a human-readable representation of the User row. """
-        return "<User({r_id}, '{uname}', '{email}', {reg})>".format(
+        return u"<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 __str__(self):
         """ Return a friendly string representing a User row. """
-        return unicode(self).encode('ascii', 'replace')
+        return unicode(self).encode('utf8', 'replace')
 
     def __unicode__(self):
         """ Return a friendly string representing a User row. """
 
     def __repr__(self):
         """ Return a human-readable representation of the Prompt row. """
-        return "<Prompt(id={id_:d}, status={status}, post_time={tpost}, "\
-               "r_post_id={post_id}, submit_time={tsubmit}, "\
-               "user='{user}', approver='{approver}', "\
-               "title='{title}', text='{excerpt}')>".format(
+        return (u"<Prompt(id={id_:d}, status={status}, post_time={tpost}, "
+               u"r_post_id={post_id}, submit_time={tsubmit}, "
+               u"user='{user}', approver='{approver}', "
+               u"title='{title}', text='{excerpt}')>").format(
                               id_=self.id,
                               status=self.get_status_string(),
-                              tpost=str(self.post_time),
-                              post_id=str(self.r_post_id),
-                              tsubmit=str(self.submit_time),
+                              tpost=unicode(self.post_time),
+                              post_id=unicode(self.r_post_id),
+                              tsubmit=unicode(self.submit_time),
                               user=self.user,
                               approver=self.approver.uname if self.approver else '',
                               title=self.title,
                 exctext = self.text
         else:
             exctext = ''
-        return "<SuggestionThread({id_}, {time_}, {status}, '{post_id}', "\
-               "{scan_time}, '{title}', '{excerpt}')>".format(
+        return (u"<SuggestionThread({id_}, {time_}, {status}, '{post_id}', "
+               u"{scan_time}, '{title}', '{excerpt}')>").format(
                     id_=self.id,
-                    time_=str(self.time),
+                    time_=unicode(self.time),
                     status=self.STATUS_TEXT[self.status],
                     post_id=self.r_post_id,
-                    scan_time=str(self.scan_time),
+                    scan_time=unicode(self.scan_time),
                     title=self.title,
                     excerpt=exctext)
 

minibot/events.py

                 self._process_message(msg)
             except (CommandParseError, CommandNameError,
                     CommandParameterError, MissingParameterError) as e:
-                self.log.info("%s: %s", classname(self), e.args[0])
+                self.log.info(u"%s: %s", classname(self), e.args[0])
 
-                self.log.info("%s: Replying to invalid command PM from %s (%s)",
+                self.log.info(u"%s: Replying to invalid command PM from %s (%s)",
                     classname(self), msg.author.name, msg.id)
                 err_cmd = SendErrorMessageCommand.command_parameter(e, msg)
                 self.owner.queue_event(err_cmd)
                 # if bad PM, log; but don't care about replies/comments
                 if msg.subreddit is None:
                     self.log.info(
-                        "%s: Ignoring bad private message from %s (%s)",
+                        u"%s: Ignoring bad private message from %s (%s)",
                         classname(self), msg.author.name, msg.id)
                 msg.mark_as_read()
 
         No validation of the data is performed.
 
         """
-        self.log.debug('%s: Parsing message %s from %s.',
+        self.log.debug(u'%s: Parsing message %s from %s.',
             classname(self), msg.id, msg.author.name)
         msg_data = {}
         text_data = []
             raise CommandParseError(
                     ''.join(["No parameter value in line: \"", line, "\""]))
 
-        self.log.debug('%s: Parsed argument line: %s = %s',
+        self.log.debug(u'%s: Parsed argument line: %s = %s',
             classname(self), field_data[0], field_data[1])
 
         return field_data
         data. If the command name is invalid, raises a CommandNameError. If the
         command parameters are invalid or incomplete, raises a
         CommandParametersError (from the command constructor). """
-        self.log.info('%s: message %s: building command: %s',
+        self.log.info(u'%s: message %s: building command: %s',
             classname(self), msg.id,
             '; '.join(['='.join([x, y]) for x, y in data.iteritems()]))
         if data.has_key('action') and data['action'] in self.cmd_actions.keys():
                 filter(Prompt.status == Prompt.STATUS_QUEUED).\
                 order_by(Prompt.post_time)[0:int(self.queue_rate)]:
             if id_ not in queued_ids:
-                self.log.info("%s: Queuing prompt %d at %s",
+                self.log.info(u"%s: Queuing prompt %d at %s",
                     classname(self), id_,
                     utc_post.strftime("%Y-%m-%d %H:%M:%S UTC"))
                 new_cmd = PostPromptCommand(id_, utc_post)
                 filter(SuggestionThread.status==SuggestionThread.STATUS_QUEUED).\
                 order_by(SuggestionThread.time)[0:int(self.queue_rate)]:
             if id_ not in queued_ids:
-                self.log.info("%s: Queuing thread %d at %s", classname(self),
+                self.log.info(u"%s: Queuing thread %d at %s", classname(self),
                 id_, utc_post.strftime("%Y-%m-%d %H:%M:%S UTC"))
                 new_cmd = PostSuggestionThreadCommand(id_, utc_post)
                 self.owner.queue_event(new_cmd)
         utc_dt_next_end = utc_dt_next + timedelta(days=1)
 
         # find any thread on the next post date
-        self.log.debug("%s: Checking %s to %s", classname(self),
+        self.log.debug(u"%s: Checking %s to %s", classname(self),
             utc_dt_next.strftime("%Y-%m-%d %H:%M:%S UTC"),
             utc_dt_next_end.strftime("%Y-%m-%d %H:%M:%S UTC"))
         num_threads = db.query(SuggestionThread).\
             utc_post_dt = self._utctime(datetime.combine(day_next, post_time))
             new_thread = SuggestionThread(utc_post_dt)
             db.add(new_thread)
-            self.log.info("%s: Added thread for %s to database",
+            self.log.info(u"%s: Added thread for %s to database",
             classname(self), utc_post_dt.strftime("%Y-%m-%d %H:%M:%S UTC"))
-            self.log.debug("%s: %s", classname(self), repr(new_thread))
+            self.log.debug(u"%s: %s", classname(self), repr(new_thread))
             db.commit()
         else: # if a thread is found on that day, no action to take
             pass
         db.commit()
         self.added = True
 
-        self.log.info("%s: Added prompt '%s' (%d) to database queue.",
+        self.log.info(u"%s: Added prompt '%s' (%d) to database queue.",
             classname(self), p['title'], new_prompt.id)
-        self.log.debug("%s: %s", classname(self), repr(new_prompt))
+        self.log.debug(u"%s: %s", classname(self), repr(new_prompt))
 
         db.close()
 
     def _run_reddit(self):
         self.msg.mark_as_read()
-        self.log.debug("%s: Marked message %s as read.",
+        self.log.debug(u"%s: Marked message %s as read.",
             classname(self), self.msg.name)
 
         reply_topic = "Prompt added"
         self.prompt.reject()
         db.commit()
 
-        log.info("%s: Removed prompt '%s' (%d) from database queue.",
+        log.info(u"%s: Removed prompt '%s' (%d) from database queue.",
                  classname(self), self.prompt.title, self.prompt.id)
 
         db.close()
         log = self.res['logger']
 
         self.msg.mark_as_read()
-        log.debug("%s: Marked message %s as read.",
+        log.debug(u"%s: Marked message %s as read.",
                   classname(self), self.msg.name)
 
         reply_title = "Prompt deleted"
         db.commit()
         self.updated = True
         self.log.info(
-            "%s: Updated prompt '%s' (%d) in database queue.",
+            u"%s: Updated prompt '%s' (%d) in database queue.",
             classname(self), p['title'], prompt.id)
-        self.log.debug("%s: %s", classname(self), repr(prompt))
+        self.log.debug(u"%s: %s", classname(self), repr(prompt))
         db.close()
 
     def _run_reddit(self):
 
         # take care of things reddit-side
         self.msg.mark_as_read()
-        self.log.debug("%s: Marked message %s as read.",
+        self.log.debug(u"%s: Marked message %s as read.",
                     classname(self), self.msg.name)
 
         reply_title = "Prompt updated"
     def start(self):
         self.log = self.res['logger']
         self.res['reddit'].compose_message(self.user, self.title, self.text)
-        self.log.info("%s: Sent PM titled '%s' to %s.", classname(self),
+        self.log.info(u"%s: Sent PM titled '%s' to %s.", classname(self),
             self.title, self.user)
 
     def run(self):
         except AttributeError as e:
             raise CommandParameterError('Invalid parent message object')
 
-        self.log.info("%s: Sent Reddit reply to %s from %s.", classname(self),
+        self.log.info(u"%s: Sent Reddit reply to %s from %s.", classname(self),
             self.msg.author.name, self.res['reddit'].user.name)
 
     def run(self):
         query = self._run_query()
 
         self.msg.reply(self._build_prompt_list(query))
-        self.log.info("%s: Sent prompt listing by PM to %s.",
+        self.log.info(u"%s: Sent prompt listing by PM to %s.",
             classname(self), self.msg.author.name)
 
         self.msg.mark_as_read()
-        self.log.debug("%s: Marked message %s as read.",
+        self.log.debug(u"%s: Marked message %s as read.",
             classname(self), self.msg.name)
         self.res['dbsession'].close()
 
             prompt_ids.append(prompt.id)
 
         if has_prompt:
-            self.log.debug("%s: Found prompts: %s", classname(self),
+            self.log.debug(u"%s: Found prompts: %s", classname(self),
                 ', '.join(['{:d}'.format(i) for i in prompt_ids]))
         else:
-            self.log.debug("%s: No prompts found.", classname(self))
+            self.log.debug(u"%s: No prompts found.", classname(self))
             prompt_listing = ["No results found."]
 
         if self.short_entry: # no newlines between entries
             self.log = self.res['logger']
             with open('minibot/commands.txt') as help_file:
                 self.msg.reply(help_file.read())
-            self.log.info("%s: Sent help message to %s",
+            self.log.info(u"%s: Sent help message to %s",
                 classname(self), self.msg.author.name)
         else:
             self.msg.reply("Can't open help file!")
-            self.log.info("%s: Can't open help file: %s: %s",
+            self.log.info(u"%s: Can't open help file: %s: %s",
                 classname(self), classname(e), e.args[0])
         self.msg.mark_as_read() # on error, reply() raises exc; won't reach this
 
 
         r_sub = reddit.submit(target, self._get_title(), self._get_text())
         prompt.set_posted(r_sub.id, r_sub.created_utc)
-        self.log.info("%s: Posted prompt %d to /r/%s", classname(self),
+        self.log.info(u"%s: Posted prompt %d to /r/%s", classname(self),
             prompt.id, target)
         db.commit()
 
         thread.set_posted(r_post.id, r_post.created_utc)
         self._archive_older_threads()
         self._add_link_to_last_thread()
-        self.log.info("%s: Posted suggestion thread %d to /r/%s",
+        self.log.info(u"%s: Posted suggestion thread %d to /r/%s",
             classname(self), thread.id, target)
         db.commit()
 
                                             SuggestionThread.STATUS_ACTIVE).\
                     order_by(desc(SuggestionThread.time)).limit(1).first()
         if thread:
-            self.log.info("%s: Found previous suggestion thread %d (%s) <%s>",
+            self.log.info(u"%s: Found previous suggestion thread %d (%s) <%s>",
                     classname(self), thread.id,
                     thread.time.strftime("%Y-%m-%d %H:%M:%S UTC"),
                     get_reddit_url(thread.r_post_id, self.res['reddit']))
             self.prev_thread = thread
             return thread
         else:
-            self.log.warn("%s: No previous suggestion thread found on %s. "
+            self.log.warn(u"%s: No previous suggestion thread found on %s. "
                           "Falling back to full week search.",
                           classname(self), prev_date_str)
 
                                             SuggestionThread.STATUS_ACTIVE).\
                       order_by(desc(SuggestionThread.time)).limit(1).first()
         if thread:
-            self.log.info("%s: Found previous suggestion thread %d (%s) <%s>",
+            self.log.info(u"%s: Found previous suggestion thread %d (%s) <%s>",
                     classname(self), thread.id,
                     thread.time.strftime("%Y-%m-%d %H:%M:%S UTC"),
                     get_reddit_url(thread.r_post_id, self.res['reddit']))
             self.prev_thread = thread
             return thread
         else:
-            self.log.warn("%s: No previous suggestion thread found in the "
+            self.log.warn(u"%s: No previous suggestion thread found in the "
                           "seven days following %s.",
                           classname(self), prev_date_str)
             self.prev_thread = None
                 filter(SuggestionThread.status == self.thread.STATUS_ACTIVE):
             other_thread.set_archived()
             thread_ids.append(other_thread.r_post_id)
-        self.log.info("%s: Archived %d other threads: id %s",
+        self.log.info(u"%s: Archived %d other threads: id %s",
             classname(self), len(thread_ids),
             ', '.join(['{}'.format(tid) for tid in thread_ids]))
 
             new_text = oldlink_re.sub(newlink, r_thread.selftext)
             r_thread.edit(new_text)
 
-            self.log.info("%s: Edited navigation link to thread %s in previous "
+            self.log.info(u"%s: Edited navigation link to thread %s in previous "
                 "thread %s", classname(self), self.thread.r_post_id,
                 self.prev_thread.r_post_id)