Commits

Anonymous committed fd3c6b8

akhet fixes
- added colored formatter
- cleaned up inis
- refactored commands because it's restricted command in python and it messes up

  • Participants
  • Parent commits c20f721

Comments (0)

Files changed (9)

File akhet/paster_templates/akhet/+package+/__init__.py_tmpl

 import sqlalchemy
 {{endif}}
 
+VERSION = (0,0,1)
+__version__ = '.'.join((str(each) for each in VERSION[:4]))
+
 def main(global_config, **settings):
     """ This function returns a Pyramid WSGI application.
     """
     # Configure renderers and event subscribers
     config.add_renderer(".html", "pyramid.mako_templating.renderer_factory")
     config.add_subscriber("{{package}}.subscribers.create_url_generator",
-        "pyramid.events.ContextFound")
+                          "pyramid.events.ContextFound")
     config.add_subscriber("{{package}}.subscribers.add_renderer_globals",
                           "pyramid.events.BeforeRender")
 

File akhet/paster_templates/akhet/+package+/commands/__init__.py_tmpl

-import os
-
-def ask_ok(prompt, retries=4, complaint='Yes or no, please!'):
-    while True:
-        ok = raw_input(prompt)
-        if ok in ('y', 'ye', 'yes'):
-            return True
-        if ok in ('n', 'no', 'nop', 'nope'):
-            return False
-        retries = retries - 1
-        if retries < 0:
-            raise IOError
-        print complaint
-
-
-def _scan_commands(package):
-    """
-    Given a path to a package directory, returns a list of all the command
-    names that are available.
-    
-    Returns an empty list if no commands are defined.
-    
-    code borrowed from django...
-    
-    """
-    module_dir = os.path.dirname(os.path.abspath(__file__))
-    try:
-        return [f[:-3] for f in os.listdir(module_dir)
-                if not f.startswith('_') and f.endswith('.py')]
-    except OSError:
-        return []
-
-
-def extend_entry_points(package):
-    head = """
-    [paste.paster_command]    
-    """
-    CMD_TMPL = "%(cmd_name)s = %(module_path)s:%(callable_cls)s"
-
-    for cmd in _scan_commands(package):
-        module_path = '.'.join([package, 'commands', cmd])
-        head += CMD_TMPL % dict(cmd_name=cmd, 
-                                module_path=module_path, 
-                                callable_cls='Command')
-
-    return head 

File akhet/paster_templates/akhet/+package+/commands/create_db.py_tmpl

-import sys
-import logging.config
-
-import transaction
-import sqlalchemy
-import sqlahelper
-
-from paste.script.command import Command
-from pyramid.paster import PCommand
-
-import {{package}}.models as models
-from {{package}}.commands import ask_ok
-
-
-class Command(PCommand):
-    """
-    Create's the application tables based on Models.
-    
-    It's safe to run this multiple time during development since it always
-    checks if table exists and creates only new ones.
-    
-    To modify exists table use `*` to drop all  or list of tables you wish
-    to drop first and create from scratch 
-    
-    options
-        * - drops all tables before making new ones
-        table1 table2  - list of tables to drop before 
-    
-    Example::
-        paster create_db production.ini table1 table2
-    """
-    summary = "Create the application's database."
-    
-    min_args = 1 # defines mix arguments that function takes
-    stdout = sys.stdout
-    
-    usage = "CONFIG_FILE"
-    
-    group_name = "{{project}}"
-    takes_config_file = -1
-    parser = Command.standard_parser(verbose=True)
-
-    def command(self):
-        """
-        put you'r action here !
-        """
-        config_uri = self.args[0]
-        # setup logging if you want to
-        logging.config.fileConfig(config_uri)
-        # logger instance
-        log = logging.getLogger(__name__)
-        
-        #pyramid env
-        env = self.bootstrap[0](config_uri)
-        #registry
-        registry = env['registry']    
-        settings = registry.settings
-        
-        
-        # create all engines and connections, if you're 
-        # using more than one engine
-        # also define it here and add into sqlahelper
-        try:
-            engine = sqlalchemy.engine_from_config(settings,
-                                                   prefix="sqlalchemy.")
-            sqlahelper.add_engine(engine)
-            
-        except KeyError:
-            self.stdout.write('missing db uri in config\n')
-            sys.exit()
-        
-        all_tables = models.Base.metadata.sorted_tables
-        tables = list()
-        drop_all =drop_some= False
-        if len(self.args) > 1:
-            drop_all = self.args[1] == '*'
-            if not drop_all:
-                # just mark tables
-                all_tables = self.args[1:]
-                drop_some = True
-                        
-        if drop_all or drop_some:
-            upgrade = ask_ok('You are about to perform db creation, and '
-                             'have choosen to drop %s '
-                             'Continue ? [y/n]' % \
-                             ('all tables' if drop_all else 
-                              'some tables %s' % all_tables))
-            if not upgrade:
-                sys.exit('Nothing done')
-    
-            models.Base.metadata.drop_all(tables=all_tables)
-                
-        # Check for any existing tables, and add only tables that are not present
-        # in current database skipping those already created
-        for table in all_tables:
-            log.debug("checking if table '%s' exists", table.name)
-            if not table.exists():
-                tables.append(table)
-    
-        # Create the tables
-        models.Base.metadata.create_all(tables=tables)
-        sess = models.Session()
-    
-        # Record 1
-        #p = models.MyModel(id=1, name=u"Foo Bar")
-        #sess.add(p)
-    
-        transaction.commit()    

File akhet/paster_templates/akhet/+package+/lib/colored_formatter.py

+
+import logging
+
+BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE = xrange(30, 38)
+
+# Sequences
+RESET_SEQ = "\033[0m"
+COLOR_SEQ = "\033[0;%dm"
+BOLD_SEQ = "\033[1m"
+
+COLORS = {
+    'CRITICAL': MAGENTA,
+    'ERROR': RED,
+    'WARNING': CYAN,
+    'INFO': GREEN,
+    'DEBUG': BLUE,
+    'SQL': YELLOW
+}
+
+
+def one_space_trim(s):
+    if s.find("  ") == -1:
+        return s
+    else:
+        s = s.replace('  ', ' ')
+        return one_space_trim(s)
+
+
+def format_sql(sql):
+    sql = sql.replace('\n', '')
+    sql = one_space_trim(sql)
+    sql = sql\
+        .replace(',', ',\n\t')\
+        .replace('SELECT', '\n\tSELECT \n\t')\
+        .replace('UPDATE', '\n\tUPDATE \n\t')\
+        .replace('DELETE', '\n\tDELETE \n\t')\
+        .replace('FROM', '\n\tFROM')\
+        .replace('ORDER BY', '\n\tORDER BY')\
+        .replace('LIMIT', '\n\tLIMIT')\
+        .replace('WHERE', '\n\tWHERE')\
+        .replace('AND', '\n\tAND')\
+        .replace('LEFT', '\n\tLEFT')\
+        .replace('INNER', '\n\tINNER')\
+        .replace('INSERT', '\n\tINSERT')\
+        .replace('DELETE', '\n\tDELETE')
+    return sql
+
+
+class ColorFormatter(logging.Formatter):
+
+    def __init__(self, *args, **kwargs):
+        # can't do super(...) here because Formatter is an old school class
+        logging.Formatter.__init__(self, *args, **kwargs)
+
+    def format(self, record):
+        """
+        Changes record's levelname to use with COLORS enum
+        """
+
+        levelname = record.levelname
+        start = COLOR_SEQ % (COLORS[levelname])
+        def_record = logging.Formatter.format(self, record)
+        end = RESET_SEQ
+
+        colored_record = ''.join([start, def_record, end])
+        return colored_record
+
+
+class ColorFormatterSql(logging.Formatter):
+
+    def __init__(self, *args, **kwargs):
+        # can't do super(...) here because Formatter is an old school class
+        logging.Formatter.__init__(self, *args, **kwargs)
+
+    def format(self, record):
+        """
+        Changes record's levelname to use with COLORS enum
+        """
+
+        start = COLOR_SEQ % (COLORS['SQL'])
+        def_record = format_sql(logging.Formatter.format(self, record))
+        end = RESET_SEQ
+
+        colored_record = ''.join([start, def_record, end])
+        return colored_record

File akhet/paster_templates/akhet/+package+/pcommands/__init__.py_tmpl

+import os
+
+def ask_ok(prompt, retries=4, complaint='Yes or no, please!'):
+    while True:
+        ok = raw_input(prompt)
+        if ok in ('y', 'ye', 'yes'):
+            return True
+        if ok in ('n', 'no', 'nop', 'nope'):
+            return False
+        retries = retries - 1
+        if retries < 0:
+            raise IOError
+        print complaint
+
+
+def _scan_commands(package):
+    """
+    Given a path to a package directory, returns a list of all the command
+    names that are available.
+    
+    Returns an empty list if no commands are defined.
+    
+    code borrowed from django...
+    
+    """
+    module_dir = os.path.dirname(os.path.abspath(__file__))
+    try:
+        return [f[:-3] for f in os.listdir(module_dir)
+                if not f.startswith('_') and f.endswith('.py')]
+    except OSError:
+        return []
+
+
+def extend_entry_points(package):
+    head = """
+    [paste.paster_command]    
+    """
+    CMD_TMPL = "%(cmd_name)s = %(module_path)s:%(callable_cls)s\n"
+
+    for cmd in _scan_commands(package):
+        module_path = '.'.join([package, 'pcommands', cmd])
+        head += CMD_TMPL % dict(cmd_name=cmd,
+                                module_path=module_path,
+                                callable_cls='Command')
+
+    return head
+
+
+from paste.script.command import Command
+from pyramid.paster import PCommand
+
+class BasePCommand(PCommand):
+    """
+    Base for Paster pluggable commands
+    """
+
+    @staticmethod
+    def standard_parser(*args, **kwargs):
+        return Command.standard_parser(*args, **kwargs)
+
+    def _get_env(config_uri):
+        # pyramid env
+        return self.bootstrap[0](config_uri)
+
+    def _get_settings(self, config_uri):
+        env = self._get_env(config_uri)
+        registry = env['registry']
+        return registry.settings

File akhet/paster_templates/akhet/+package+/pcommands/create_db.py_tmpl

+import sys
+import logging.config
+
+import transaction
+import sqlalchemy
+import sqlahelper
+
+import {{package}}.models as models
+from {{package}}.commands import ask_ok, BasePCommand
+
+
+class Command(BasePCommand):
+    """
+    Create's the application tables based on Models.
+    
+    It's safe to run this multiple time during development since it always
+    checks if table exists and creates only new ones.
+    
+    To modify exists table use `*` to drop all  or list of tables you wish
+    to drop first and create from scratch 
+    
+    options
+        * - drops all tables before making new ones
+        table1 table2  - list of tables to drop before 
+    
+    Example::
+        paster create_db production.ini table1 table2
+    """
+    summary = "Create the application's database."
+    
+    min_args = 1 # defines mix arguments that function takes
+    stdout = sys.stdout
+    
+    usage = "CONFIG_FILE"
+    
+    group_name = "{{project}}"
+    takes_config_file = -1
+    parser = BasePCommand.standard_parser(verbose=True)
+
+    def command(self):
+        """
+        put you'r action here !
+        """
+        config_uri = self.args[0]
+        
+        # setup logging if you want to
+        logging.config.fileConfig(config_uri)
+        log = logging.getLogger(__name__)
+        
+        # optional env 
+        # env = self._get_env(config_uri)
+        settings = self._get_settings(config_uri)
+        
+        
+        # create all engines and connections, if you're 
+        # using more than one engine
+        # also define it here and add into sqlahelper
+        try:
+            engine = sqlalchemy.engine_from_config(settings,
+                                                   prefix="sqlalchemy.")
+            sqlahelper.add_engine(engine)
+
+        except KeyError:
+            self.stdout.write('missing db uri in config\n')
+            sys.exit()
+
+        all_tables = models.Base.metadata.sorted_tables
+        tables = list()
+        drop_all = drop_some = False
+        if len(self.args) > 1:
+            drop_all = self.args[1] == '*'
+            if not drop_all:
+                # just mark tables
+                all_tables = self.args[1:]
+                drop_some = True
+
+        if drop_all or drop_some:
+            upgrade = ask_ok('You are about to perform db creation, and '
+                             'have chosen to drop %s '
+                             'Continue ? [y/n]' % \
+                             ('all tables' if drop_all else
+                              'some tables %s' % all_tables))
+            if not upgrade:
+                sys.exit('Nothing done')
+
+            models.Base.metadata.drop_all(tables=all_tables)
+
+        # Check for any existing tables, and add only tables that are not present
+        # in current database skipping those already created
+        for table in all_tables:
+            log.debug("checking if table '%s' exists", table.name)
+            if not table.exists():
+                tables.append(table)
+
+        # Create the tables
+        models.Base.metadata.create_all(tables=tables)
+        sess = models.Session()
+
+        # Record 1
+        #p = models.MyModel(id=1, name=u"Foo Bar")
+        #sess.add(p)
+
+        transaction.commit()

File akhet/paster_templates/akhet/development.ini_tmpl

 debug_notfound = false
 debug_routematch = false
 debug_templates = true
-debug_toolbar = true
+
+## debug toolbar
+debugtoolbar.enabled = true
 debugtoolbar.hosts = 127.0.0.1
+
 default_locale_name = en
+
 cache.regions = default_term, second, short_term, long_term
 cache.type = memory
 cache.second.expire = 1
 cache.short_term.expire = 60
 cache.default_term.expire = 300
 cache.long_term.expire = 3600
+
 mako.directories = {{package}}:templates
 mako.strict_undefined = true
 {{if crypto}}
 {{if sqlalchemy}}
 sqlalchemy.url = sqlite:///%(here)s/db.sqlite
 {{endif}}
+
 {{if mailer}}
 mail.host = localhost
 mail.port = 25
 formatter = generic
 
 [formatter_generic]
+# uncomment to enable colored log levels
+# class={{project}}.lib.colored_formatter.ColorFormatter
 format = %(asctime)s %(levelname)-5.5s [%(name)s][%(threadName)s] %(message)s
 
 # End logging configuration

File akhet/paster_templates/akhet/production.ini_tmpl

 debug_notfound = false
 debug_routematch = false
 debug_templates = false
-debug_toolbar = false
+
+## debug toolbar
+debugtoolbar.enabled = false
 debugtoolbar.hosts = 127.0.0.1
+
 default_locale_name = en
+
 cache.regions = default_term, second, short_term, long_term
 cache.type = memory
 cache.second.expire = 1
 cache.short_term.expire = 60
 cache.default_term.expire = 300
 cache.long_term.expire = 3600
+
 mako.directories = {{package}}:templates
 mako.strict_undefined = true
 {{if crypto}}
 {{endif}}
 session.key = {{project}}
 {{if crypto}}
-session.encrypt_key = {{random_string}}
-session.validate_key = {{random_string}}
+session.encrypt_key = {{random_1}}
+session.validate_key = {{random_2}}
 {{endif}}
 {{if sqlalchemy}}
 sqlalchemy.url = sqlite:///%(here)s/db.sqlite
 {{endif}}
 
+{{if mailer}}
+mail.host = localhost
+mail.port = 25
+# mail.username = None           # SMTP username
+# mail.password = None	         # SMTP password
+# mail.tls = False               # Use TLS
+# mail.ssl = False               # Use SSL
+# mail.keyfile = None            # SSL key file
+# mail.certfile = None           # SSL certificate file
+# mail.queue_path = None         # Location of maildir
+# mail.default_sender = None     # Default from address
+# mail.debug = False             # SMTP debug level
+
+testingemail = true
+{{endif}}
 
 [filter:weberror]
 use = egg:WebError#error_catcher

File akhet/paster_templates/akhet/setup.py_tmpl

 
 from setuptools import setup, find_packages
 
-from {{package}}.commands import extend_entry_points
+from {{package}}.pcommands import extend_entry_points
 
 here = os.path.abspath(os.path.dirname(__file__))
 README = open(os.path.join(here, "README.txt")).read()