Project

General

Profile

« Previous | Next » 

Revision 76207b78

Added by dsorber almost 11 years ago

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.

View differences:

software/bookmark_library/bmklib/web/base_controller.py
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')
......
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')
software/bookmark_library/bmklib/web/bmklib.wsgi
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
......
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()
software/bookmark_library/bmklib/web/controllers/all_bookmarks.py
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):
......
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
......
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)
software/bookmark_library/bmklib/web/controllers/all_tags.py
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):
......
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
......
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)
software/bookmark_library/bmklib/web/controllers/bookmark.py
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):
......
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])
......
# 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
software/bookmark_library/bmklib/web/controllers/main.py
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
......
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]
software/bookmark_library/bmklib/web/controllers/tagged.py
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):
......
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)
......
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)
software/bookmark_library/bmklib/web/controllers/update_bookmark.py
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):
......
# 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:
......
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:
......
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
software/bookmark_library/bmklib/web/templates/tag_list.html
<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>

Also available in: Unified diff