From ac6de461bb7c06329f00be24fd2c36365a545417 Mon Sep 17 00:00:00 2001 From: Ben Kurtovic Date: Sun, 2 Sep 2012 14:37:04 -0400 Subject: [PATCH] Implement lazy-importing of oursql and pytz. --- earwigbot/commands/time_command.py | 11 ++++++----- earwigbot/wiki/site.py | 16 ++++++++-------- 2 files changed, 14 insertions(+), 13 deletions(-) diff --git a/earwigbot/commands/time_command.py b/earwigbot/commands/time_command.py index a172a43..f110d1a 100644 --- a/earwigbot/commands/time_command.py +++ b/earwigbot/commands/time_command.py @@ -24,10 +24,11 @@ from datetime import datetime from math import floor from time import time -import pytz - +from earwigbot import importer from earwigbot.commands import Command +pytz = importer.new("pytz") + class Time(Command): """Report the current time in any timezone (UTC default), or in beats.""" name = "time" @@ -52,12 +53,12 @@ class Time(Command): self.reply(data, "@{0:0>3}".format(beats)) def do_time(self, data, timezone): - if not pytz: + try: + tzinfo = pytz.timezone(timezone) + except ImportError: msg = "This command requires the 'pytz' module: http://pytz.sourceforge.net/" self.reply(data, msg) return - try: - tzinfo = pytz.timezone(timezone) except pytz.exceptions.UnknownTimeZoneError: self.reply(data, "Unknown timezone: {0}.".format(timezone)) return diff --git a/earwigbot/wiki/site.py b/earwigbot/wiki/site.py index 6043675..765ea81 100644 --- a/earwigbot/wiki/site.py +++ b/earwigbot/wiki/site.py @@ -32,14 +32,14 @@ from urllib import quote_plus, unquote_plus from urllib2 import build_opener, HTTPCookieProcessor, URLError from urlparse import urlparse -import oursql - -from earwigbot import exceptions +from earwigbot import exceptions, importer from earwigbot.wiki import constants from earwigbot.wiki.category import Category from earwigbot.wiki.page import Page from earwigbot.wiki.user import User +oursql = importer.new("oursql") + __all__ = ["Site"] class Site(object): @@ -514,10 +514,6 @@ class Site(object): may raise its own exceptions (e.g. oursql.InterfaceError) if it cannot establish a connection. """ - if not oursql: - e = "Module 'oursql' is required for SQL queries." - raise exceptions.SQLError(e) - args = self._sql_data for key, value in kwargs.iteritems(): args[key] = value @@ -531,7 +527,11 @@ class Site(object): if "autoreconnect" not in args: args["autoreconnect"] = True - self._sql_conn = oursql.connect(**args) + try: + self._sql_conn = oursql.connect(**args) + except ImportError: + e = "Module 'oursql' is required for SQL queries." + raise exceptions.SQLError(e) def _get_service_order(self): """Return a preferred order for using services (e.g. the API and SQL).