commit 76207b786acc1aa3a36bfb3274f4d033c6526227
Author: dsorber <david.sorber@gmail.com>
Date:   Sat Aug 15 10:40:53 2015 -0400

    A few mostly minor changes. I created a Delegator object in the wsgi script that, by storring the DB connection, should increase performance. I also updated the wsgi script regexes and removed some unnecessary calls from the contorllers.

diff --git a/software/bookmark_library/bmklib/web/base_controller.py b/software/bookmark_library/bmklib/web/base_controller.py
index ba0ad9e..b8bc0e6 100644
--- a/software/bookmark_library/bmklib/web/base_controller.py
+++ b/software/bookmark_library/bmklib/web/base_controller.py
@@ -2,7 +2,7 @@ import os
 
 from genshi.template import TemplateLoader
 
-BASE_PATH = '/home/dsorber/Documents/repo/software/bookmark_library/'
+BASE_PATH = '/home/dsorber/Documents/phalanx-repo/software/bookmark_library/'
 DB_PATH = os.path.join('/var/www', 'bookmarks.db')
 TEMPLATE_PATH = os.path.join(BASE_PATH, 'bmklib', 'web', 'templates')
 
@@ -11,10 +11,13 @@ MAX_PER_PAGE = 30
 
 class BaseHTMLController(object):
     
-    def __init__(self, environ, template_name=None):
+    def __init__(self, environ, db_conn, template_name=None):
         
         self.environ = environ
         
+        # Store the database connection
+        self.db_conn = db_conn
+        
         # Load and store the template
         loader = TemplateLoader(TEMPLATE_PATH, auto_reload=True)    
         self.template = loader.load(template_name, encoding='utf-8')
diff --git a/software/bookmark_library/bmklib/web/bmklib.wsgi b/software/bookmark_library/bmklib/web/bmklib.wsgi
index 265c6bc..f8c314e 100644
--- a/software/bookmark_library/bmklib/web/bmklib.wsgi
+++ b/software/bookmark_library/bmklib/web/bmklib.wsgi
@@ -1,5 +1,8 @@
 import re
 
+import sqlite3
+
+from bmklib.web.base_controller import DB_PATH
 from bmklib.web.controllers.all_bookmarks import AllBookmarksPageController
 from bmklib.web.controllers.all_tags import AllTagsPageController
 from bmklib.web.controllers.bookmark import BookmarkPageController
@@ -7,54 +10,58 @@ from bmklib.web.controllers.main import MainPageController
 from bmklib.web.controllers.tagged import TaggedPageController
 from bmklib.web.controllers.update_bookmark import UpdateBookmarkController
 
-# It accepts two arguments:
-# environ points to a dictionary containing CGI like environment variables
-# which is filled by the server for each received request from the client
-# start_response is a callback function supplied by the server
-# which will be used to send the HTTP status and headers to the server
-def application(environ, start_response):
-    
-    path = environ['PATH_INFO']
-
-    if not path or path == '/':
-        # Main page
-        controller = MainPageController(environ)
-        response_headers, response_body = controller.generate_response()
-
-    elif re.search('^/bookmarks$', path) or re.search('^/bookmarks/', path):
-        # All bookmarks page
-        controller = AllBookmarksPageController(environ)
-        response_headers, response_body = controller.generate_response()
-    
-    elif re.search('^/bookmark$', path) or re.search('^/bookmark/', path):
-        # Specific bookmark page
-        controller = BookmarkPageController(environ)
-        response_headers, response_body = controller.generate_response()
+class Delegator(object):
+
+    def __init__(self, db_path=DB_PATH):
+        self.db_path = db_path
+        self.conn = sqlite3.connect(DB_PATH, check_same_thread=False)
+
+    def __call__(self, environ, start_response):
+        path = environ['PATH_INFO']
+
+        if not path or path == '/':
+            # Main page
+            controller = MainPageController(environ, self.conn)
+            response_headers, response_body = controller.generate_response()
+
+        elif re.match('^/bookmark(s|(s/\d*))$', path):
+            # All bookmarks page
+            controller = AllBookmarksPageController(environ, self.conn)
+            response_headers, response_body = controller.generate_response()
+        
+        elif re.match('^/bookmar(k|(k/\d*))$', path):
+            # Specific bookmark page
+            controller = BookmarkPageController(environ, self.conn)
+            response_headers, response_body = controller.generate_response()
         
-    elif re.search('^/update_bookmark$', path) or re.search('^/update_bookmark/$', path):
-        # Update bookmark
-        controller = UpdateBookmarkController(environ)
-        response_headers, response_body = controller.generate_response()
+        elif re.match('^/update_bookmar(k|(k/))$', path):
+            # Update bookmark
+            controller = UpdateBookmarkController(environ, self.conn)
+            response_headers, response_body = controller.generate_response()
         
-    elif re.search('^/tags$', path) or re.search('^/tags/', path):
-        # All tags page
-        controller = AllTagsPageController(environ)
-        response_headers, response_body = controller.generate_response()
-   
-    elif re.search('^/tagged/', path):
-        # All bookmarks tagged with tag page
-        controller = TaggedPageController(environ)
-        response_headers, response_body = controller.generate_response()
+        elif re.match('^/tag(s|(s/))$', path):
+            # All tags page
+            controller = AllTagsPageController(environ, self.conn)
+            response_headers, response_body = controller.generate_response()
+       
+        elif re.match('^/tagge(d|(d/\d*))$', path):
+            # All bookmarks tagged with tag page
+            controller = TaggedPageController(environ, self.conn)
+            response_headers, response_body = controller.generate_response()
+            
+        else:
+            # User supplied an invalid URL
+            response_body = 'Invalid URL "%s"' % environ['PATH_INFO']
+            response_headers = [('Content-Type', 'text/plain'),
+                                ('Content-Length', str(len(response_body)))]
+        # HTTP response code and message
+        status = '200 OK'
+        # Send the status and response headers to the server
+        start_response(status, response_headers)
+        # Return the response body. (Notice it is wrapped in a list although it
+        # could be any iterable.)
+        return [response_body]
         
-    else:
-        # User supplied an invalid URL
-        response_body = 'Invalid URL "%s"' % environ['PATH_INFO']
-        response_headers = [('Content-Type', 'text/plain'),
-                            ('Content-Length', str(len(response_body)))]
-    # HTTP response code and message
-    status = '200 OK'
-    # Send the status and response headers to the server
-    start_response(status, response_headers)
-    # Return the response body. (Notice it is wrapped in a list although it
-    # could be any iterable.)
-    return [response_body]
+
+# Set the callable object
+application = Delegator()
diff --git a/software/bookmark_library/bmklib/web/controllers/all_bookmarks.py b/software/bookmark_library/bmklib/web/controllers/all_bookmarks.py
index b251f6c..15551fd 100644
--- a/software/bookmark_library/bmklib/web/controllers/all_bookmarks.py
+++ b/software/bookmark_library/bmklib/web/controllers/all_bookmarks.py
@@ -4,12 +4,12 @@ import os.path
 import sqlite3
 
 from bmklib.lib.bookmark import Bookmark
-from bmklib.web.base_controller import BaseHTMLController, DB_PATH, MAX_PER_PAGE
+from bmklib.web.base_controller import BaseHTMLController, MAX_PER_PAGE
 
 class AllBookmarksPageController(BaseHTMLController):
     
-    def __init__(self, environ, template_name='bookmark_list.html'):
-        super(AllBookmarksPageController, self).__init__(environ, template_name)
+    def __init__(self, environ, db_conn, template_name='bookmark_list.html'):
+        super(AllBookmarksPageController, self).__init__(environ, db_conn, template_name)
     
     def build_content(self):
         
@@ -19,11 +19,8 @@ class AllBookmarksPageController(BaseHTMLController):
         path = self.environ['PATH_INFO'][1:]
         path_parts = path.split('/')
         
-        conn = sqlite3.connect(DB_PATH)        
-        db = conn.cursor()
-        
         # Grab the total number of bookmarks
-        db = conn.cursor()
+        db = self.db_conn.cursor()
         db.execute("SELECT COUNT(*) FROM bookmarks")
         total_bmks = int(db.fetchone()[0])
         self.content['total_num_bmks'] = total_bmks
@@ -55,7 +52,7 @@ class AllBookmarksPageController(BaseHTMLController):
         self.content['page_idx'] = page_idx
         
         # Build Bookmark objects for all of the returned results
-        bookmarks = [Bookmark(conn, id=row[0]) for row in db.fetchall()]
+        bookmarks = [Bookmark(self.db_conn, id=row[0]) for row in db.fetchall()]
         
         self.content['bookmarks'] = bookmarks
         self.content['path_parts'] = len(path_parts)
diff --git a/software/bookmark_library/bmklib/web/controllers/all_tags.py b/software/bookmark_library/bmklib/web/controllers/all_tags.py
index 2398bed..5414f13 100644
--- a/software/bookmark_library/bmklib/web/controllers/all_tags.py
+++ b/software/bookmark_library/bmklib/web/controllers/all_tags.py
@@ -4,12 +4,13 @@ import os.path
 import sqlite3
 
 from bmklib.lib.tag import Tag
-from bmklib.web.base_controller import BaseHTMLController, DB_PATH, MAX_PER_PAGE
+from bmklib.web.base_controller import BaseHTMLController, MAX_PER_PAGE
 
 class AllTagsPageController(BaseHTMLController):
     
-    def __init__(self, environ, template_name='tag_list.html'):
-        super(AllTagsPageController, self).__init__(environ, template_name)
+    def __init__(self, environ, db_conn, template_name='tag_list.html'):
+        super(AllTagsPageController, self).__init__(environ, db_conn, 
+                                                    template_name)
     
     def build_content(self):
         
@@ -19,11 +20,8 @@ class AllTagsPageController(BaseHTMLController):
         path = self.environ['PATH_INFO'][1:]
         path_parts = path.split('/')
         
-        conn = sqlite3.connect(DB_PATH)        
-        db = conn.cursor()
-        
         # Grab the total number of tags
-        db = conn.cursor()
+        db = self.db_conn.cursor()
         db.execute("SELECT COUNT(*) FROM tags")
         total_tags = int(db.fetchone()[0])
         self.content['total_num_tags'] = total_tags
@@ -55,7 +53,7 @@ class AllTagsPageController(BaseHTMLController):
         self.content['page_idx'] = page_idx
         
         # Build Tag objects for all of the returned results
-        tags = [Tag(conn, id=row[0]) for row in db.fetchall()]
+        tags = [Tag(self.db_conn, id=row[0]) for row in db.fetchall()]
         
         self.content['tags'] = tags
         self.content['path_parts'] = len(path_parts)
diff --git a/software/bookmark_library/bmklib/web/controllers/bookmark.py b/software/bookmark_library/bmklib/web/controllers/bookmark.py
index d31ad2e..edadbe6 100644
--- a/software/bookmark_library/bmklib/web/controllers/bookmark.py
+++ b/software/bookmark_library/bmklib/web/controllers/bookmark.py
@@ -4,12 +4,13 @@ import os.path
 import sqlite3
 
 from bmklib.lib.bookmark import Bookmark, BookmarkNotFoundError
-from bmklib.web.base_controller import BaseHTMLController, DB_PATH, MAX_PER_PAGE
+from bmklib.web.base_controller import BaseHTMLController, MAX_PER_PAGE
 
 class BookmarkPageController(BaseHTMLController):
     
-    def __init__(self, environ, template_name='bookmark.html'):
-        super(BookmarkPageController, self).__init__(environ, template_name)
+    def __init__(self, environ, db_conn, template_name='bookmark.html'):
+        super(BookmarkPageController, self).__init__(environ, db_conn, 
+                                                     template_name)
     
     def build_content(self):
         
@@ -17,9 +18,6 @@ class BookmarkPageController(BaseHTMLController):
         path = self.environ['PATH_INFO'][1:]
         path_parts = path.split('/')
         
-        conn = sqlite3.connect(DB_PATH)        
-        db = conn.cursor()
-        
         # Do some basic validation
         try:
             bmk_id = int(path_parts[1])
@@ -34,7 +32,7 @@ class BookmarkPageController(BaseHTMLController):
             
             # Build Bookmark object
             try:
-                bookmark = Bookmark(conn, id=bmk_id)
+                bookmark = Bookmark(self.db_conn, id=bmk_id)
                 self.content['bookmark'] = bookmark
             except BookmarkNotFoundError:
                 self.content['invalid'] = True
diff --git a/software/bookmark_library/bmklib/web/controllers/main.py b/software/bookmark_library/bmklib/web/controllers/main.py
index cf889b4..3355368 100644
--- a/software/bookmark_library/bmklib/web/controllers/main.py
+++ b/software/bookmark_library/bmklib/web/controllers/main.py
@@ -2,12 +2,12 @@ import os.path
 
 import sqlite3
 
-from bmklib.web.base_controller import BaseHTMLController, DB_PATH
+from bmklib.web.base_controller import BaseHTMLController
 
 class MainPageController(BaseHTMLController):
     
-    def __init__(self, environ, template_name='main.html'):
-        super(MainPageController, self).__init__(environ, template_name)
+    def __init__(self, environ, db_conn, template_name='main.html'):
+        super(MainPageController, self).__init__(environ, db_conn, template_name)
         
     def build_link(self, link):
         # Create links based on the PATH_INFO
@@ -19,10 +19,8 @@ class MainPageController(BaseHTMLController):
         return os.path.join(*prefix)
     
     def build_content(self):
-        conn = sqlite3.connect(DB_PATH)
-
         # Grab the total number of bookmarks
-        db = conn.cursor()
+        db = self.db_conn.cursor()
         db.execute("SELECT COUNT(*) FROM bookmarks")
         self.content['total_num_bmks'] = db.fetchone()[0]
         
diff --git a/software/bookmark_library/bmklib/web/controllers/tagged.py b/software/bookmark_library/bmklib/web/controllers/tagged.py
index 4b19158..1c7757d 100644
--- a/software/bookmark_library/bmklib/web/controllers/tagged.py
+++ b/software/bookmark_library/bmklib/web/controllers/tagged.py
@@ -5,12 +5,13 @@ import sqlite3
 
 from bmklib.lib.bookmark import Bookmark
 from bmklib.lib.tag import Tag
-from bmklib.web.base_controller import BaseHTMLController, DB_PATH, MAX_PER_PAGE
+from bmklib.web.base_controller import BaseHTMLController, MAX_PER_PAGE
 
 class TaggedPageController(BaseHTMLController):
     
-    def __init__(self, environ, template_name='bookmark_list.html'):
-        super(TaggedPageController, self).__init__(environ, template_name)
+    def __init__(self, environ, db_conn, template_name='bookmark_list.html'):
+        super(TaggedPageController, self).__init__(environ, db_conn, 
+                                                   template_name)
     
     def build_content(self):
         
@@ -21,12 +22,9 @@ class TaggedPageController(BaseHTMLController):
         if len(path_parts) != 2:
             # TODO: this is an errar
             pass
-
-        conn = sqlite3.connect(DB_PATH)
-        db = conn.cursor()
-                
+        
         tag_id = int(path_parts[1])
-        tag = Tag(conn, tag_id)
+        tag = Tag(self.db_conn, tag_id)
         
         self.content['page_title'] = 'Tagged: {:s}'.format(tag.value)
         
@@ -38,7 +36,7 @@ class TaggedPageController(BaseHTMLController):
         self.content['page_idx'] = page_idx
         
         # Build Bookmark objects for all of the returned results
-        bookmarks = [Bookmark(conn, id=bmk_id) for bmk_id in tag.category_bmks]
+        bookmarks = [Bookmark(self.db_conn, id=bmk_id) for bmk_id in tag.category_bmks]
         
         self.content['bookmarks'] = bookmarks
         self.content['path_parts'] = len(path_parts)
diff --git a/software/bookmark_library/bmklib/web/controllers/update_bookmark.py b/software/bookmark_library/bmklib/web/controllers/update_bookmark.py
index 382c492..0f1727c 100644
--- a/software/bookmark_library/bmklib/web/controllers/update_bookmark.py
+++ b/software/bookmark_library/bmklib/web/controllers/update_bookmark.py
@@ -5,12 +5,13 @@ import sqlite3
 
 from bmklib.lib.bookmark import Bookmark, BookmarkNotFoundError
 from bmklib.lib.tag import Tag
-from bmklib.web.base_controller import BaseHTMLController, DB_PATH
+from bmklib.web.base_controller import BaseHTMLController
 
 class UpdateBookmarkController(BaseHTMLController):
     
-    def __init__(self, environ, template_name='bookmark.html'):
-        super(UpdateBookmarkController, self).__init__(environ, template_name)
+    def __init__(self, environ, db_conn, template_name='bookmark.html'):
+        super(UpdateBookmarkController, self).__init__(environ, db_conn, 
+                                                       template_name)
     
     def build_content(self):
         
@@ -49,10 +50,7 @@ class UpdateBookmarkController(BaseHTMLController):
             
         # Retrieve the specified Bookmark object and update its values
         try:
-            conn = sqlite3.connect(DB_PATH)        
-            db = conn.cursor()
-            
-            bookmark = Bookmark(conn, id=bmk_id)
+            bookmark = Bookmark(self.db_conn, id=bmk_id)
             bookmark.url = escape(post_vars['url'][0])
             bookmark.title = escape(post_vars['title'][0])
             if 'description' in post_vars:
@@ -68,7 +66,7 @@ class UpdateBookmarkController(BaseHTMLController):
                 bookmark.category_tags.clear()
                 for tag in category_tags:
                     if tag:
-                        bookmark.category_tags.add(Tag(conn, value=tag))
+                        bookmark.category_tags.add(Tag(self.db_conn, value=tag))
             
             # Update description tags
             if 'description_tags' in post_vars:
@@ -77,7 +75,7 @@ class UpdateBookmarkController(BaseHTMLController):
                 bookmark.description_tags.clear()
                 for tag in description_tags:
                     if tag:
-                        bookmark.description_tags.add(Tag(conn, value=tag))
+                        bookmark.description_tags.add(Tag(self.db_conn, value=tag))
             
             self.content['invalid'] = False
             self.content['bookmark'] = bookmark
diff --git a/software/bookmark_library/bmklib/web/templates/tag_list.html b/software/bookmark_library/bmklib/web/templates/tag_list.html
index dd70ad0..e309431 100644
--- a/software/bookmark_library/bmklib/web/templates/tag_list.html
+++ b/software/bookmark_library/bmklib/web/templates/tag_list.html
@@ -19,7 +19,7 @@
 <div id="bmk_list">
     <div py:for="idx, tag in enumerate(tags)" id="${idx == 0 and 'first' or ''}" class="${idx % 2 == 1 and 'odd' or 'even'} row">
         <span class="bmk_index"><a href="${update_link}/${tag.id}">${idx + ((page_idx - 1) * len(tags)) + 1}</a></span>
-        <span><a href="tagged/${tag.id}">${tag.value}</a></span>
+        <span><a href="tagged/${tag.id}">${tag.value}</a>&nbsp;&nbsp;&nbsp;[category: ${len(tag.category_bmks)}&nbsp;&nbsp;&nbsp;description: ${len(tag.description_bmks)}]</span>
     </div>
 </div>
 
