changeset 7:57a45adf33d4

separate out request from self. ultimately a new object should be spawned per request
author k0s <k0scist@gmail.com>
date Tue, 06 Oct 2009 19:19:58 -0400
parents 3198742f7a86
children 67c2ccaef869
files bitsyblog/bitsyblog.py
diffstat 1 files changed, 70 insertions(+), 68 deletions(-) [+]
line wrap: on
line diff
--- a/bitsyblog/bitsyblog.py	Mon Oct 05 09:20:02 2009 -0400
+++ b/bitsyblog/bitsyblog.py	Tue Oct 06 19:19:58 2009 -0400
@@ -76,30 +76,26 @@
                                                      writer_name='html',
                                                      settings_overrides={'report_level': 5})
 
-
         # for BitsyAuth
         self.newuser = self.users.new
 
     ### methods dealing with HTTP
 
     def __call__(self, environ, start_response):
-        self.request = Request(environ)
-        res = self.make_response(self.request.method)
+        request = Request(environ)
+        res = self.response_functions.get(request.method, self.error())(request)
         return res(environ, start_response)
 
-    def make_response(self, method):
-        return self.response_functions.get(method, self.error)()
-
     def get_response(self, text, content_type='text/html'):
         res = Response(content_type=content_type, body=text)
         res.content_length = len(res.body)
         return res
 
-    def get_index(self):
+    def get_index(self, request):
         """returns material pertaining to the root of the site"""
-        path = self.request.path_info.strip('/')
 
-        n_links = self.number_of_links()
+        path = request.path_info.strip('/')
+        n_links = self.number_of_links(request)
 
         ### the front page
         if not path: 
@@ -107,7 +103,7 @@
 
         ### feeds
 
-        n_posts = self.number_of_posts()
+        n_posts = self.number_of_posts(request)
 
         # site rss
         if path == 'rss':
@@ -137,18 +133,20 @@
             logo = os.path.join(self.file_dir, 'bitsyblog.png')
             return self.get_response(file(logo, 'rb').read(), content_type='image/png')        
 
-    def get_user_space(self, user, path):
-        self.request.user = self.users[user] # user whose blog is viewed
-        check = self.check_user(user) # is this the authenticated user?
+    def get_user_space(self, user, path, request):
+        """returns a part of the user space"""
+
+        request.user = self.users[user] # user whose blog is viewed
+        check = self.check_user(user, request) # is this the authenticated user?
 
         feed = None # not an rss/atom feed by default (flag)
-        n_posts = self.number_of_posts(user)
+        n_posts = self.number_of_posts(request, user)
 
         # special paths
         if path == [ 'post' ]:
             if check is not None:
                 return check
-            return self.get_response(self.form_post(user))
+            return self.get_response(self.form_post(request, user))
 
         if path == [ 'preferences' ]:
             if check is not None:
@@ -169,14 +167,14 @@
 
         if len(path) == 2:
             if path[0] == 'css':
-                for i in self.request.user.settings['CSS']:
+                for i in request.user.settings['CSS']:
                     # find the right CSS file
                     if i['filename'] == path[1]:
                         return self.get_response(i['css'], content_type='text/css')
                 else:
                     return exc.HTTPNotFound('CSS "%s" not found' % path[1])
 
-        role = self.role(user)
+        role = self.role(user, request)
 
         # get the blog
         try:
@@ -195,43 +193,47 @@
             return self.get_response(content, content_type='text/xml')
         
         # reverse the blog if necessary
-        if self.request.GET.get('sort') == 'forward':
+        if request.GET.get('sort') == 'forward':
             blog = list(reversed(blog))
 
-        n_links = self.number_of_links(user)
+        n_links = self.number_of_links(request, user)
         # don't display navigation for short blogs
         if len(blog) < 2:
             n_links = 0
             
         # write the blog
-        content = self.write_blog(user, blog, self.request.path_info, n_links)
+        content = self.write_blog(user, blog, request.path_info, n_links, request)
 
         # return the content
         return self.get_response(content)        
 
-    def get(self):
+    def get(self, request):
         """
         display the blog or respond to a get request
         """
+
+        # GENSHI: global data dictionary
+        data = { 'site_name': self.site_name }
+
         # front matter of the site
         index = self.get_index()
         if index is not None:
             return index
 
         ### user space
-        user, path = self.userpath()
+        user, path = self.userpath(request)
         if user not in self.users:
             return exc.HTTPNotFound("No blog found for %s" % user)
-        return self.get_user_space(user, path)
+        return self.get_user_space(user, path, request)
 
-    def post(self):
+    def post(self, request):
         """
         write a blog entry and other POST requests
         """
         # TODO: posting to '/' ?
         
         # find user + path
-        user, path = self.userpath()
+        user, path = self.userpath(request)
 
         if user not in self.users:
             return exc.HTTPNotFound("No blog found for %s" % user)
@@ -330,42 +332,42 @@
     def passwords(self):
         return self.users.passwords()
 
-    def authenticated(self):
+    def authenticated(self, request):
         """return authenticated user"""
-        return self.request.environ.get('REMOTE_USER')
+        return request.environ.get('REMOTE_USER')
 
-    def check_user(self, user):
+    def check_user(self, user, request):
         """
         determine authenticated user
         returns None on success
         """
-        authenticated = self.authenticated()
+        authenticated = self.authenticated(request)
         if authenticated is None:
             return exc.HTTPUnauthorized('Unauthorized')
         elif user != authenticated:
             return exc.HTTPForbidden("Forbidden")        
 
-    def role(self, user):
+    def role(self, user, request):
         """
         determine what role the authenticated member has
         with respect to the user
         """
-        auth = self.authenticated()
+        auth = self.authenticated(request)
         if not auth:
             return 'public'
         if auth == user:
             return 'author'
         else:
-            if auth in self.request.user.settings['Friends']:
+            if auth in request.user.settings['Friends']:
                 return 'friend'
             else:
                 return 'public'
 
     ### user methods
 
-    def userpath(self):
+    def userpath(self, request):
         """user who's blog one is viewing"""        
-        path = self.request.path_info.strip('/').split('/')
+        path = request.path_info.strip('/').split('/')
         name = path[0]
         path = path[1:]
         if not name:
@@ -417,10 +419,10 @@
         
     ### blog retrival methods
 
-    def number_of_posts(self, user=None):
+    def number_of_posts(self, request, user=None):
         """return the number of blog posts to display"""
         # determine number of posts to display (None -> all)
-        n_posts = self.request.GET.get('posts', None)
+        n_posts = request.GET.get('posts', None)
         if n_posts is not None:
             try:
                 n_posts = int(n_posts)
@@ -430,10 +432,10 @@
                 n_posts = None
         return n_posts
 
-    def number_of_links(self, user=None):
+    def number_of_links(self, request, user=None):
         """return the number of links to display in the navigation"""
         # determine number of navigation links to display
-        n_links = self.request.GET.get('n')
+        n_links = request.GET.get('n')
         if n_links == 'all':
             return -1
         try:
@@ -485,16 +487,16 @@
 
     ### methods that write HTML
 
-    def render(self, body, title=None, feedtitle=None):
+    def render(self, request, body, title=None, feedtitle=None):
         """layout the page in a unified way"""
         stylesheets = ()
-        user = getattr(self.request, 'user', None)
+        user = getattr(request, 'user', None)
         _title = [ self.site_name ]
         if user:
-            stylesheets = self.request.user['CSS']
+            stylesheets = request.user['CSS']
             stylesheets = [ (("/%s" % self.user_url(user.name, 'css', css['filename'])),
                              css['name']) for css in stylesheets ]
-            _title.insert(0, self.request.user.name)
+            _title.insert(0, request.user.name)
         else:
             stylesheets = (("/css/site.css", "Default"),)
             
@@ -506,12 +508,12 @@
         if feedtitle:
             head_markup = ( '<link rel="alternate" type="application/atom+xml" title="%s" href="atom" />' % feedtitle, 
                             '<link rel="alternate" type="application/rss+xml" title="%s" href="rss" />' % feedtitle,)
-        return markup.wrap(self.site_nav()+body, title, stylesheets, head_markup=head_markup)
+        return markup.wrap(self.site_nav(request)+body, title, stylesheets, head_markup=head_markup)
 
-    def site_nav(self):
+    def site_nav(self, request):
         """returns HTML for site navigation"""
         links = [('/',), ]
-        user = self.authenticated()
+        user = self.authenticated(request)
         if user:
             links.extend([('/%s' % user, user),
                           ('/%s/post' % user, 'post'),
@@ -549,7 +551,7 @@
             print >> retval, self.navigation(user, blog, '/%s' % user, n_links)
             print >> retval, '</div>'
 
-        return self.render(retval.getvalue(), feedtitle=self.site_name)
+        return self.render(request, retval.getvalue(), feedtitle=self.site_name)
 
     def navigation(self, user, blog, path, n_links, n_char=80):
         prefs = self.users[user].settings
@@ -578,25 +580,25 @@
         print >> retval, '</div>'
         return retval.getvalue()
 
-    def blog_entry(self, user, entry):
+    def blog_entry(self, request, user, entry):
         """given the content string, return a marked-up blog entry"""
         # XXX no need to pass user
 
         # user preferences
-        prefs = self.request.user.settings
+        prefs = request.user.settings
         format = prefs.get('Date format', self.date_format)
         subject = prefs.get('Subject', self.subject)
 
-        role = self.role(user)
+        role = self.role(user, request)
         
         subject = subject % { 'date' : entry.date.strftime(format) }
         subject = cgi.escape(subject)
         html = StringIO()
-        id = entry.datestamp()
-        print >> html, '<div id="%s" class="blog-entry">' % id
-        print >> html, '<a name="%s" />' % id
+        blog_id = entry.datestamp()
+        print >> html, '<div id="%s" class="blog-entry">' % blog_id
+        print >> html, '<a name="%s" />' % blog_id
         print >> html, '<div class="subject">'
-        print >> html, '<a href="/%s">%s</a>' % (self.user_url(user, id), subject)
+        print >> html, '<a href="/%s">%s</a>' % (self.user_url(user, blog_id), subject)
         if (entry.privacy == 'secret') and (role == 'friend'):
             print >> html, '<em>secret</em>'
         print >> html, '</div>'
@@ -617,21 +619,21 @@
         print >> html, '</div>'
         return html.getvalue()
         
-    def write_blog(self, user, blog, path, n_links):
+    def write_blog(self, user, blog, path, n_links, request):
         """return the user's blog in HTML"""
         # XXX no need to pass path or user!
         retval = StringIO()
         print >> retval,  self.navigation(user, blog, path, n_links, 0)
         for entry in blog:
-            print >> retval, self.blog_entry(user, entry)
+            print >> retval, self.blog_entry(request, user, entry)
         feedtitle=None
-        if self.request.path_info.strip('/') == user:
+        if request.path_info.strip('/') == user:
             feedtitle = "%s's blog" % user
         title = None
         if len(blog) == 1:
-            format = self.request.user.settings.get('Date format', self.date_format)
+            format = request.user.settings.get('Date format', self.date_format)
             title = blog[0].date.strftime(format)
-        return self.render(retval.getvalue(), title=title, feedtitle=feedtitle)
+        return self.render(request, retval.getvalue(), title=title, feedtitle=feedtitle)
                            
     def restructuredText(self, string):
         origstring = string
@@ -751,14 +753,14 @@
 
     ### forms and accompanying display
 
-    def form_post(self, user):
+    def form_post(self, request, user):
         retval = StringIO()
         print >> retval, '<form action="/%s" method="post">' % self.user_url(user)
         print >> retval, '<textarea cols="80" rows="25" name="form-post"></textarea><br/>'
         print >> retval, self.privacy_settings()
         print >> retval, '<input type="submit" name="submit" value="Post" />'
         print >> retval, '</form>'
-        return self.render(retval.getvalue())
+        return self.render(request, retval.getvalue())
 
     def preferences_form(self, user):
         prefs = self.request.user.settings
@@ -808,7 +810,7 @@
         body = self.preferences_form(user)(errors)
         if message:
             body = '%s\n%s' % ( markup.p(markup.strong(message)), body )
-        return self.render(body, title='preferences')
+        return self.render(request, body, title='preferences')
 
     def privacy_settings(self, default='public'):
         """HTML snippet for privacy settings"""
@@ -821,16 +823,16 @@
 class BitsierBlog(BitsyBlog):
     """single user version of bitsyblog"""
 
-    def get(self):
+    def get(self, request):
         ### user space
-        user, path = self.userpath()
+        user, path = self.userpath(request)
         if user not in self.users:
             return exc.HTTPNotFound("No blog found for %s" % user)
 
-        return self.get_user_space(user, path)
+        return self.get_user_space(user, path, request)
 
-    def userpath(self):
-        path = self.request.path_info.strip('/').split('/')
+    def userpath(self, request):
+        path = request.path_info.strip('/').split('/')
         if path == ['']:
             path = []
         return self.user, path
@@ -847,10 +849,10 @@
     def passwords(self):
         return { self.user: self.users.password(self.user) }
 
-    def site_nav(self):
+    def site_nav(self, request):
         """returns HTML for site navigation"""
         links = [('/', self.user), ]
-        user = self.authenticated()
+        user = self.authenticated(request)
         if user:
             links.extend([
                           ('/post', 'post'),