Language: Python

Untitled Python (21-Aug @ 05:13)

Syntax Highlighted Code

  1. #!/home/yansky/mypython/bin/python
  2. import cgi, HTMLParser, urllib2, httplib, BeautifulSoup, MySQLdb, sys
  3. #import cgitb; cgitb.enable()
  4. print 'Content-Type: text/html\n\n'
  5. [196 more lines...]

Plain Code

#!/home/yansky/mypython/bin/python
import cgi, HTMLParser, urllib2, httplib, BeautifulSoup, MySQLdb, sys
#import cgitb; cgitb.enable()
print 'Content-Type: text/html\n\n'

# Get the cgi module and the values of all fields in the form

formStorage = cgi.FieldStorage()

# Get a parameter string from the form 
theValue =  formStorage['postLink'].value
getanimValue = formStorage.getvalue("animated")
animValue = 0
if getanimValue == 'animated':
  animValue = 1  

def putInDB(picLink, uid, nm, aV):
  
  # connect
  try:
  
    db = MySQLdb.connect(host="localhost", user="foo", passwd="bar", db="yansky_avatars")
    
  except MySQLdb.Error, e:
  
    print "Error %d: %s" % (e.args[0], e.args[1])
    
    sys.exit (1)  
  

  # create a cursor
  cursor = db.cursor()
  
  # execute SQL statement
  cursor.execute("SELECT userID FROM avStorage")
  # get the resultset as a tuple
  checkIfThere = cursor.fetchall()
  
  dbExec = "INSERT INTO avStorage (userName, userID, avatarLink, animated) VALUES (%s, %s, %s, %s)"
  
  tuP = (nm, uid, picLink, aV)
  
  whatDone = 'Saved.'
  
  for checks in checkIfThere:

    if checks[0] == uid:
      
      # execute SQL statement
      dbExec = "UPDATE avStorage SET userName=%s, userID=%s, avatarLink=%s, animated=%s WHERE userID=%s"
      
      tuP = (nm, uid, picLink, aV, uid)
      
      whatDone = 'Updated.'

  # execute SQL statement
  cursor.execute(
      dbExec,
      tuP
  )   
  
  
  # execute SQL statement
  cursor.execute("SELECT * FROM avStorage")
  # get the resultset as a tuple
  result = cursor.fetchall()
  
  new_text_file1 = open("../wpavatars/avatar.css", "w")
  new_text_file2 = open("../wpavatars/jbavatar.css", "w")
  new_text_file3 = open("../wpavatars/animatedavatar.css", "w")
  
  tex1 = ""
  tex2 = ""
  tex3 = ""
  # iterate through resultset
  for record in result:
  
    uName = record[0]
    uIDs = str(record[1])
    uAvLink = record[2]
  
    if record[3]:
    
      tex3 += "/* "+uName+" */ \n tr.wlr_"+uIDs+" td.bodyuser div:first-child >a:first-child {background:url("+uAvLink+"); display:block; height:80px; width:80px; background-repeat: no-repeat;  } \n \n "
    
    else:
    
      tex1 += "/* "+uName+" */ \n tr.wlr_"+uIDs+" td.bodyuser div:first-child >a:first-child {background:url("+uAvLink+"); display:block; height:80px; width:80px; background-repeat: no-repeat;  } \n \n "
      tex2 += "/* "+uName+" */ \n tr.wlr_"+uIDs+" a .bu_name:after {content: url("+uAvLink+") ; } \n \n "
      
  new_text_file1.write(tex1)
  new_text_file2.write(tex2)
  new_text_file3.write(tex3)
    
  new_text_file1.close()
  new_text_file2.close()
  new_text_file3.close()
  
  
  print """\
      <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
      <html>
      <head>
      <title>Whirlpool.Net.Au Avatar Thingo</title>
      <style type="text/css">
        body{
          
          background-color:#F0F0F8;
        
        }
      </style>
      </head>
      <body>
        <br />
        <p>Avatar Link """+whatDone+""" </p>
      </body>
      </html>
  """



def getAvLink(repFullNum, threadNum, pageNum, anchorNum):

    getURL = "http://forums.whirlpool.net.au/forum-replies.cfm?t="+threadNum+"&p="+pageNum+"#r"+anchorNum
    shortenLink = "/forum-replies.cfm?t="+threadNum+"&p="+pageNum+"#r"+anchorNum
    
    if (pageNum == '1'):
        shortenLink = "/forum-replies.cfm?t="+threadNum+"#r"+anchorNum

    request = urllib2.Request(getURL)
    request.add_header('User-Agent', 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.14) Gecko/20080404 Firefox/2.0.0.14')
    opener = urllib2.build_opener()
    feeddata = opener.open(request).read()
    b = BeautifulSoup.BeautifulSoup(feeddata)

    getPostAs = b.find("a", { "href" : shortenLink }).parent.parent.parent.findAll('a')

    for item in getPostAs:

        if item.has_key('href'):

            hr = item['href']

            if hr.startswith('/forum-user.cfm?id='):

            uid = int(hr.split('id=')[1])

            nm = ''.join(str(item.contents[1].contents[0]))

            elif hr.endswith('.jpg'):

            picLink = hr

            elif hr.endswith('.jpeg'):

            picLink = hr

            elif hr.endswith('.png'):

            picLink = hr

            elif hr.endswith('.gif'):

            picLink = hr             

    putInDB(picLink, uid ,nm, animValue)
                

if theValue.startswith("http://forums.whirlpool.net.au/forum-replies-herring") and theValue.find("r=") > -1:

    vS = theValue.split('&tpr=')

    repFullNum = vS[0].split('r=')[1].split('&tpr')[0]

    vS2 = vS[1].split(',')

    threadNum = vS2[0]

    pageNum = vS2[1]
    anchorNum = vS2[2]

    getAvLink(repFullNum, threadNum, pageNum, anchorNum)

else:
  print """\
      <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
      <html>
      <head>
      <title>Whirlpool.Net.Au Avatar Thingo</title>
      <style type="text/css">
        body{
          
          background-color:#F0F0F8;
        
        }
      </style>
      </head>
      <br />
      <p>Dude, that's not a proper URL!</p>
      </body></html>
      """ 

SQL (10-Aug @ 18:25)

thedevel

Syntax Highlighted Code

  1. #!/usr/bin/env python
  2.  
  3. f = file(raw_input("Enter the path for the txt file: "))
  4. w = file(raw_input("Enter the path for the out SQL file: "),'w')
  5. [24 more lines...]

Plain Code

#!/usr/bin/env python

f = file(raw_input("Enter the path for the txt file: "))
w = file(raw_input("Enter the path for the out SQL file: "),'w')
w.write("INSERT INTO drug_listing (fda_seq_no,drug_firm,firm_code,strength,unit,rx_otc,tradename) VALUES\n")

# Initiate variables
tlist = []
tstring = ''

while (True):
    l = f.readline() # Read line in
    if not l: # If line is empty
        f.close()
        break
    llist = l.split() # Convert string into list
    if len(llist) is 5: # If strength and unit are missing
        llist.insert(3,'') # Insert blank
        llist.insert(4,'') # Insert blank
    x = '' # Empty string x
    x = x.join([i + ' ' for i in llist[6:]]).strip() # Join each list element in positions > 6
    nlist = llist[:6] # Add first 6 listings
    nlist.append(x) # Add tradename
    vtuple = tuple(nlist) # Covert list to tuple
    tlist.append(vtuple) # Add listing tuple to list
tstring = tstring.join([str(i) + ",\n" for i in tlist]) # Join each listing with a comma
w.write(str(tstring[:-2]) + ";") # Remove last newline and comma, add semicolon, write to file
w.close()

Untitled Python (10-Aug @ 18:14)

Syntax Highlighted Code

  1. #!/usr/bin/env python
  2.  
  3. x = ['byron','lame','weather']
  4. for i in x:
  5. [2 more lines...]

Plain Code

#!/usr/bin/env python

x = ['byron','lame','weather']
for i in x:
    print i

Untitled Python (7-Aug @ 18:46)

Syntax Highlighted Code

  1. if self.extra_class:
  2.   templatevars["search"]["extra_class"] = "nodefaultsearch"
  3.  

Plain Code

if self.extra_class:
  templatevars["search"]["extra_class"] = "nodefaultsearch"

PIL resize image and maintain aspect ratio (25-Jul @ 09:24)

darthmahon

Syntax Highlighted Code

  1. import PIL
  2. from PIL import Image
  3.  
  4. img = Image.open('somepic.jpg')
  5. [3 more lines...]

Plain Code

import PIL
from PIL import Image

img = Image.open('somepic.jpg')
wpercent = (300/float(img.size[0]))
hsize = int((float(img.size[1])*float(wpercent)))
img = img.resize((300,hsize), PIL.Image.ANTIALIAS)
img.save('sompic.jpg') 

Resize image and maintain aspect ratio (25-Jul @ 09:23)

Syntax Highlighted Code

  1. import PIL
  2. from PIL import Image
  3.  
  4. img = Image.open('somepic.jpg')
  5. [3 more lines...]

Plain Code

import PIL
from PIL import Image

img = Image.open('somepic.jpg')
wpercent = (300/float(img.size[0]))
hsize = int((float(img.size[1])*float(wpercent)))
img = img.resize((300,hsize), PIL.Image.ANTIALIAS)
img.save('sompic.jpg') 

Untitled Python (24-Jul @ 18:11)

Syntax Highlighted Code

  1. print('vai apanhar....')

Plain Code

print('vai apanhar....')

Untitled Python (24-Jul @ 18:10)

Syntax Highlighted Code

  1. import sys

Plain Code

import sys

Untitled Python (3-Jul @ 17:30)

Syntax Highlighted Code

  1. class ClientsWorkspace(ExtJSONView):
  2.     context(my_application)
  3.     contains('clients') #the id of the container
  4.    
  5. [5 more lines...]

Plain Code

class ClientsWorkspace(ExtJSONView):
    context(my_application)
    contains('clients') #the id of the container
    
    listing_fields(['name','email',]) #columns for the ExtJSGrid
    default_view('addform') #a view that return a ExtForm in JSON format

    bind_url('editclient') #the view that will return the JSON to show on click event

Untitled Python (30-Jun @ 23:29)

Syntax Highlighted Code

  1. print 'lalala'

Plain Code

print 'lalala'

Untitled Python (30-Jun @ 14:43)

Syntax Highlighted Code

  1. import re
  2.  
  3. str = "* will * there."
  4. all = re.findall("\*", str)
  5.  

Plain Code

import re

str = "* will * there."
all = re.findall("\*", str)

Untitled Python (26-Jun @ 01:11)

Syntax Highlighted Code

  1. Do a simple doctest test on the app.
  2. ************************************
  3. :Test-Layer: functional
  4.  
  5. [28 more lines...]

Plain Code

Do a simple doctest test on the app.
************************************
:Test-Layer: functional

   >>> import grok
   >>> from zope.component import getMultiAdapter
   >>> from zope import schema
   >>> from pymenthon.forms.components import AddForm
   >>> from zope.interface import Interface
   >>> from zope.publisher.browser import TestRequest
   >>> class IPerson(Interface):
   ...    firstname = schema.TextLine(title=u'Firstname')
   ...    lastname = schema.TextLine(title=u'Lastname')
   ...
   >>> class People(grok.Application, grok.Container):
   ...    pass
   ...

Now we can create a JSON View

   >>> class PersonJSON(grok.JSON):
   ...    grok.context(People)
   ...
   ...    def hello(self):
   ...        return {'hi':'there'}
   ...

Finally, let's get the view

   >>> persons = People()
   >>> request = TestRequest()
   >>> form = getMultiAdapter((persons, request), name="hello")

Untitled Python (18-Jun @ 00:48)

Syntax Highlighted Code

  1. i = 0
  2. for i in range(0,i+1):
  3.  print "yo"
  4.  
  5.  

Plain Code

i = 0
for i in range(0,i+1):
 print "yo"

Untitled Python (30-May @ 17:50)

Syntax Highlighted Code

  1. class Register(Master):
  2.     """Register an InternalPrincipal add an IUser"""
  3.     def update(self, login=None, password=None, password_repeat=None, fname=None, lname=None, email=None):
  4.         if login is not None:
  5. [10 more lines...]

Plain Code

class Register(Master):
    """Register an InternalPrincipal add an IUser"""
    def update(self, login=None, password=None, password_repeat=None, fname=None, lname=None, email=None):
        if login is not None:
            pau = component.getUtility(IAuthentication)
            principals = pau['principals']
            if login not in principals:
                name = fname + ' ' + lname
                principals[login] = user = InternalPrincipal(login, password, name)
                role_manager = IPrincipalRoleManager(self.context)
                role_manager.assignRoleToPrincipal('Tpi.User', login)
                user = IUser(user) #pass it the InternalPrincipal object for adaption
                user.email = email 
                user.fname = fname
                user.lname = lname

Untitled Python (29-May @ 05:15)

Syntax Highlighted Code

  1. class Register(Master):
  2.     """Register an InternalPrincipal add an IUser"""
  3.     def update(self, login=None, password=None, password_repeat=None, fname=None, lname=None, email=None):
  4.         # TODO: validate password is equal to password_repeat    
  5. [14 more lines...]

Plain Code

class Register(Master):
    """Register an InternalPrincipal add an IUser"""
    def update(self, login=None, password=None, password_repeat=None, fname=None, lname=None, email=None):
        # TODO: validate password is equal to password_repeat    
        # add principal to principal folder
        if login is not None:
            pau = component.getUtility(IAuthentication)
            principals = pau['principals']
            if login not in principals:
                name = fname + ' ' + lname
                principals[login] = user = InternalPrincipal(login, password, name)
                # save the email to an IUser instance
                user = IUser(user) #pass it the InternalPrincipal object for adaption
                user.email = email 
                user.fname = fname
                user.lname = lname
                principalRoleManager.assignRoleToPrincipal('Tpi.Employee', login)
            else:pass
        else:pass

Untitled Python (27-May @ 03:38)

Syntax Highlighted Code

  1. #!/usr/bin/python
  2.  
  3. def amort(cost, interest, term, pmt):
  4.     mint = (1 + interest) ** (1.0/12)
  5. [28 more lines...]

Plain Code

#!/usr/bin/python

def amort(cost, interest, term, pmt):
    mint = (1 + interest) ** (1.0/12)
    for i in range(term):
        for j in range(12):
            cost *= mint
            cost -= pmt
    return cost

def findpmt(cost, interest, term):
    ub = cost
    lb = 0
    test = cost / 2
    bal = amort(cost, interest, term, test)
    while abs(bal) > 1000:
        if bal > 0:
            lb = test
        else:
            ub = test
        test = (lb + ub)/2
        bal = amort(cost, interest, term, test)
    return test

def ira(down, pmt, interest, term):
    mint = (1 + interest) ** (1.0/12)
    for i in range(term):
        for j in range(12):
            down += pmt
            down *= mint
    return down

Untitled Python (25-May @ 02:47)

Syntax Highlighted Code

  1.  File "/home/sancho/revoluciones/grok/rdbexample/eggs/tmpIHUqUX/zope.tales-3.4.0a1-py2.4.egg/zope/tales/tales.py", line 696, in evaluate
  2.    - /home/sancho/revoluciones/grok/Tpi/src/tpi/app_templates/master.pt
  3.    - Line 39, Column 5
  4.    - Expression: <PythonExpr (view.navLIST(context.__name__))>
  5. [16 more lines...]

Plain Code

  File "/home/sancho/revoluciones/grok/rdbexample/eggs/tmpIHUqUX/zope.tales-3.4.0a1-py2.4.egg/zope/tales/tales.py", line 696, in evaluate
   - /home/sancho/revoluciones/grok/Tpi/src/tpi/app_templates/master.pt
   - Line 39, Column 5
   - Expression: <PythonExpr (view.navLIST(context.__name__))>
   - Names:
      {'args': (),
       'context': <tpi.app.Tpi object at 0xb74e872c>,
       'default': <object object at 0xb7d98560>,
       'loop': {},
       'nothing': None,
       'options': {},
       'repeat': {},
       'request': <zc.resourcelibrary.publication.Request instance URL=http://192.168.1.103:8080/test/@@index>,
       'static': <grok.components.DirectoryResource object at 0x9c33b4c>,
       'template': <grok.components.TrustedFilePageTemplate object at 0x9708ccc>,
       'view': <tpi.app.Index object at 0x9c3384c>}
  File "/home/sancho/revoluciones/grok/rdbexample/eggs/tmpIHUqUX/zope.tales-3.4.0a1-py2.4.egg/zope/tales/pythonexpr.py", line 59, in __call__
   - __traceback_info__: (view.navLIST(context.__name__))
  File "<string>", line 0, in ?
AttributeError: 'Index' object has no attribute 'navLIST'

Untitled Python (25-May @ 02:43)

Syntax Highlighted Code

  1. class SimpleClientJSON(grok.JSON):
  2.     grok.context(SimpleClient)
  3.  
  4.     def firstname(self):
  5. [17 more lines...]

Plain Code

class SimpleClientJSON(grok.JSON):
    grok.context(SimpleClient)

    def firstname(self):
        return {'firstname': self.context.firstname}
        #return dict(client = self.context) TODO: make the object JSON serializable

    def lastname(self):
        return {'lastname': self.context.lastname}

class Index(grok.View):
    grok.context(rdbexample)

    def render(self):
        session = Session()
        client = session.query(SimpleClient).first()
        if client:
            view = getMultiAdapter((client, self.request), name='firstname')
            return view()
        else:
            self.redirect('addsimpleclient')

Untitled Python (25-May @ 00:05)

Syntax Highlighted Code

  1. def foo():
  2.   '''print hello'''
  3.   print 'hello'

Plain Code

def foo():
  '''print hello'''
  print 'hello'

Untitled Python (24-May @ 06:04)

Syntax Highlighted Code

  1. class Listing(Master):
  2.     '''
  3.    Member listing view. This demonstrates how to require a permission to view, and also how to
  4.    obtain a list of annotated principals.
  5. [18 more lines...]

Plain Code

class Listing(Master):
    '''
    Member listing view. This demonstrates how to require a permission to view, and also how to
    obtain a list of annotated principals.
    '''

    grok.require('logindemo.ViewMemberListing')

    def fieldNames(self):
        return (f for f in IUser)

    def members(self):
        pau = getUtility(IAuthentication)
        principals = pau['principals']
        roster = []
        for id in sorted(principals.keys()):
            # adapt the principals to IUser to get all fields
            user = IUser(principals[id])
            fields = {}
            for field in IUser:
                fields[field] = getattr(user, field)
            roster.append(fields)
        return roster

Untitled Python (24-May @ 05:50)

Syntax Highlighted Code

  1. class MemberListing(grok.View):
  2.  
  3.     def fieldNames(self):
  4.         return (f for f in IUser)
  5. [15 more lines...]

Plain Code

class MemberListing(grok.View):

    def fieldNames(self):
        return (f for f in IUser)

    def members(self):
        pau = component.getUtility(IAuthentication)
        principals = pau['principals']
        roster = [ ]
        for id in sorted(principals.keys()):
            print id
            print principals[id]
            user = IUser(principals[id])        # <----- this is where the code is breaking
            fields = {}
            for field in IUser:
                fields[field] = getattr(user, field)
            roster.append(fields)
        return roster

Untitled Python (24-May @ 05:39)

Syntax Highlighted Code

  1. import re
  2. import grok
  3. from grok import index
  4. from zope.interface import Interface
  5. [194 more lines...]

Plain Code

import re
import grok
from grok import index
from zope.interface import Interface
from zope import schema
from z3c.widget.tiny.widget import TinyWidget
from zope.app.authentication import PluggableAuthentication
from zope.app.authentication.principalfolder import PrincipalFolder
from zope.app.authentication.principalfolder import InternalPrincipal
from zope.app.authentication.principalfolder import IInternalPrincipal
from zope.app.authentication.interfaces import IPasswordManager
from zope.app.authentication.session import SessionCredentialsPlugin
from zope.app.security.interfaces import IAuthentication
from zope.app.security.interfaces import IUnauthenticatedPrincipal
from zope.securitypolicy.interfaces import IPrincipalRoleManager
from zope.securitypolicy.interfaces import IRole
from zope.securitypolicy.interfaces import IRolePermissionManager
from zope.securitypolicy.role import LocalRole
from zope.i18n import MessageFactory
from zope.component import provideAdapter
from zope.component import getUtility
from zope.interface import implements
from zope.component import adapts
from zope.component import getUtility
from zope.component import getUtilitiesFor
from zope.annotation.interfaces import IAnnotations
from persistent.dict import PersistentDict
from zope.i18n import MessageFactory
import appconfig
from zope import component

expr = re.compile(r"^(w&.%#$&'*+-/=?^_`{}|~]+!)*[w&.%#$&'*+-/=?^_`{}|~]+"
                  r"@(([0-9a-z]([0-9a-z-]*[0-9a-z])?.)+[a-z]{2,6}|([0-9]{1,3}"
                  r".){3}[0-9]{1,3})$", re.IGNORECASE)
check_email = expr.match


##############################################################################
### I N T E R F A C E S ######################################################
##############################################################################

_ = MessageFactory('tpi')


################################################## email validation

class NotAnEmailAddress(schema.ValidationError):
    __doc__ = _(u"Invalid email address")

check_email = re.compile(r"[a-zA-Z0-9._%-]+@([a-zA-Z0-9-]+.)*[a-zA-Z]{2,4}").match
def valid_email(value):
    if check_email(value):
        return True
    raise NotAnEmailAddress(value)

################################################## interfaces


class IUser(Interface):
    """Basic user data."""
    login = schema.TextLine(title=_(u"Login"),
                            required=True)
    password = schema.Password(title=_(u"Password"),
                            required=True)
    password_repeat = schema.Password(title=_(u"Password repeat"),
                            required=True)
    fname = schema.TextLine(title=_(u"First name"),
                            required=False)
    lname = schema.TextLine(title=_(u"Last name"),
                            required=False)
    email = schema.ASCIILine(title=_(u"E-mail"),
                            required=False,
                            constraint=valid_email)

### H E L P E R   S C R I P T S  #############################################

def setup_pau(pau):
    pau['principals'] = PrincipalFolder('tpi.principals.')
    pau.authenticatorPlugins = ('principals',)
    pau['session'] = session = SessionCredentialsPlugin()
    session.loginpagename = 'login'
    pau.credentialsPlugins = ('No Challenge if Authenticated', 'session',)

def role_factory(*args):
    def factory():
        return LocalRole(*args)
    return factory

##############################################################################
### A P P L I C A T I O N ####################################################
##############################################################################

class Tpi(grok.Application, grok.Container):
    def __init__(self):
        super(Tpi, self).__init__()

    ### U T I L I T I E S  ###################################################

    # register authentication utility
    grok.local_utility(PluggableAuthentication, IAuthentication, 
                       setup=setup_pau)

    # register Admin Role  
    grok.local_utility(role_factory(u'TPI Administrator'), IRole,
                       name='tpi.Admin',
                       name_in_container='tpi.Admin')

    # register Employee Role  
    grok.local_utility(role_factory(u'TPI Employees'), IRole,
                       name='tpi.Employee',
                       name_in_container='tpi.Employees')

    # register Employee Role  
    grok.local_utility(role_factory(u'TPI Member'), IRole,
                       name='tpi.Member',
                       name_in_container='tpi.Member')

### S U B S C R I B E R S ####################################################

@grok.subscribe(Tpi, grok.IObjectAddedEvent)
def grant_permissions(app, event):
    role_manager = IRolePermissionManager(app)
    # Admin Permissions
    role_manager.grantPermissionToRole('tpi.ViewClients', 'tpi.Employees')
    role_manager.grantPermissionToRole('tpi.AddClient', 'tpi.Employees')
    role_manager.grantPermissionToRole('tpi.DeleteClient', 'tpi.Admin')
    role_manager.grantPermissionToRole('tpi.ViewMemberListing', 'tpi.Admin')
    # Employee Permissions
    role_manager.grantPermissionToRole('tpi.ViewClients', 'tpi.Employees')
    role_manager.grantPermissionToRole('tpi.AddClient', 'tpi.Employees')


class GlobalMacros(grok.View):
    grok.context(Interface)
    grok.name('globalmacros')

class Index(grok.View):
    grok.context(Tpi)
    grok.name('index')
    def navLIST(self, name):
        if name not in appconfig.menuitems.keys():
            pass
        else:
            return appconfig.menuitems[name]



##############################################################################
### A U T H E N T I C A T I O N ##############################################
##############################################################################

class Register(grok.Form):
    
    form_fields = grok.AutoFields(IUser)
    label = u'User registration'
    template = grok.PageTemplateFile('form.pt')

    @grok.action('Sign up')
    def save(self, login, password, password_repeat, fname, lname, email):
        # TODO: validate password is equal to password_repeat
        
        # add principal to principal folder
        pau = component.getUtility(IAuthentication)
        principals = pau['principals']
        assert(login not in principals)
        name = fname + ' ' + lname      
        principals[login] = user = InternalPrincipal(login, password, name)

        # save the email to an IUser instance
        user.email = email
        
        # grant principal the role
        role_manager = IPrincipalRoleManager(self.context)
        role_manager.assignRoleToPrincipal('tpi.Employee',
                                           principals.prefix + login)
        self.redirect('index')

class MemberListing(grok.Adapter):
    grok.implements(IUser)
    grok.template('form.pt')

    def fieldNames(self):
        return (f for f in IUser)

    def members(self):
        pau = component.getUtility(IAuthentication)
        principals = pau['principals']
        roster = [ ]
        for id in sorted(principals.keys()):
            print id
            print principals[id]
            user = IUser(principals[id])        # <----- this is where the code is breaking
            fields = {}
            for field in IUser:
                fields[field] = getattr(user, field)
            roster.append(fields)
        return roster

Untitled Python (24-May @ 05:28)

Syntax Highlighted Code

  1. import grok
  2. from urllib import urlencode
  3. from zope.interface import Interface, implements, classImplements
  4. from zope.component import getUtility, provideAdapter
  5. [177 more lines...]

Plain Code

import grok
from urllib import urlencode
from zope.interface import Interface, implements, classImplements
from zope.component import getUtility, provideAdapter
from zope.app.authentication import PluggableAuthentication
from zope.app.authentication.principalfolder import PrincipalFolder
from zope.app.authentication.principalfolder import InternalPrincipal
from zope.app.authentication.session import SessionCredentialsPlugin
# XXX: Failed attempt to display the password_encoding field
# from zope.app.form.browser.source import SourceDropdownWidget
from zope.app.security.interfaces import IAuthentication
from zope.app.security.interfaces import IUnauthenticatedPrincipal
from zope.app.securitypolicy.interfaces import IPrincipalPermissionManager
from zope.annotation.interfaces import IAttributeAnnotatable
from zope.i18n import MessageFactory


from interfaces import IUser, UserDataAdapter  

_ = MessageFactory('logindemo')

def setup_pau(pau):
    '''
    Callback to setup the Pluggable Authentication Utility
       A reference to this function is passed as a parameter in the
    declaration of the PAU (see LoginDemo class)
    '''
    # the principal source is a PrincipalFolder, stored in ZODB
    pau['principals'] = PrincipalFolder() 
    pau.authenticatorPlugins = ('principals',)
    # the SessionCredentialsPlugin isused for cookie-based authentication
    pau['session'] = session = SessionCredentialsPlugin()
    session.loginpagename = 'login' # the page to redirect for login
    # configuration of the credentials plugin
    pau.credentialsPlugins = ('No Challenge if Authenticated', 'session',)
        
class LoginDemo(grok.Application, grok.Container):
    """
    An app that lets you create an account and change your password.
    """
    # register the authentication utility; see setup_pau for settings
    grok.local_utility(PluggableAuthentication, IAuthentication,
                       setup=setup_pau)
    # make InternalPrincipal instances annotatable
    classImplements(InternalPrincipal,IAttributeAnnotatable)
    # register the adapter for IInternalPrincipal which provides IUser
    provideAdapter(UserDataAdapter)
           
class ViewMemberListing(grok.Permission):
    ''' Permission to see the member listing '''
    grok.name('logindemo.ViewMemberListing')

class Master(grok.View):
    """
    The master page template macro.
    
    The template master.pt is used as page macro in most views. Since this
    template uses the logged_in method and message attributes below, it's best
    to make all other views in this app subclasses of Master.
    """
    grok.context(Interface)  # register this view for all objects

    message = '' # used to give feedback

    def logged_in(self):
        # this is the canonical way to tell whether the user is authenticated
        # in Zope 3: check if the principal provides IUnauthenticatedPrincipal
        return not IUnauthenticatedPrincipal.providedBy(self.request.principal)
    
class Index(Master):
    """
    The main page, showing user data and member count.
    """

    def members(self):
        # get the authentication utility
        pau = getUtility(IAuthentication)
        result = len(pau['principals'])
        if result == 0:
            return _(u'No one has')
        elif result == 1:
            return _(u'One member has')
        else:
            return unicode(result) + _(u' members have')

    
class Login(Master):
    """
    Login form and handler.
    """
    def update(self, login_submit=None):
        if login_submit is not None: # we are handling the login submission
            if self.logged_in(): # if the login was accepted then...
                # redirect to where the user came from, or to the main page
                dest = self.request.get('camefrom', self.application_url())
                self.redirect(dest)
            else: # if the user is still not logged in...
                # then an incorrect login or password was provided
                self.message = _(u'Invalid login name and/or password')

class Logout(grok.View):
    """
    Logout handler.
    """
    grok.context(Interface)
    def render(self):
        # get the session plugin and tell it to logout
        session = getUtility(IAuthentication)['session']
        session.logout(self.request)
        # redirect to the main page
        self.redirect(self.application_url())
        
class Join(grok.AddForm, Master):
    """
    User registration form.
    """
    form_fields = grok.AutoFields(IUser)
    # XXX: Failed attempt to display the password_encoding field
    #form_fields[u'password_encoding'].custom_widget = SourceDropdownWidget
    label = u'User registration'
    template = grok.PageTemplateFile('form.pt')
    
    @grok.action('Save')
    def save(self, **data):
        '''
        Create an InternalPrincipal with the user data.
        
        This method also sets extra fields using an annotations through
        the IUser adapter, and grants the ViewMemberListing permission to
        the principal just created.
        '''
        login = data['login']
        pau = getUtility(IAuthentication)
        principals = pau['principals']
        # create an instance of InternalPrincipal
        principal = InternalPrincipal(login, data['password'], data['name'],
                                      passwordManagerName='SHA1')
        # add principal to principal folder; we may assume that the login
        # name is unique because of validation on the IUser interface
        # but to be doubly sure, we assert this
        assert(login not in principals)
        principals[login] = principal
        # save the e-mail
        user = IUser(principal)
        user.email = data['email']
        # grant the user permission to view the member listing
        permission_mngr = IPrincipalPermissionManager(grok.getSite())
        permission_mngr.grantPermissionToPrincipal(
           'logindemo.ViewMemberListing', principals.prefix + login)

        self.redirect(self.url('login')+'?'+urlencode({'login':login}))
                    
class Account(grok.View):
    
    def render(self):
        return 'Not implemented'
    
class Listing(Master):
    '''
    Member listing view. This demonstrates how to require a permission to view, and also how to
    obtain a list of annotated principals.
    '''

    grok.require('logindemo.ViewMemberListing')

    def fieldNames(self):
        return (f for f in IUser)

    def members(self):
        pau = getUtility(IAuthentication)
        principals = pau['principals']
        roster = []
        for id in sorted(principals.keys()):
            # adapt the principals to IUser to get all fields
            user = IUser(principals[id])
            fields = {}
            for field in IUser:
                fields[field] = getattr(user, field)
            roster.append(fields)
        return roster

Untitled Python (24-May @ 04:09)

Syntax Highlighted Code

  1. import re
  2. import grok
  3. from grok import index
  4. from zope.interface import Interface
  5. [249 more lines...]

Plain Code

import re
import grok
from grok import index
from zope.interface import Interface
from zope import schema
from z3c.widget.tiny.widget import TinyWidget
from zope.app.authentication import PluggableAuthentication
from zope.app.authentication.principalfolder import PrincipalFolder
from zope.app.authentication.principalfolder import InternalPrincipal
from zope.app.authentication.principalfolder import IInternalPrincipal
from zope.app.authentication.interfaces import IPasswordManager
from zope.app.authentication.session import SessionCredentialsPlugin
from zope.app.security.interfaces import IAuthentication
from zope.app.security.interfaces import IUnauthenticatedPrincipal
from zope.securitypolicy.interfaces import IPrincipalRoleManager
from zope.securitypolicy.interfaces import IRole
from zope.securitypolicy.interfaces import IRolePermissionManager
from zope.securitypolicy.role import LocalRole
from zope.i18n import MessageFactory
from zope.component import provideAdapter
from zope.component import getUtility
from zope.interface import implements
from zope.component import adapts
from zope.component import getUtility
from zope.component import getUtilitiesFor
from zope.annotation.interfaces import IAnnotations
from persistent.dict import PersistentDict
from zope.i18n import MessageFactory
import appconfig
from zope import component

expr = re.compile(r"^(w&.%#$&'*+-/=?^_`{}|~]+!)*[w&.%#$&'*+-/=?^_`{}|~]+"
                  r"@(([0-9a-z]([0-9a-z-]*[0-9a-z])?.)+[a-z]{2,6}|([0-9]{1,3}"
                  r".){3}[0-9]{1,3})$", re.IGNORECASE)
check_email = expr.match


##############################################################################
### I N T E R F A C E S ######################################################
##############################################################################

_ = MessageFactory('tpi')

USER_DATA_KEY = 'tpi.iuser.data'

################################################## email validation

class NotAnEmailAddress(schema.ValidationError):
    __doc__ = _(u"Invalid email address")

check_email = re.compile(r"[a-zA-Z0-9._%-]+@([a-zA-Z0-9-]+.)*[a-zA-Z]{2,4}").match
def valid_email(value):
    if check_email(value):
        return True
    raise NotAnEmailAddress(value)

################################################## login name validation

class LoginNameTaken(schema.ValidationError):
    __doc__ = _(u"Login name already in use. Please choose a different id")

def unique_login(login):
    pau = getUtility(IAuthentication)
    if login in pau['principals']:
        raise LoginNameTaken
    return True


################################################## login name validation

class NotValidLogin(schema.ValidationError):
    __doc__ = _(u"Login name is invalid. Please check your records.")

def check_valid_login(login):
    pau = getUtility(IAuthentication)
    if login not in pau['principals']:
        raise NotValidLogin
    return True

################################################## password manager selection

class PasswordManagerChoices(object):
    implements(schema.interfaces.IIterableSource)
    
    def __init__(self):
        self.choices = [name for name, util in
                            sorted(getUtilitiesFor(IPasswordManager))]
        
    def __iter__(self):
        return iter(self.choices)
    
    def __len__(self):
        return len(self.choices)
    
    def __contains__(self, value):
        return value in self.choices

################################################## interfaces


class IUser(Interface):
    """Basic user data."""
    login = schema.TextLine(title=_(u"Login"),
                            required=True,
                            constraint=unique_login)
    password = schema.Password(title=_(u"Password"),
                            required=True)
    password_repeat = schema.Password(title=_(u"Password repeat"),
                            required=True)
    fname = schema.TextLine(title=_(u"First name"),
                            required=False)
    lname = schema.TextLine(title=_(u"Last name"),
                            required=False)
    email = schema.ASCIILine(title=_(u"E-mail"),
                            required=False,
                            constraint=valid_email)

### P E R M I S S I O N S ####################################################


class ViewClients(grok.Permission):
    grok.name('tpi.ViewClients')
    grok.title('View Clients')

class AddClient(grok.Permission):
    grok.name('tpi.AddClient')
    grok.title('Add Client')

class DeleteClient(grok.Permission):
    grok.name('tpi.DeleteClients')
    grok.title('Delete Clients')

class ViewMemberListing(grok.Permission):
    grok.name('tpi.ViewMemberListing')
    grok.title('View TPI Members')




### H E L P E R   S C R I P T S  #############################################

_ = MessageFactory('tpi')

def setup_pau(pau):
    pau['principals'] = PrincipalFolder('tpi.principals.')
    pau.authenticatorPlugins = ('principals',)
    pau['session'] = session = SessionCredentialsPlugin()
    session.loginpagename = 'login'
    pau.credentialsPlugins = ('No Challenge if Authenticated', 'session',)

def role_factory(*args):
    def factory():
        return LocalRole(*args)
    return factory


##############################################################################
### A P P L I C A T I O N ####################################################
##############################################################################

class Tpi(grok.Application, grok.Container):
    def __init__(self):
        super(Tpi, self).__init__()

class GlobalMacros(grok.View):
    grok.context(Interface)
    grok.name('globalmacros')

class Index(grok.View):
    grok.context(Tpi)
    grok.name('index')
    def navLIST(self, name):
        if name not in appconfig.menuitems.keys():
            pass
        else:
            return appconfig.menuitems[name]

##############################################################################
### A U T H E N T I C A T I O N ##############################################
##############################################################################

class Register(grok.Form):
    
    form_fields = grok.AutoFields(IUser)
    label = u'User registration'
    template = grok.PageTemplateFile('form.pt')

    @grok.action('Sign up')
    def save(self, login, password, password_repeat, fname, lname, email):
        # TODO: validate password is equal to password_repeat
        
        # add principal to principal folder
        
        pau = getUtility(IAuthentication)
        principals = pau['principals']
        name = fname + ' ' + lname      
        principals[login] = InternalPrincipal(login, password, name)

        # grant principal the role
        role_manager = IPrincipalRoleManager(self.context)
        role_manager.assignRoleToPrincipal('tpi.Employee',
                                           principals.prefix + login)
        self.redirect('index')


class Login(grok.View):
    grok.context(Interface)

    def update(self, login=None, password=None, login_submit=None):
        if (not IUnauthenticatedPrincipal.providedBy(self.request.principal)
            and login_submit is not None):
            camefrom = self.request.get('camefrom', '.')
            self.redirect(camefrom)


class Logout(grok.View):
    grok.context(Interface)

    def render(self):
        # get the session plugin and tell it to logout
        session = component.getUtility(IAuthentication)['session']
        session.logout(self.request)
        # redirect to the main page
        self.redirect(self.application_url())


class MyAccount(grok.View):
    grok.context(Interface)

    def render(self):
        return 'Not yet implemented'


class MemberListing(grok.View):
    grok.implements(IUser)
    def fieldNames(self):
        return (f for f in IUser)

    def members(self):
        pau = component.getUtility(IAuthentication)
        principals = pau['principals']
        roster = [ ]
        for id in sorted(principals.keys()):
            print id
            #user = IUser(principals[id])        # <----- this is where the code is breaking
            #fields = {}
            #for field in IUser:
            #    fields[field] = getattr(user, field)
            #roster.append(fields)
        return roster



Untitled Python (21-May @ 05:25)

Syntax Highlighted Code

  1. import grok
  2. from grok import index
  3. import appconfig
  4. from zope.interface import Interface # this import will allow macros to access any object in any context
  5. [183 more lines...]

Plain Code

import grok
from grok import index
import appconfig
from zope.interface import Interface # this import will allow macros to access any object in any context
from zope import interface, schema
from z3c.widget.tiny.widget import TinyWidget
from agreements import IAgreements
from agreements import Agreements
from agreement import Agreement
from clients import IClients
from clients import Clients
from client import IClient
from client import Client
from shoot import Shoot
from shoots import IShoots
from shoots import Shoots
from invoice import Invoice
from billablehours import BillableHours
from imagerepository import ImageRepository
from pendingconfirmations import IPendingConfirmations
from pendingconfirmations import PendingConfirmations
from pendingconfirmation import PendingConfirmation
from groffs import Groffs
from groff import Groff
import apputils
import appconfig
from urllib import urlencode
from zope.interface import implements
from zope.interface import classImplements
from zope.component import getUtility
from zope.component import provideAdapter
from zope.app.authentication import PluggableAuthentication
from zope.app.authentication.principalfolder import PrincipalFolder
from zope.app.authentication.principalfolder import InternalPrincipal
from zope.app.authentication.session import SessionCredentialsPlugin
# XXX: Failed attempt to display the password_encoding field
# from zope.app.form.browser.source import SourceDropdownWidget
from zope.app.security.interfaces import IAuthentication
from zope.app.security.interfaces import IUnauthenticatedPrincipal
from zope.securitypolicy.interfaces import IPrincipalRoleManager, IRole
from zope.securitypolicy.interfaces import IPrincipalPermissionManager
from zope.securitypolicy.interfaces import IRolePermissionManager
from zope.annotation.interfaces import IAttributeAnnotatable
from zope.i18n import MessageFactory
from interfaces import IUser
from interfaces import UserDataAdapter
from zope import component

### H E L P E R   S C R I P T S  #############################################

def setup_pau(pau):
    pau['principals'] = PrincipalFolder('nudge.principals.')
    pau.authenticatorPlugins = ('principals',)
    pau['session'] = session = SessionCredentialsPlugin()
    session.loginpagename = 'login'
    pau.credentialsPlugins = ('No Challenge if Authenticated', 'session',)

def role_factory(*args):
    def factory():
        return LocalRole(*args)
    return factory

##############################################################################
### A P P L I C A T I O N ####################################################
##############################################################################

class Tpi(grok.Application, grok.Container):
    def __init__(self):
        super(Tpi, self).__init__()
        # create top level folders
        self['clients'] = Clients()
        self['agreements'] = Agreements()
        self['shoots'] = Shoots()
        self['confirmations'] = PendingConfirmations()
        self['groffs'] = Groffs()

### P E R M I S S I O N S ####################################################

    class ViewClients(grok.Permission):
        grok.name('tpi.ViewClients')
        grok.title('View Clients')

    class AddClient(grok.Permission):
        grok.name('tpi.AddClient')
        grok.title('Add Client')

    class DeleteClient(grok.Permission):
        grok.name('tpi.DeleteClients')
        grok.title('Delete Clients')

### U T I L I T I E S  #######################################################

    # register authentication utility
    grok.local_utility(PluggableAuthentication, IAuthentication, 
                       setup=setup_pau)

    # register Admin Role  
    grok.local_utility(role_factory(u'TPI Administrator'), IRole,
                       name='tpi.Admin',
                       name_in_container='tpi.Admin')

    # register Employee Role  
    grok.local_utility(role_factory(u'TPI Employees'), IRole,
                       name='tpi.Employees',
                       name_in_container='tpi.Employees')

### S U B S C R I B E R S ####################################################

@grok.subscribe(Tpi, grok.IObjectAddedEvent)
def grant_permissions(app, event):
    role_manager = IRolePermissionManager(app)
    # Admin Permissions
    role_manager.grantPermissionToRole('tpi.ViewClients', 'tpi.Employees')
    role_manager.grantPermissionToRole('tpi.AddClient', 'tpi.Employees')
    role_manager.grantPermissionToRole('tpi.DeleteClient', 'tpi.Admin')
    # Employee Permissions
    role_manager.grantPermissionToRole('tpi.ViewClients', 'tpi.Employees')
    role_manager.grantPermissionToRole('tpi.AddClient', 'tpi.Employees')

### C A T A L O G S ##########################################################

class ClientIndex(grok.Indexes):
    grok.site(Tpi)
    grok.context(IClient) #objects implementing this interface will be indexed
    grok.name('client_catalog') #name of catalog
    name = index.Field(attribute='name')
    email = index.Field(attribute='email')
    uid = index.Field(attribute='uid')


##############################################################################
### V I E W S ################################################################
##############################################################################

class GlobalMacros(grok.View):
    grok.context(Interface)
    grok.name('globalmacros')

class Index(grok.View):
    grok.context(Tpi)
    grok.name('index')
    def navLIST(self, name):
        if name not in appconfig.menuitems.keys():
            pass
        else:
            return appconfig.menuitems[name]

##############################################################################
### A U T H E N T I C A T I O N ##############################################
##############################################################################

class SignUp(grok.Form):
    
    form_fields = grok.Fields(
        name = schema.TextLine(title=u"Your name"),
        # TODO: validate email address
        email = schema.TextLine(title=u"Email address"),
        password = schema.Password(title=u"Password"),
        password_repeat = schema.Password(title=u"Repeat password"),
        )

    @grok.action('Sign up')
    def sign_up(self, name, email, password, password_repeat):
        # TODO: validate password is equal to password_repeat

        # add principal to principal folder
        pau = component.getUtility(IAuthentication)
        principals = pau['principals']
        principals[email] = user = InternalPrincipal(email, password, name)

        # grant principal the role
        role_manager = IPrincipalRoleManager(self.context)
        role_manager.assignRoleToPrincipal('tpi.Employee',
                                           principals.prefix + email)
        self.redirect('index')

class Login(grok.View):
    grok.context(Interface)

    def update(self, login_submit=None):
        if (not IUnauthenticatedPrincipal.providedBy(self.request.principal)
            and login_submit is not None):
            camefrom = self.request.get('camefrom', '.')
            self.redirect(camefrom)



Untitled Python (19-May @ 07:39)

Syntax Highlighted Code

  1. import grok
  2. import appconfig
  3. from zope.interface import Interface # this import will allow macros to access any object in any context
  4. from zope import interface, schema
  5. [247 more lines...]

Plain Code

import grok
import appconfig
from zope.interface import Interface # this import will allow macros to access any object in any context
from zope import interface, schema
from z3c.widget.tiny.widget import TinyWidget
from agreements import IAgreements
from agreements import Agreements
from agreement import Agreement
from clients import IClients
from clients import Clients
from client import Client
from shoot import Shoot
from shoots import IShoots
from shoots import Shoots
from invoice import Invoice
from billablehours import BillableHours
from imagerepository import ImageRepository
from pendingconfirmations import IPendingConfirmations
from pendingconfirmations import PendingConfirmations
from pendingconfirmation import PendingConfirmation
from groffs import Groffs
from groff import Groff
import apputils
import appconfig
from urllib import urlencode
from zope.interface import Interface, implements, classImplements
from zope.component import getUtility, provideAdapter
from zope.app.authentication import PluggableAuthentication
from zope.app.authentication.principalfolder import PrincipalFolder
from zope.app.authentication.principalfolder import InternalPrincipal
from zope.app.authentication.session import SessionCredentialsPlugin
# XXX: Failed attempt to display the password_encoding field
# from zope.app.form.browser.source import SourceDropdownWidget
from zope.app.security.interfaces import IAuthentication
from zope.app.security.interfaces import IUnauthenticatedPrincipal
from zope.securitypolicy.interfaces import IPrincipalPermissionManager
from zope.annotation.interfaces import IAttributeAnnotatable
from zope.i18n import MessageFactory



class Tpi(grok.Application, grok.Container):
    def __init__(self):
        super(Tpi, self).__init__()
        self['clients'] = Clients()
        self['agreements'] = Agreements()
        self['shoots'] = Shoots()
        self['confirmations'] = PendingConfirmations()
        self['groffs'] = Groffs()
        

##############################################################################
### V I E W ##################################################################
##############################################################################

class GlobalMacros(grok.View):
    grok.context(Interface)
    grok.name('globalmacros')

    def objVALUES(self):
        return [ (key,self.context[key]) for key in self.context.keys() ]


##############################################################################
### V I E W ##################################################################
##############################################################################

class Index(grok.View):
    grok.context(Tpi)
    grok.name('index')

### L I S T I N G S ##########################################################

    def objVALUES(self):
        return [ (key,self.context[key]) for key in self.context.keys() ]

    def navLIST(self, name):
        if name not in appconfig.menuitems.keys():
            pass
        else:
            return appconfig.menuitems[name]

##############################################################################
### A U T H E N T I C A T I O N   C R A P ####################################
##############################################################################

from interfaces import IUser, UserDataAdapter  

_ = MessageFactory('logindemo')

def setup_pau(pau):
    '''
    Callback to setup the Pluggable Authentication Utility
    A reference to this function is passed as a parameter in the
    declaration of the PAU (see LoginDemo class)
    '''
    # the principal source is a PrincipalFolder, stored in ZODB
    pau['principals'] = PrincipalFolder() 
    pau.authenticatorPlugins = ('principals',)
    # the SessionCredentialsPlugin isused for cookie-based authentication
    pau['session'] = session = SessionCredentialsPlugin()
    session.loginpagename = 'login' # the page to redirect for login
    # configuration of the credentials plugin
    pau.credentialsPlugins = ('No Challenge if Authenticated', 'session',)
        
class LoginDemo(grok.Application, grok.Container):
    """
    An app that lets you create an account and change your password.
    """
    # register the authentication utility; see setup_pau for settings
    grok.local_utility(PluggableAuthentication, IAuthentication,
                       setup=setup_pau)
    # make InternalPrincipal instances annotatable
    classImplements(InternalPrincipal,IAttributeAnnotatable)
    # register the adapter for IInternalPrincipal which provides IUser
    provideAdapter(UserDataAdapter)
           
class ViewMemberListing(grok.Permission):
    ''' Permission to see the member listing '''
    grok.name('logindemo.ViewMemberListing')

class Master(grok.View):
    """
    The master page template macro.
    
    The template master.pt is used as page macro in most views. Since this
    template uses the logged_in method and message attributes below, it's best
    to make all other views in this app subclasses of Master.
    """
    grok.context(Interface)  # register this view for all objects

    message = '' # used to give feedback

    def logged_in(self):
        # this is the canonical way to tell whether the user is authenticated
        # in Zope 3: check if the principal provides IUnauthenticatedPrincipal
        return not IUnauthenticatedPrincipal.providedBy(self.request.principal)
    
class Members(Master):
    """
    The main page, showing user data and member count.
    """

    def members(self):
        # get the authentication utility
        pau = getUtility(IAuthentication)
        result = len(pau['principals'])
        if result == 0:
            return _(u'No one has')
        elif result == 1:
            return _(u'One member has')
        else:
            return unicode(result) + _(u' members have')

    
class Login(Master):
    """
    Login form and handler.
    """
    def update(self, login_submit=None):
        if login_submit is not None: # we are handling the login submission
            if self.logged_in(): # if the login was accepted then...
                # redirect to where the user came from, or to the main page
                dest = self.request.get('camefrom', self.application_url())
                self.redirect(dest)
            else: # if the user is still not logged in...
                # then an incorrect login or password was provided
                self.message = _(u'Invalid login name and/or password')

class Logout(grok.View):
    """
    Logout handler.
    """
    grok.context(Interface)
    def render(self):
        # get the session plugin and tell it to logout
        session = getUtility(IAuthentication)['session']
        session.logout(self.request)
        # redirect to the main page
        self.redirect(self.application_url())
        
class Join(grok.AddForm, Master):
    """
    User registration form.
    """
    form_fields = grok.AutoFields(IUser)
    # XXX: Failed attempt to display the password_encoding field
    #form_fields[u'password_encoding'].custom_widget = SourceDropdownWidget
    label = u'User registration'
    template = grok.PageTemplateFile('form.pt')
    
    @grok.action('Save')
    def save(self, **data):
        '''
        Create an InternalPrincipal with the user data.
        
        This method also sets extra fields using an annotations through
        the IUser adapter, and grants the ViewMemberListing permission to
        the principal just created.
        '''
        login = data['login']
        pau = getUtility(IAuthentication)
        principals = pau['principals']
        # create an instance of InternalPrincipal
        principal = InternalPrincipal(login, data['password'], data['name'],
                                      passwordManagerName='SHA1')
        # add principal to principal folder; we may assume that the login
        # name is unique because of validation on the IUser interface
        # but to be doubly sure, we assert this
        assert(login not in principals)
        principals[login] = principal
        # save the e-mail
        user = IUser(principal)
        user.email = data['email']
        # grant the user permission to view the member listing
        permission_mngr = IPrincipalPermissionManager(grok.getSite())
        permission_mngr.grantPermissionToPrincipal(
           'logindemo.ViewMemberListing', principals.prefix + login)

        self.redirect(self.url('login')+'?'+urlencode({'login':login}))
                    
class Account(grok.View):
    
    grok.context(LoginDemo)
    def render(self):
        return 'Not implemented'
    
class Listing(Master):
    '''
    Member listing view. This demonstrates how to require a permission to view, and also how to
    obtain a list of annotated principals.
    '''

    grok.require('logindemo.ViewMemberListing')

    def fieldNames(self):
        return (f for f in IUser)

    def members(self):
        pau = getUtility(IAuthentication)
        principals = pau['principals']
        roster = []
        for id in sorted(principals.keys()):
            # adapt the principals to IUser to get all fields
            user = IUser(principals[id])
            fields = {}
            for field in IUser:
                fields[field] = getattr(user, field)
            roster.append(fields)
        return roster

Untitled Python (19-May @ 07:35)

Syntax Highlighted Code

  1. grok.local_utility(PluggableAuthentication, IAuthentication,
  2.                    setup=setup_pau)
  3.  

Plain Code

grok.local_utility(PluggableAuthentication, IAuthentication,
                   setup=setup_pau)

Untitled Python (19-May @ 06:12)

Syntax Highlighted Code

  1. ./bin/zopectl fg
  2. /home/sancho/grok-wsgi/rdbexample/parts/app/runzope -C /home/sancho/grok-wsgi/rdbexample/parts/zopectl/zope.conf
  3. /home/sancho/grok-wsgi/rdbexample/collective.lead/collective/lead/database.py:36: SADeprecationWarning: The 'transactional' argument to sessionmaker() is deprecated; use autocommit=True|False instead.
  4.   self._Session = scoped_session(sessionmaker(
  5. [35 more lines...]

Plain Code

./bin/zopectl fg
/home/sancho/grok-wsgi/rdbexample/parts/app/runzope -C /home/sancho/grok-wsgi/rdbexample/parts/zopectl/zope.conf
/home/sancho/grok-wsgi/rdbexample/collective.lead/collective/lead/database.py:36: SADeprecationWarning: The 'transactional' argument to sessionmaker() is deprecated; use autocommit=True|False instead.
  self._Session = scoped_session(sessionmaker(
------
2008-05-19T02:11:48 INFO root -- HTTP:localhost:8080 Server started.
        Hostname: localhost
        Port: 8080
------
2008-05-19T02:11:48 INFO root Startup time: 3.524 sec real, 3.450 sec CPU
------
2008-05-19T02:11:48 ERROR SiteError http://localhost:8080/example/@@index
Traceback (most recent call last):
  File "/home/sancho/grok-wsgi/rdbexample/eggs/tmp-ZoTc1/zope.publisher-3.4.2-py2.4.egg/zope/publisher/publish.py", line 133, in publish
  File "/home/sancho/grok-wsgi/rdbexample/grok/src/grok/publication.py", line 45, in callObject
    return super(ZopePublicationSansProxy, self).callObject(request, ob)
  File "/home/sancho/grok-wsgi/rdbexample/eggs/tmpWGUZJt/zope.app.publication-3.4.3-py2.4.egg/zope/app/publication/zopepublication.py", line 167, in callObject
  File "/home/sancho/grok-wsgi/rdbexample/eggs/tmp-ZoTc1/zope.publisher-3.4.2-py2.4.egg/zope/publisher/publish.py", line 108, in mapply
   - __traceback_info__: <rdbexample.app.FacultyList object at 0x9f8f02c>
  File "/home/sancho/grok-wsgi/rdbexample/eggs/tmp-ZoTc1/zope.publisher-3.4.2-py2.4.egg/zope/publisher/publish.py", line 114, in debug_call
  File "/home/sancho/grok-wsgi/rdbexample/grok/src/grok/components.py", line 173, in __call__
    return mapply(self.render, (), self.request)
  File "/home/sancho/grok-wsgi/rdbexample/eggs/tmp-ZoTc1/zope.publisher-3.4.2-py2.4.egg/zope/publisher/publish.py", line 108, in mapply
   - __traceback_info__: <bound method FacultyList.render of <rdbexample.app.FacultyList object at 0x9f8f02c>>
  File "/home/sancho/grok-wsgi/rdbexample/eggs/tmp-ZoTc1/zope.publisher-3.4.2-py2.4.egg/zope/publisher/publish.py", line 114, in debug_call
  File "/home/sancho/grok-wsgi/rdbexample/src/rdbexample/app.py", line 32, in render
    for faculty in rdb.query(Faculty).all():
  File "/home/sancho/grok-wsgi/rdbexample/megrok.rdb/src/megrok/rdb/__init__.py", line 15, in query
    return database.session.query(class_)
  File "/home/sancho/grok-wsgi/rdbexample/collective.lead/collective/lead/database.py", line 102, in session
    self._join_transaction()
  File "/home/sancho/grok-wsgi/rdbexample/collective.lead/collective/lead/database.py", line 96, in _join_transaction
    tx.join_transaction(self._Session(), self._initial_transaction_status)
  File "/home/sancho/grok-wsgi/rdbexample/collective.lead/collective/lead/tx.py", line 152, in join_transaction
    transaction.get().join(DataManager(session, initial_status))
  File "/home/sancho/grok-wsgi/rdbexample/collective.lead/collective/lead/tx.py", line 26, in __init__
    if session.transactional:
AttributeError: 'Session' object has no attribute 'transactional'

Untitled Python (17-May @ 16:51)

Syntax Highlighted Code

  1. import grok
  2. import appconfig
  3. from zope import interface, schema
  4. from groff import Groff
  5. [76 more lines...]

Plain Code

import grok
import appconfig
from zope import interface, schema
from groff import Groff
import apputils
import uuid, time
import fsutils
import subprocess

##############################################################################
### M O D E L ################################################################
##############################################################################

class IClients(interface.Interface):
    pass

class Groffs(grok.Container):
    def __init__(self):
        super(Groffs, self).__init__()

    def traverse(self, name):
        if name in self.keys():
            return self[name]

##############################################################################
### V I E W ##################################################################
##############################################################################

class Index(grok.View):
    grok.context(Groffs)
    grok.name('index')

    def listGroffObjects(self):
        return ( name for name,obj in self.context.items() if isinstance(obj, Groff))

    def readPDF(self,pdfuri):
        return fsutils.file_to_stringIO(pdfuri)

    def writeMOM(self, obj):
        template = open(appconfig.xtemplate).read()
        momuri = appconfig.groffsuri + obj.__name__
        mom = open(momuri, 'w')
        mom.write(template %(obj.fname + ' ' + obj.lname))
        return momuri

    def addGROFF(self, *arg):
        uid = apputils.genUUID()
        self.context[uid] = Groff(*arg)
        self.context._p_changed = True
        return self.context[uid]
        
    def groffME(self, momuri, pdfuri):
        ret = subprocess.call("groff -mom %s | pstopdf -i -o %s" %(momuri,pdfuri), 
                              shell=True,
                              stdout=open('/dev/null', 'w'),
                              stderr=subprocess.STDOUT)
        return ret

    def update(self, fname=None, lname=None, email=None, groffbitch=None, groff=None):
        if fname and lname and email:
            obj = self.addGROFF(fname, lname, email)
            momuri = self.writeMOM(obj)
            pdfuri = appconfig.groffsuri + obj.__name__ + '.pdf'
            if self.groffME(momuri, pdfuri) == 0:
                pass
            obj.pdfuri = pdfuri
        if groff:
            pdfuri = self.context[groff].pdfuri
            pdf = self.readPDF(pdfuri)
            RESPONSE = self.request.response
            RESPONSE.setHeader('content-type', 'application/pdf')
            RESPONSE.setHeader('content-length', str(len(pdf)))
            RESPONSE.setHeader('content-disposition', 'attachment; filename=%s' %(groff + '.pdf'))
            return pdf
        



    

    

Untitled Python (17-May @ 06:42)

Syntax Highlighted Code

  1. def addPENDINGCONFIRMATION(self, client, agreement, datetime_sent):
  2.     app = self.context.__parent__.__parent__
  3.     confirmations = app['confirmations']
  4.     uid = apputils.genUUID()
  5. [2 more lines...]

Plain Code

def addPENDINGCONFIRMATION(self, client, agreement, datetime_sent):
    app = self.context.__parent__.__parent__
    confirmations = app['confirmations']
    uid = apputils.genUUID()
    confirmations[uid] = PendingConfirmation(client, agreement, datetime_sent)
    confirmations._p_changed = True

Untitled Python (16-May @ 17:37)

Syntax Highlighted Code

  1. ------
  2. 2008-05-16T13:36:53 ERROR SiteError http://localhost:8080/mechanic/@@index
  3. Traceback (most recent call last):
  4.   File "/home/sancho/grok-wsgi/lib/python2.4/site-packages/zope.publisher-3.5.0a1.dev_r78838-py2.4.egg/zope/publisher/publish.py", line 133, in publish
  5. [43 more lines...]

Plain Code

------
2008-05-16T13:36:53 ERROR SiteError http://localhost:8080/mechanic/@@index
Traceback (most recent call last):
  File "/home/sancho/grok-wsgi/lib/python2.4/site-packages/zope.publisher-3.5.0a1.dev_r78838-py2.4.egg/zope/publisher/publish.py", line 133, in publish
    result = publication.callObject(request, obj)
  File "/home/sancho/grok-wsgi/lib/python2.4/site-packages/grok-0.12-py2.4.egg/grok/publication.py", line 45, in callObject
    return super(ZopePublicationSansProxy, self).callObject(request, ob)
  File "/home/sancho/grok-wsgi/lib/python2.4/site-packages/zope.app.publication-3.4.2-py2.4.egg/zope/app/publication/zopepublication.py", line 167, in callObject
    return mapply(ob, request.getPositionalArguments(), request)
  File "/home/sancho/grok-wsgi/lib/python2.4/site-packages/zope.publisher-3.5.0a1.dev_r78838-py2.4.egg/zope/publisher/publish.py", line 108, in mapply
    return debug_call(obj, args)
   - __traceback_info__: <dbmechanic.app.Index object at 0xa1ad36c>
  File "/home/sancho/grok-wsgi/lib/python2.4/site-packages/zope.publisher-3.5.0a1.dev_r78838-py2.4.egg/zope/publisher/publish.py", line 114, in debug_call
    return obj(*args)
  File "/home/sancho/grok-wsgi/lib/python2.4/site-packages/grok-0.12-py2.4.egg/grok/components.py", line 139, in __call__
    return self._render_template()
  File "/home/sancho/grok-wsgi/lib/python2.4/site-packages/grok-0.12-py2.4.egg/grok/components.py", line 143, in _render_template
    return self.template.render(self)
  File "/home/sancho/grok-wsgi/lib/python2.4/site-packages/megrok.genshi-0.9-py2.4.egg/megrok/genshi/components.py", line 26, in render
    return stream.render(self.result_type)
  File "/home/sancho/grok-wsgi/lib/python2.4/site-packages/Genshi-0.4.4-py2.4.egg/genshi/core.py", line 154, in render
  File "/home/sancho/grok-wsgi/lib/python2.4/site-packages/Genshi-0.4.4-py2.4.egg/genshi/output.py", line 45, in encode
  File "/home/sancho/grok-wsgi/lib/python2.4/site-packages/Genshi-0.4.4-py2.4.egg/genshi/output.py", line 274, in __call__
  File "/home/sancho/grok-wsgi/lib/python2.4/site-packages/Genshi-0.4.4-py2.4.egg/genshi/output.py", line 519, in __call__
  File "/home/sancho/grok-wsgi/lib/python2.4/site-packages/Genshi-0.4.4-py2.4.egg/genshi/output.py", line 679, in __call__
  File "/home/sancho/grok-wsgi/lib/python2.4/site-packages/Genshi-0.4.4-py2.4.egg/genshi/output.py", line 459, in __call__
  File "/home/sancho/grok-wsgi/lib/python2.4/site-packages/Genshi-0.4.4-py2.4.egg/genshi/core.py", line 212, in _ensure
  File "/home/sancho/grok-wsgi/lib/python2.4/site-packages/Genshi-0.4.4-py2.4.egg/genshi/template/markup.py", line 252, in _include
  File "/home/sancho/grok-wsgi/lib/python2.4/site-packages/Genshi-0.4.4-py2.4.egg/genshi/template/markup.py", line 297, in _match
  File "/home/sancho/grok-wsgi/lib/python2.4/site-packages/Genshi-0.4.4-py2.4.egg/genshi/template/markup.py", line 242, in _exec
  File "/home/sancho/grok-wsgi/lib/python2.4/site-packages/Genshi-0.4.4-py2.4.egg/genshi/template/base.py", line 421, in _eval
  File "/home/sancho/grok-wsgi/lib/python2.4/site-packages/Genshi-0.4.4-py2.4.egg/genshi/template/eval.py", line 136, in evaluate
  File "/home/sancho/grok-wsgi/DBMechanic/src/dbmechanic/app_templates/index.g", line 11, in <Expression u'view.form()'>
    ${view.form()}
  File "/home/sancho/grok-wsgi/lib/python2.4/site-packages/ToscaWidgets-0.8.5-py2.4.egg/tw/core/base.py", line 474, in __call__
    return self.display(value, **kw)
  File "/home/sancho/grok-wsgi/lib/python2.4/site-packages/ToscaWidgets-0.8.5-py2.4.egg/tw/core/base.py", line 468, in display
    kw = self.prepare_dict(value, kw)
  File "/home/sancho/grok-wsgi/lib/python2.4/site-packages/tw.forms-0.8-py2.4.egg/tw/forms/core.py", line 180, in prepare_dict
    error = kw.setdefault('error', self.error_at_request)
  File "/home/sancho/grok-wsgi/lib/python2.4/site-packages/ToscaWidgets-0.8.5-py2.4.egg/tw/core/util.py", line 235, in __get__
    return getattr(request_local, self.name)
  File "/home/sancho/grok-wsgi/lib/python2.4/site-packages/Paste-1.5-py2.4.egg/paste/registry.py", line 125, in __getattr__
    return getattr(self._current_obj(), attr)
  File "/home/sancho/grok-wsgi/lib/python2.4/site-packages/Paste-1.5-py2.4.egg/paste/registry.py", line 180, in _current_obj
    raise TypeError(
TypeError: No object (name: ToscaWidgets per-request storage) has been registered for this thread

Untitled Python (16-May @ 05:05)

Syntax Highlighted Code

  1. Traceback (most recent call last):
  2.   File "./bin/paster", line 7, in ?
  3.     sys.exit(
  4.   File "/home/sancho/grok-wsgi/lib/python2.4/site-packages/PasteScript-1.3.6-py2.4.egg/paste/script/command.py", line 78, in run
  5. [22 more lines...]

Plain Code

Traceback (most recent call last):
  File "./bin/paster", line 7, in ?
    sys.exit(
  File "/home/sancho/grok-wsgi/lib/python2.4/site-packages/PasteScript-1.3.6-py2.4.egg/paste/script/command.py", line 78, in run
    invoke(command, command_name, options, args[1:])
  File "/home/sancho/grok-wsgi/lib/python2.4/site-packages/PasteScript-1.3.6-py2.4.egg/paste/script/command.py", line 117, in invoke
    exit_code = runner.run(args)
  File "/home/sancho/grok-wsgi/lib/python2.4/site-packages/PasteScript-1.3.6-py2.4.egg/paste/script/command.py", line 212, in run
    result = self.command()
  File "/home/sancho/grok-wsgi/lib/python2.4/site-packages/PasteScript-1.3.6-py2.4.egg/paste/script/serve.py", line 227, in command
    relative_to=base, global_conf=vars)
  File "/home/sancho/grok-wsgi/lib/python2.4/site-packages/PasteScript-1.3.6-py2.4.egg/paste/script/serve.py", line 248, in loadapp
    return loadapp(
  File "/home/sancho/grok-wsgi/lib/python2.4/site-packages/PasteDeploy-1.3.1-py2.4.egg/paste/deploy/loadwsgi.py", line 193, in loadapp
    return loadobj(APP, uri, name=name, **kw)
  File "/home/sancho/grok-wsgi/lib/python2.4/site-packages/PasteDeploy-1.3.1-py2.4.egg/paste/deploy/loadwsgi.py", line 214, in loadobj
    return context.create()
  File "/home/sancho/grok-wsgi/lib/python2.4/site-packages/PasteDeploy-1.3.1-py2.4.egg/paste/deploy/loadwsgi.py", line 606, in create
    return self.object_type.invoke(self)
  File "/home/sancho/grok-wsgi/lib/python2.4/site-packages/PasteDeploy-1.3.1-py2.4.egg/paste/deploy/loadwsgi.py", line 157, in invoke
    app = filter(app)
  File "/home/sancho/grok-wsgi/lib/python2.4/site-packages/PasteDeploy-1.3.1-py2.4.egg/paste/deploy/loadwsgi.py", line 118, in filter_wrapper
    wsgi_app, context.global_conf,
  File "/home/sancho/grok-wsgi/lib/python2.4/site-packages/PasteDeploy-1.3.1-py2.4.egg/paste/deploy/util/fixtypeerror.py", line 57, in fix_call
    val = callable(*args, **kw)
TypeError: make_middleware() got an unexpected keyword argument 'default_view'

Untitled Python (16-May @ 01:58)

Syntax Highlighted Code

  1. sancho@mulata:~/grok-wsgi$ ./bin/paster serve etc/grok.ini
  2. Traceback (most recent call last):
  3.   File "./bin/paster", line 7, in ?
  4.     sys.exit(
  5. [67 more lines...]

Plain Code

sancho@mulata:~/grok-wsgi$ ./bin/paster serve etc/grok.ini 
Traceback (most recent call last):
  File "./bin/paster", line 7, in ?
    sys.exit(
  File "/home/sancho/grok-wsgi/lib/python2.4/site-packages/PasteScript-1.3.6-py2.4.egg/paste/script/command.py", line 78, in run
    invoke(command, command_name, options, args[1:])
  File "/home/sancho/grok-wsgi/lib/python2.4/site-packages/PasteScript-1.3.6-py2.4.egg/paste/script/command.py", line 117, in invoke
    exit_code = runner.run(args)
  File "/home/sancho/grok-wsgi/lib/python2.4/site-packages/PasteScript-1.3.6-py2.4.egg/paste/script/command.py", line 212, in run
    result = self.command()
  File "/home/sancho/grok-wsgi/lib/python2.4/site-packages/PasteScript-1.3.6-py2.4.egg/paste/script/serve.py", line 227, in command
    relative_to=base, global_conf=vars)
  File "/home/sancho/grok-wsgi/lib/python2.4/site-packages/PasteScript-1.3.6-py2.4.egg/paste/script/serve.py", line 248, in loadapp
    return loadapp(
  File "/home/sancho/grok-wsgi/lib/python2.4/site-packages/PasteDeploy-1.3.1-py2.4.egg/paste/deploy/loadwsgi.py", line 193, in loadapp
    return loadobj(APP, uri, name=name, **kw)
  File "/home/sancho/grok-wsgi/lib/python2.4/site-packages/PasteDeploy-1.3.1-py2.4.egg/paste/deploy/loadwsgi.py", line 214, in loadobj
    return context.create()
  File "/home/sancho/grok-wsgi/lib/python2.4/site-packages/PasteDeploy-1.3.1-py2.4.egg/paste/deploy/loadwsgi.py", line 606, in create
    return self.object_type.invoke(self)
  File "/home/sancho/grok-wsgi/lib/python2.4/site-packages/PasteDeploy-1.3.1-py2.4.egg/paste/deploy/loadwsgi.py", line 153, in invoke
    app = context.app_context.create()
  File "/home/sancho/grok-wsgi/lib/python2.4/site-packages/PasteDeploy-1.3.1-py2.4.egg/paste/deploy/loadwsgi.py", line 606, in create
    return self.object_type.invoke(self)
  File "/home/sancho/grok-wsgi/lib/python2.4/site-packages/PasteDeploy-1.3.1-py2.4.egg/paste/deploy/loadwsgi.py", line 99, in invoke
    return fix_call(context.object, context.global_conf, **context.local_conf)
  File "/home/sancho/grok-wsgi/lib/python2.4/site-packages/PasteDeploy-1.3.1-py2.4.egg/paste/deploy/util/fixtypeerror.py", line 57, in fix_call
    val = callable(*args, **kw)
  File "/home/sancho/grok-wsgi/lib/python2.4/site-packages/repoze.grok-0.1.5-py2.4.egg/repoze/grok/bbb.py", line 37, in make_grokapp
    app = getWSGIApplication(config_file)
  File "/home/sancho/grok-wsgi/lib/python2.4/site-packages/zope.app.wsgi-3.4.0-py2.4.egg/zope/app/wsgi/__init__.py", line 134, in getWSGIApplication
    db = config(configfile, schemafile, features)
  File "/home/sancho/grok-wsgi/lib/python2.4/site-packages/zope.app.wsgi-3.4.0-py2.4.egg/zope/app/wsgi/__init__.py", line 124, in config
    appsetup.config(options.site_definition, features=features)
  File "/home/sancho/grok-wsgi/lib/python2.4/site-packages/zope.app.appsetup-3.4.1-py2.4.egg/zope/app/appsetup/appsetup.py", line 111, in config
    context = xmlconfig.file(file, context=context, execute=execute)
  File "/home/sancho/grok-wsgi/lib/python2.4/site-packages/zope.configuration-3.4.0-py2.4.egg/zope/configuration/xmlconfig.py", line 610, in file
    include(context, name, package)
  File "/home/sancho/grok-wsgi/lib/python2.4/site-packages/zope.configuration-3.4.0-py2.4.egg/zope/configuration/xmlconfig.py", line 546, in include
    processxmlfile(f, context)
  File "/home/sancho/grok-wsgi/lib/python2.4/site-packages/zope.configuration-3.4.0-py2.4.egg/zope/configuration/xmlconfig.py", line 378, in processxmlfile
    parser.parse(src)
  File "xml/sax/expatreader.py", line 107, in parse
  File "xml/sax/xmlreader.py", line 123, in parse
  File "xml/sax/expatreader.py", line 207, in feed
  File "xml/sax/expatreader.py", line 348, in end_element_ns
  File "/home/sancho/grok-wsgi/lib/python2.4/site-packages/zope.configuration-3.4.0-py2.4.egg/zope/configuration/xmlconfig.py", line 357, in endElementNS
    self.context.end()
  File "/home/sancho/grok-wsgi/lib/python2.4/site-packages/zope.configuration-3.4.0-py2.4.egg/zope/configuration/config.py", line 542, in end
    self.stack.pop().finish()
  File "/home/sancho/grok-wsgi/lib/python2.4/site-packages/zope.configuration-3.4.0-py2.4.egg/zope/configuration/config.py", line 690, in finish
    actions = self.handler(context, **args)
  File "/home/sancho/grok-wsgi/lib/python2.4/site-packages/zope.configuration-3.4.0-py2.4.egg/zope/configuration/xmlconfig.py", line 546, in include
    processxmlfile(f, context)
  File "/home/sancho/grok-wsgi/lib/python2.4/site-packages/zope.configuration-3.4.0-py2.4.egg/zope/configuration/xmlconfig.py", line 378, in processxmlfile
    parser.parse(src)
  File "xml/sax/expatreader.py", line 107, in parse
  File "xml/sax/xmlreader.py", line 123, in parse
  File "xml/sax/expatreader.py", line 207, in feed
  File "xml/sax/expatreader.py", line 348, in end_element_ns
  File "/home/sancho/grok-wsgi/lib/python2.4/site-packages/zope.configuration-3.4.0-py2.4.egg/zope/configuration/xmlconfig.py", line 357, in endElementNS
    self.context.end()
  File "/home/sancho/grok-wsgi/lib/python2.4/site-packages/zope.configuration-3.4.0-py2.4.egg/zope/configuration/config.py", line 542, in end
    self.stack.pop().finish()
  File "/home/sancho/grok-wsgi/lib/python2.4/site-packages/zope.configuration-3.4.0-py2.4.egg/zope/configuration/config.py", line 690, in finish
    actions = self.handler(context, **args)
  File "/home/sancho/grok-wsgi/lib/python2.4/site-packages/grok-0.11-py2.4.egg/grok/zcml.py", line 48, in grokDirective
    do_grok(package.__name__, _context)
zope.configuration.xmlconfig.ZopeXMLConfigurationError: File "/home/sancho/grok-wsgi/etc/site.zcml", line 60.0-60.68
    ZopeXMLConfigurationError: File "/home/sancho/grok-wsgi/etc/grok-apps/pymenthon/src/pymenthon/configure.zcml", line 4.2-4.27
    AttributeError: 'NoneType' object has no attribute '__name__'

Untitled Python (16-May @ 01:40)

Syntax Highlighted Code

  1. sancho@mulata:~/grok-wsgi$ ./bin/paster serve etc/grok.ini
  2. Traceback (most recent call last):
  3.   File "./bin/paster", line 7, in ?
  4. <