Skip to content
Browse files

Support PEP8 on all app.

  • Loading branch information...
1 parent 09854fd commit 76dbeae961ce8b03af64966067a9905eb3c5e3c4 @chronossc committed
Showing with 86 additions and 75 deletions.
  1. +41 −38 breadcrumbs/breadcrumbs.py
  2. +14 −10 breadcrumbs/middleware.py
  3. +9 −6 breadcrumbs/tests.py
  4. +16 −17 breadcrumbs/utils.py
  5. +6 −4 breadcrumbs_sample/webui/views.py
View
79 breadcrumbs/breadcrumbs.py
@@ -6,8 +6,7 @@
from django.conf import settings
from django.utils.translation import ugettext as _
from django.utils.safestring import mark_safe
-from django.utils.text import force_unicode
-import sys
+
class Singleton(object):
"""
@@ -25,12 +24,14 @@ def __new__(cls, *args, **kwds):
def _1st_init(self, *args, **kwds):
pass
+
class BreadcrumbsInvalidFormat(Exception):
"""
Simple exception that can be extended
"""
pass
+
class BreadcrumbsNotSet(Exception):
"""
Raised in utils.breadcrumbs_for_flatpages when we not have breadcrumbs in
@@ -38,12 +39,13 @@ class BreadcrumbsNotSet(Exception):
"""
pass
+
class Breadcrumb(object):
"""
Breadcrumb can have methods to customize breadcrumb object, Breadcrumbs
class send to us name and url.
"""
- def __init__(self,name,url):
+ def __init__(self, name, url):
# HERE
#
# If I don't use force_unicode, always runs ok, but have problems on
@@ -55,27 +57,28 @@ def __str__(self):
return self.__unicode__()
def __unicode__(self):
- return u"%s,%s" % (self.name,self.url)
+ return u"%s,%s" % (self.name, self.url)
def __repr__(self):
- return u"Breadcrumb <%s,%s>" % (self.name,self.url)
+ return u"Breadcrumb <%s,%s>" % (self.name, self.url)
+
class Breadcrumbs(Singleton):
"""
Breadcrumbs maintain a list of breadcrumbs that you can get interating with
class or with get_breadcrumbs().
"""
- def _1st_init(self,*args,**kwargs):
+ def _1st_init(self, *args, **kwargs):
"""
singleton function that start some variables
"""
self._clean()
- self.__init__(*args,**kwargs)
+ self.__init__(*args, **kwargs)
- def __call__(self,*args,**kwargs):
+ def __call__(self, *args, **kwargs):
if not len(args) and not len(kwargs):
return self
- return self.__init__(*args,**kwargs)
+ return self.__init__(*args, **kwargs)
def __fill_home(self):
# fill home if settings.BREADCRUMBS_AUTO_HOME is True
@@ -85,63 +88,63 @@ def __fill_home(self):
def _clean(self):
self.__bds = []
- self.__autohome=getattr(settings,'BREADCRUMBS_AUTO_HOME',False)
- self.__urls =[]
+ self.__autohome = getattr(settings, 'BREADCRUMBS_AUTO_HOME', False)
+ self.__urls = []
self.__fill_home()
- def __init__(self,*args,**kwargs):
+ def __init__(self, *args, **kwargs):
"""
Call validate and if ok, call fill bd
"""
# match Breadcrumbs( 'name', 'url' )
- if len(args) == 2 and type(args[0]) not in (list,tuple):
- if(self.__validate(args,0)):
- self.__fill_bds( args )
+ if len(args) == 2 and type(args[0]) not in (list, tuple):
+ if(self.__validate(args, 0)):
+ self.__fill_bds(args)
# match ( ( 'name', 'url'), ..) and samething with list
- elif len(args) == 1 and type(args[0]) in (list,tuple) \
+ elif len(args) == 1 and type(args[0]) in (list, tuple) \
and len(args[0]) > 0:
- for i,arg in enumerate(args[0]):
- if self.__validate(arg,i):
- self.__fill_bds( arg )
+ for i, arg in enumerate(args[0]):
+ if self.__validate(arg, i):
+ self.__fill_bds(arg)
# try to ( obj1, obj2, ... ) and samething with list
else:
- for i,arg in enumerate(args):
- if(self.__validate(arg,i)):
- self.__fill_bds( arg )
+ for i, arg in enumerate(args):
+ if(self.__validate(arg, i)):
+ self.__fill_bds(arg)
- def __validate(self,obj,index):
+ def __validate(self, obj, index):
"""
check for object type and return a string as name for each item of a
list or tuple with items, if error was found raise
BreadcrumbsInvalidFormat
"""
# for list or tuple
- if type(obj) in (list,tuple):
+ if type(obj) in (list, tuple):
if len(obj) == 2:
if (not obj[0] and not obj[1]) or \
- ( type(obj[0]) not in (str,unicode) and \
- type(obj[1]) not in (str,unicode)):
+ (type(obj[0]) not in (str, unicode) and \
+ type(obj[1]) not in (str, unicode)):
raise BreadcrumbsInvalidFormat(u"Invalid format for \
- breadcrumb %s in %s" % (index,type(obj).__name__))
+ breadcrumb %s in %s" % (index, type(obj).__name__))
if len(obj) != 2:
raise BreadcrumbsInvalidFormat(
u"Wrong itens number in breadcrumb %s in %s. \
You need to send as example (name,url)" % \
- (index,type(obj).__name__)
+ (index, type(obj).__name__)
)
# for objects
- elif not hasattr(obj,'name') and not hasattr(obj,'url'):
- raise BreadcrumbsInvalidFormat(u"You need to use a tuple like"+ \
- " (name,url) or object with name and url attributes for" + \
+ elif not hasattr(obj, 'name') and not hasattr(obj, 'url'):
+ raise BreadcrumbsInvalidFormat(u"You need to use a tuple like "
+ "(name,url) or object with name and url attributes for "
"breadcrumb.")
return True
- def __fill_bds(self,bd):
+ def __fill_bds(self, bd):
"""
simple interface to add Breadcrumb to bds
"""
- if hasattr(bd,'name') and hasattr(bd,'url'):
- bd = Breadcrumb(bd.name,bd.url)
+ if hasattr(bd, 'name') and hasattr(bd, 'url'):
+ bd = Breadcrumb(bd.name, bd.url)
else:
bd = Breadcrumb(*bd)
if bd.url not in self.__urls:
@@ -151,7 +154,7 @@ def __fill_bds(self,bd):
def __iter__(self):
return iter(self.__bds)
- def __getitem__(self,key):
+ def __getitem__(self, key):
return self.__bds[key]
def __repr__(self):
@@ -161,10 +164,10 @@ def __str__(self):
return self.__unicode__()
def __unicode__(self):
- return u"Breadcrumbs <%s>" % u", ".join([mark_safe(item.name) for item in \
- self[:10]] + [u' ...'])
+ return u"Breadcrumbs <%s>" % u", ".join([mark_safe(item.name) for item \
+ in self[:10]] + [u' ...'])
def all(self):
return self.__bds
-# vim: ts=4 sts=4 sw=4 et ai
+# vim: ts=4 sts=4 sw=4 et ai
View
24 breadcrumbs/middleware.py
@@ -7,25 +7,29 @@
from django.http import Http404
from django.shortcuts import get_object_or_404
+
class BreadcrumbsMiddleware(object):
- def process_request(self,request):
+ def process_request(self, request):
request.breadcrumbs = Breadcrumbs()
request.breadcrumbs._clean()
- return None
+
class FlatpageFallbackMiddleware(object):
def process_response(self, request, response):
+ # No need to check for a flatpage for non-404 responses.
if response.status_code != 404:
- return response # No need to check for a flatpage for non-404 responses.
+ return response
try:
- # In old 1.0 we have a patch for flat pages, but as live app, we can't
- # touch in django code, so we clone flat page middleware with some
- # modifications :)
- # We need to get flat page, aniway, but if fail, fail silently. Also we
- # check for permissions, parts of code are from flat page view
- f = get_object_or_404(FlatPage, url__exact=request.path_info, sites__id__exact=settings.SITE_ID)
- if f: breadcrumbs_for_flatpages(request,f)
+ # In old 1.0 we have a patch for flat pages, but as live app, we
+ # can't touch in django code, so we clone flat page middleware with
+ # some modifications :)
+ # We need to get flat page, aniway, but if fail, fail silently. Also
+ # we check for permissions, parts of code are from flat page view
+ f = get_object_or_404(FlatPage, url__exact=request.path_info,
+ sites__id__exact=settings.SITE_ID)
+ if f:
+ breadcrumbs_for_flatpages(request, f)
return flatpage(request, request.path_info)
# Return the original response if any errors happened. Because this
# is a middleware, we can't assume the errors will be caught elsewhere.
View
15 breadcrumbs/tests.py
@@ -1,4 +1,6 @@
-# -*-
+# -*- coding: utf-8 -*-
+
+# TODO: Write unit tests!!!
# run this script on your shell
from breadcrumbs import Breadcrumbs
@@ -7,17 +9,18 @@
# fill one per time
for i in range(5):
- bds( 'name%s' % i,'url%s' % i )
+ bds('name%s' % i, 'url%s' % i)
+
# create a simple class to emulate one object with name and url
-class emulatedobj(object):
- def __init__(self,*args):
+class EmulateObj(object):
+ def __init__(self, *args):
self.name = args[0]
self.url = args[1]
# add 10 objects
-bds( [ emulatedobj('name %s' % (i+10), 'url %s' % (i+10)) for i in range(10) ] )
+bds([EmulateObj('name %s' % (i + 10), 'url %s' % (i + 10)) for i in range(10)])
# print all
for bd in bds:
- print bd.name,bd.url
+ print bd.name, bd.url
View
33 breadcrumbs/utils.py
@@ -1,20 +1,20 @@
# -*- coding: utf-8 -*-
-from .breadcrumbs import Breadcrumbs,BreadcrumbsNotSet
+from .breadcrumbs import Breadcrumbs, BreadcrumbsNotSet
from django.contrib.flatpages.models import FlatPage
from django.http import Http404
-def breadcrumbs_for_flatpages(request,flatpage):
+
+def breadcrumbs_for_flatpages(request, flatpage):
""" given request and flatpage instance create breadcrumbs for all flat
pages """
- if not hasattr(request,'breadcrumbs') or \
- not isinstance(request.breadcrumbs,Breadcrumbs):
- raise BreadcrumbNotSet(u"You need to setup breadcrumbs to use this " + \
- "function.")
+ if not hasattr(request, 'breadcrumbs') or \
+ not isinstance(request.breadcrumbs, Breadcrumbs):
+ raise BreadcrumbsNotSet(u"You need to setup breadcrumbs to use this "
+ u"function.")
- if not isinstance(flatpage,FlatPage) or \
- not hasattr(flatpage,'id'):
- raise TypeError(u"flatpage argument isn't a FlatPage instance or " + \
- "not have id.")
+ if not isinstance(flatpage, FlatPage) or not hasattr(flatpage, 'id'):
+ raise TypeError(u"flatpage argument isn't a FlatPage instance or not "
+ u"have id.")
paths = []
for part in request.path_info.split(u"/"):
@@ -23,14 +23,14 @@ def breadcrumbs_for_flatpages(request,flatpage):
continue
# Add slash again
if not part.startswith(u"/"):
- part = u"/"+part
+ part = u"/" + part
if not part.endswith(u"/"):
- part = part+u"/"
+ part = part + u"/"
# If we have something on paths, url for flatpage is composed of what we
# have in path + part. Note that strins in path not have last slash, but
# part have.
if len(paths) > 0:
- url = u"".join(paths+[part])
+ url = u"".join(paths + [part])
else:
url = part
# if is same url we don't hit database again
@@ -38,14 +38,13 @@ def breadcrumbs_for_flatpages(request,flatpage):
# 404 because it is a url design problem, not flatpages or breadcrumbs
# problem.
if url == flatpage.url:
- request.breadcrumbs(flatpage.title,flatpage.url)
+ request.breadcrumbs(flatpage.title, flatpage.url)
else:
try:
f = FlatPage.objects.get(url=url)
except FlatPage.DoesNotExist:
raise Http404
else:
- request.breadcrumbs(f.title,f.url)
+ request.breadcrumbs(f.title, f.url)
# add last part of path in paths with one slash
- paths.append(u"/"+url[1:-1].rpartition(u"/")[-1])
-
+ paths.append(u"/" + url[1:-1].rpartition(u"/")[-1])
View
10 breadcrumbs_sample/webui/views.py
@@ -3,15 +3,17 @@
from django.shortcuts import render_to_response
from django.template.context import RequestContext
-def home(request):
+
+def home(request):
print request.breadcrumbs
return render_to_response('home.html',
- {'text':'Hello, this is home!'},
+ {'text': 'Hello, this is home!'},
context_instance=RequestContext(request))
+
def someview(request):
- request.breadcrumbs('just a view to show some url',request.path)
+ request.breadcrumbs('just a view to show some url', request.path)
return render_to_response('home.html',
- {'text':'Hello, this is some second view'},
+ {'text': 'Hello, this is some second view'},
context_instance=RequestContext(request))

0 comments on commit 76dbeae

Please sign in to comment.
Something went wrong with that request. Please try again.