changeset 9:e4f28fde518a

more self.request cleanup
author k0s <k0scist@gmail.com>
date Tue, 06 Oct 2009 21:37:28 -0400
parents 67c2ccaef869
children 93a4557e15c1
files bitsyblog/bitsyblog.py
diffstat 1 files changed, 49 insertions(+), 34 deletions(-) [+]
line wrap: on
line diff
--- a/bitsyblog/bitsyblog.py	Tue Oct 06 19:44:02 2009 -0400
+++ b/bitsyblog/bitsyblog.py	Tue Oct 06 21:37:28 2009 -0400
@@ -31,8 +31,10 @@
 from blog import FileBlog
 from cStringIO import StringIO
 from docutils.utils import SystemMessage
+from genshi.template import TemplateLoader
 from lxml import etree
 from markup.form import Form
+from paste.fileapp import FileApp
 from pkg_resources import resource_filename
 from user import FilespaceUsers
 from webob import Request, Response, exc
@@ -53,6 +55,7 @@
                  'subject': '[ %(date)s ]:',
                  'n_links': 5, # number of links for navigation
                  'site_name': 'bitsyblog',
+                 'auto_reload': 'False',
                  'help_file': None,
                  }
 
@@ -70,6 +73,13 @@
         self.blog = FileBlog(self.file_dir)
         self.cooker = self.restructuredText
 
+        # template renderer
+        self.loader = TemplateLoader(resource_filename(__name__, 'templates'),
+                                     auto_reload=self.auto_reload.lower()=='true')
+
+        # static file renderer
+
+        # helpfile
         if self.help_file and os.path.exists(self.help_file):
             help = file(self.help_file).read()
             self.help = docutils.core.publish_string(help,
@@ -126,12 +136,12 @@
         # site.css 
         if path == 'css/site.css':
             css_file = os.path.join(self.file_dir, 'site.css')
-            return self.get_response(file(css_file).read(), content_type='text/css')
+            return self.get_response(file(css_file).read(), content_type='text/css') # should use FileApp
 
         # logo
         if path == 'bitsyblog.png':
             logo = os.path.join(self.file_dir, 'bitsyblog.png')
-            return self.get_response(file(logo, 'rb').read(), content_type='image/png')        
+            return self.get_response(file(logo, 'rb').read(), content_type='image/png') # should use FileApp
 
     def get_user_space(self, user, path, request):
         """returns a part of the user space"""
@@ -213,7 +223,7 @@
         """
 
         # GENSHI: global data dictionary
-        data = { 'site_name': self.site_name }
+        request.environ['data'] = { 'site_name': self.site_name }
 
         # front matter of the site
         index = self.get_index()
@@ -224,6 +234,7 @@
         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, request)
 
     def post(self, request):
@@ -237,7 +248,7 @@
 
         if user not in self.users:
             return exc.HTTPNotFound("No blog found for %s" % user)
-        self.request.user = self.users[user]
+        request.user = self.users[user]
 
         check = self.check_user(user)
         if check is not None:
@@ -248,11 +259,11 @@
             
                 # make the data look like we want
                 settings = {}
-                settings['Date format'] = self.request.POST.get('Date format')
-                settings['Subject'] = '%(date)s'.join((self.request.POST['Subject-0'], self.request.POST['Subject-2']))
-                settings['Stylesheet'] = self.request.POST['Stylesheet']
-                settings['CSS file'] = self.request.POST.get('CSS file')
-                settings['Friends'] = ', '.join(self.request.POST.getall('Friends'))
+                settings['Date format'] = request.POST.get('Date format')
+                settings['Subject'] = '%(date)s'.join((request.POST['Subject-0'], request.POST['Subject-2']))
+                settings['Stylesheet'] = request.POST['Stylesheet']
+                settings['CSS file'] = request.POST.get('CSS file')
+                settings['Friends'] = ', '.join(request.POST.getall('Friends'))
                 
                 errors = self.users.write_settings(user, **settings)
                 if errors: # re-display form with errors                    
@@ -263,7 +274,7 @@
                 entry = self.blog.entry(user, path[0], roles['author'])
                 if entry is None:
                     return exc.HTTPNotFound("Blog entry %s not found %s" % path[0])
-                privacy = self.request.POST.get('privacy')
+                privacy = request.POST.get('privacy')
                 datestamp = entry.datestamp()
                 if privacy:
                     self.blog.delete(user, datestamp)
@@ -273,31 +284,31 @@
                 return exc.HTTPMethodNotAllowed("Not sure what you're trying to do")
         
         # get the body of the post
-        body = self.request.body
-        body = self.request.POST.get('form-post', body)
+        body = request.body
+        body = request.POST.get('form-post', body)
         body = body.strip()
         if not body:
             return exc.HTTPSeeOther("Your post has no content!  No blog for you", 
-                                    location='/%s' % self.user_url(user, 'post'))
+                                    location='/%s' % self.user_url(request, user, 'post'))
 
         # determine if the post is secret or private
-        privacy = self.request.GET.get('privacy') or self.request.POST.get('privacy') or 'public'
+        privacy = request.GET.get('privacy') or self.request.POST.get('privacy') or 'public'
 
         # write the file
         now = utils.datestamp(datetime.datetime.now())
-        location = "/%s" % self.user_url(user, now)
+        location = "/%s" % self.user_url(request, user, now)
         self.blog.post(user, now, body, privacy)
 
         # point the user at the post
         return exc.HTTPSeeOther("Post blogged by bitsy", location=location)
 
-    def put(self):
+    def put(self, request):
         """
         PUT several blog entries from a file
         """
 
         # find user + path
-        user, path = self.user()
+        user, path = self.userpath(request)
 
         if user not in self.users.users():
             return exc.HTTPNotFound("No blog found for %s" % user)
@@ -307,9 +318,9 @@
         
         # find the dates + entries in the file
         regex = '\[.*\]:'
-        entries = re.split(regex, self.request.body)[1:]
+        entries = re.split(regex, request.body)[1:]
         dates = [ date.strip().strip(':').strip('[]').strip()
-                  for date in re.findall(regex, self.request.body) ]
+                  for date in re.findall(regex, request.body) ]
         dates = [ dateutil.parser.parse(date) for date in dates ]
 
         # write to the blog
@@ -379,17 +390,17 @@
     def isentry(self, string): # TODO -> blog.py
         return (len(string) == len(''.join(utils.timeformat))) and string.isdigit()
 
-    def user_url(self, user, *args, **kw):
+    def user_url(self, request, user, *args, **kw):
         permalink = kw.get('permalink')
         if permalink:
-            _args = [ self.request.host_url, user ]
+            _args = [ request.host_url, user ]
         else:
             _args = [ user ]
         _args.extend(args)
         return '/'.join([str(arg) for arg in _args])
 
-    def permalink(self, blogentry):
-        return self.user_url(blogentry.user, blogentry.datestamp(), permalink=True)
+    def permalink(self, request, blogentry):
+        return self.user_url(request, blogentry.user, blogentry.datestamp(), permalink=True)
 
     def entry_subject(self, blogentry):
         if hasattr(self.request, 'user') and self.request.user.name == blogentry.user:
@@ -400,8 +411,8 @@
         date_format = prefs.get('Date format', self.date_format)
         return subject % { 'date': blogentry.date.strftime(date_format) }
 
-    def mangledurl(self, blogentry):
-        return self.user_url(blogentry.user, 'x%x' % (int(blogentry.datestamp()) * self.users.secret(blogentry.user)), permalink=True)
+    def mangledurl(self, request, blogentry):
+        return self.user_url(request, blogentry.user, 'x%x' % (int(blogentry.datestamp()) * self.users.secret(blogentry.user)), permalink=True)
 
     def unmangleurl(self, url, user):
         url = url.strip('x')
@@ -494,7 +505,7 @@
         _title = [ self.site_name ]
         if user:
             stylesheets = request.user['CSS']
-            stylesheets = [ (("/%s" % self.user_url(user.name, 'css', css['filename'])),
+            stylesheets = [ (("/%s" % self.user_url(request, user.name, 'css', css['filename'])),
                              css['name']) for css in stylesheets ]
             _title.insert(0, request.user.name)
         else:
@@ -598,14 +609,14 @@
         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, blog_id), subject)
+        print >> html, '<a href="/%s">%s</a>' % (self.user_url(request, user, blog_id), subject)
         if (entry.privacy == 'secret') and (role == 'friend'):
             print >> html, '<em>secret</em>'
         print >> html, '</div>'
         print >> html, self.cooker(entry.body)
 
         if role == 'author':
-            print >> html, '<div><form action="/%s" method="post">' % self.user_url(entry.user, id)
+            print >> html, '<div><form action="/%s" method="post">' % self.user_url(request, entry.user, blog_id)
             print >> html, self.privacy_settings(entry.privacy)
             print >> html, '<input type="submit" name="submit" value="Change Privacy" />'
             print >> html, '</form></div>'
@@ -613,7 +624,7 @@
                 title = "You can give this URL so people may see this %s post without logging in" % entry.privacy
                 print >> html, '<div>'
                 print >> html, '<span title="%s">Mangled URL:</span>' % title
-                print >> html, markup.link(self.mangledurl(entry))
+                print >> html, markup.link(self.mangledurl(request, entry))
                 print >> html, '</div>'
         
         print >> html, '</div>'
@@ -755,7 +766,7 @@
 
     def form_post(self, request, user):
         retval = StringIO()
-        print >> retval, '<form action="/%s" method="post">' % self.user_url(user)
+        print >> retval, '<form action="/%s" method="post">' % self.user_url(request, 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" />'
@@ -811,7 +822,7 @@
         if message:
             body = '%s\n%s' % ( markup.p(markup.strong(message)), body )
         return self.render(request, body, title='preferences')
-
+    
     def privacy_settings(self, default='public'):
         """HTML snippet for privacy settings"""
         settings = (('public', 'viewable to everyone'),
@@ -824,10 +835,14 @@
     """single user version of bitsyblog"""
 
     def get(self, request):
+
+        # GENSHI: global data dictionary
+        request.environ['data'] = { 'site_name': self.site_name }
+
         ### user space
         user, path = self.userpath(request)
         if user not in self.users:
-            return exc.HTTPNotFound("No blog found for %s" % user)
+            return exc.HTTPNotFound("Blog entry not found")
 
         return self.get_user_space(user, path, request)
 
@@ -837,10 +852,10 @@
             path = []
         return self.user, path
 
-    def user_url(self, user, *args, **kw):
+    def user_url(self, request, user, *args, **kw):
         permalink = kw.get('permalink')
         if permalink:
-            _args = [ self.request.host_url ]
+            _args = [ request.host_url ]
         else:
             _args = [ ]
         _args.extend(args)