[Zope] SOS - outer product, or external method needed with classes ! Please help me ! 3

kepes.krisztian kepes.krisztian at peto.hu
Mon Sep 20 10:28:58 EDT 2004


Hi !

I trying, and trying.
I see that fds=context.uft.createformclass('fields') is working, because 
  the createformclass is the proc. of the uft extension module, or 
member of the product.

But when I try to access any part of the fds(FieldDefList) object, a 
member, a method, anything, Zope is say that it is unauthorized.

So I think, that is caused by Zope's security system, what not allow to 
I access a not known module, or classes/methods.

But I don't know, how to enable the access from program.

If it is not successfull, I MUST return to my first version: that is 
working with dicts, and same thing, and store the datas in common 
variables. It is not too elegant, and many errors create by wrong writed 
dictionray keys, but I don't want to fight with zope.

Please help me, big Zope Masters: how to access an outer class from a 
product, or external method - with avoiding the Zope's security error, 
when I try to access this outer instance's members ?

Thanx for help:
  KK

 >>>
The error message is:
You are not allowed to access 'Add' in this context.

When I try to change add to additem, it is makes same error.
I try to add proxy role the caller python script, and I add all of the
rights, but the error isn't changed.

I remove all of the sys,time,wx.DateTime imports and usage from this
routine, but the error is unchangeable !

Why ?

Thanx for help:
   KK

Ps:
Please send the answers to private mail too, because I'm in digest
mode. Thx.





  >>>>
Hi !

I start the full development of my idea, a special form tool.
It is uses classes, not python dicts, so I cannot write the code in
python scripts.

In native python everything is working good. The FormClasses.Grid is
generate a grid with datas well.

So I try to do it in Zope.

First I trying with a Product creation.
The product is nothing to do else, only create an interface with two
method, and these methods are creating special objects - grid, and
fielddefs.

The tester program is that (py script):

fds=context.uft.createformclass('fields')
# 1
fd=fds.Add()
fd.Name='ID'
fd.Type='int'
# 2

When I put a "return 1" to #1, it is showed.
But when I move that to #2, the zope is say "Unauthorized !", and it is
show an pwd dialog.

I don't understand, why do it, and why do it in FieldDefs.Add() ?

Ok, I think that I avoid product usage, I use external method.
I put everything to uftext.py, and I create an external method object.

fds=context.extcreateformclass('fields')
# 1
fd=fds.Add()
fd.Name='ID'
fd.Type='int'
# 2

But the result is same.
The fielddefs.Add is moving into unauth-ed area...

Why ?

Please anyone help me in this - to avoid, or destroy the problem...

Thanx:
   KK





-------------- next part --------------
##############################################################################
#
# Zope Public License (ZPL) Version 1.0
# -------------------------------------
#
# Copyright (c) Digital Creations.  All rights reserved.
#
# This license has been certified as Open Source(tm).
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# 1. Redistributions in source code must retain the above copyright
#    notice, this list of conditions, and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright
#    notice, this list of conditions, and the following disclaimer in
#    the documentation and/or other materials provided with the
#    distribution.
#
# 3. Digital Creations requests that attribution be given to Zope
#    in any manner possible. Zope includes a "Powered by Zope"
#    button that is installed by default. While it is not a license
#    violation to remove this button, it is requested that the
#    attribution remain. A significant investment has been put
#    into Zope, and this effort will continue if the Zope community
#    continues to grow. This is one way to assure that growth.
#
# 4. All advertising materials and documentation mentioning
#    features derived from or use of this software must display
#    the following acknowledgement:
#
#      "This product includes software developed by Digital Creations
#      for use in the Z Object Publishing Environment
#      (http://www.zope.org/)."
#
#    In the event that the product being advertised includes an
#    intact Zope distribution (with copyright and license included)
#    then this clause is waived.
#
# 5. Names associated with Zope or Digital Creations must not be used to
#    endorse or promote products derived from this software without
#    prior written permission from Digital Creations.
#
# 6. Modified redistributions of any form whatsoever must retain
#    the following acknowledgment:
#
#      "This product includes software developed by Digital Creations
#      for use in the Z Object Publishing Environment
#      (http://www.zope.org/)."
#
#    Intact (re-)distributions of any official Zope release do not
#    require an external acknowledgement.
#
# 7. Modifications are encouraged but must be packaged separately as
#    patches to official Zope releases.  Distributions that do not
#    clearly separate the patches from the original work must be clearly
#    labeled as unofficial distributions.  Modifications which do not
#    carry the name Zope may be packaged in any form, as long as they
#    conform to all of the clauses above.
#
#
# Disclaimer
#
#   THIS SOFTWARE IS PROVIDED BY DIGITAL CREATIONS ``AS IS'' AND ANY
#   EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
#   IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
#   PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL DIGITAL CREATIONS OR ITS
#   CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
#   SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
#   LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
#   USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
#   ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
#   OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
#   OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
#   SUCH DAMAGE.
#
#
# This software consists of contributions made by Digital Creations and
# many individuals on behalf of Digital Creations.  Specific
# attributions are listed in the accompanying credits file.
#
##############################################################################
__doc__ = """"Update Form Tool Product

$Id: __init__.py,v 0.7 2003/04/25 12:43:18 mw Exp $
"""
__version__ = '$Revision: 0.7 $'


from OFS import SimpleItem
import Globals
from Globals import Persistent, DTMLFile, InitializeClass, HTMLFile

import FormClasses

import sys,time
import traceback

manage_addUpdFormToolForm=HTMLFile('Add',globals())

class UpdFormTool(SimpleItem.SimpleItem):
    "UpdFormTool object"
    params={}
    meta_type = 'Update Form Tool Object'
    #dateformat='';timeformat='';timestampformat=""
    #database_type=0;

    #index_html=DTMLFile('Edit', globals())
    index_html=DTMLFile('index', globals())
    manage_options = ({'label': 'Content', 'action': "index_html"},)

    def manage_edit(self, title, dateformat,timeformat,timestampformat,database_type,REQUEST=None):
        """ Change the parameters of UpdateForm Tool Object"""
        self.title=title
        #self.Setdatabase_type(int(database_type))
        #self.SetDateTimeFormats(dateformat,timeformat,timestampformat)
        #self.edit(title, connection_string, check)
        if REQUEST is not None: REQUEST.RESPONSE.redirect('manage_main')

    def __init__(self, id,title):
        "initialize a new instance of UpdFormTool"
        self.id=id
        self.title=title

    def CreateGrid(self):
        return FormClasses.Grid()
    def CreateCol(self):
        return FormClasses.GridColumn()
    def CreateFieldDefs(self):
        return FormClasses.FieldDefList()
    def CreateField(self):
        return FormClasses.FieldDef()


    #manage_properties=DTMLFile('Edit2', globals())


#manage_properties = HTMLFile('Edit',globals())

# Administrative pages

def manage_addUpdFormTool(self, id, title,RESPONSE=None):
    "Add a UpdFormTool to a folder."
    self._setObject(id, UpdFormTool(id,title))
    #self.edit(title)
    if RESPONSE<>None:
       RESPONSE.redirect('manage_main')
    #if REQUEST is not None:
    #   return self.manage_main(self, REQUEST)





-------------- next part --------------
import UpdFormTool

def initialize(context):
    """Initialize the UpdFormTool product.
    This makes the object apear in the product list"""
    context.registerClass(
        UpdFormTool.UpdFormTool,
        constructors = (UpdFormTool.manage_addUpdFormToolForm,UpdFormTool.manage_addUpdFormTool),
        icon='icon.gif'
    )


-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.zope.org/pipermail/zope/attachments/20040920/ea4e6513/Add.htm
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.zope.org/pipermail/zope/attachments/20040920/ea4e6513/Edit.htm
-------------- next part --------------
import sys,mx.DateTime

print mx.DateTime.DateTimeDelta(0)
s=mx.DateTime.localtime()
print s.hour
#sys.exit()


from FormClasses import *

fds=FieldDefList()
fd=fds.Add()
fd.Name='ID'
fd.Type='int'

fd=fds.Add()
fd.Name='NAME'

fd=fds.Add()
fd.Name='VAL'
fd.Type='float'

fd=fds.Add()
fd.Name='D'
fd.Type='date'

fd=fds.Add()
fd.Name='SECNAME'
fd.Origin='NAME'
fd.Table='SECOND'
# LU
fd=fds.Add()
fd.Name='LEADER_ID'
fd.Origin=''
fd.Table=''
fd.SetSQLLookup('LEADERS','ID','NAME')

g=Grid()
g.SetFieldDefs(fds)

print g.GetFieldDefs()

#g.SetTableNames(['first,second'])
#g.TableNames[0]=['first,second']
#print g.TableNames[0]
g.SetTableNames(['first','second'])

print g.GetTableNames()

g.SetSQLWheres('first.SECID=second.ID')
g.SetSQLOrders('order by first.ID')

print g.GetFieldDefs()

#print g.ParseDateTimeString('99-01-01')

#sys.exit()

s=g.BuildSQL()
print s

cols=g.Columns

c=cols.Add()
print c
c.Names='ID'

c=cols.Add()
c.Names='NAME'

c=cols.Add()
c.Names='VAL'

c=cols.Add()
c.Names='D'

rows=[]
row={'ID':1000,'NAME':'a','VAL':112.1,'D':'99.03.02'}
rows.append(row)
row={'ID':200000,'NAME':'b','VAL':10000.99,'D':'04.12.01'}
rows.append(row)
row={'ID':3000000,'NAME':'c','VAL':39,'D':'2004-03-22'}
rows.append(row)
g.DataRows=rows

s=g.GenerateGrid()
print s

#print g.FormatInt(10000)
#print g.FormatFloat(1000.02)

'''
class A(object):
      __slots__=('x','a','__v')
      def __init__(self):
          self.__v=0
      def g(self):
          print "g"
          return self.__v
      def s(self,v):
          self.__v=v
          print "s"
      #GS=property(g,s)

a=A()
print a.g()
a.s(1)
print a.g()

#print a.GS
a.GS=2
print a.GS
print a.g()
'''





-------------- next part --------------
import sys,mx.DateTime,time

def ParamToStrList(value,errortext,lowerit=False):
    if type(value)==type(''):
       value=[value]
    elif type(value)==type([]):
       value=value[:]
    else:
       raise Exception,errortext
    tn=[]
    for s in value:
        s=str(s)
        if lowerit: s=s.lower()
        tn.append(s)
    return tn

def ParseDateTimeString(dtstr):
    l=[]
    sval=[""]
    l.append(sval)
    idx=0;ldtstr=len(dtstr)
    instr=True
    if ldtstr>0:
       while idx<ldtstr:
          achar=dtstr[idx]
          ins=(achar>='0' and achar<='9')
          if ins<>instr:
             if (sval[0]<>""):
                sval=[""]
                l.append(sval)
             instr=ins
          else:
             if instr:
                sval[0]=sval[0]+achar
          idx+=1
       ls=[]
       for ll in l:
           s=ll[0]
           if s<>'': ls.append(s)
       if len(ls)==0: return None
       # Dátum és idõ
       for i in range(len(ls),6):
           ls.append(None)
       for i in range(3):
           s=ls[i]
           if s==None: s=1
           else: s =int(ls[i])
           ls[i]=s
       for i in range(3,6):
           s=ls[i]
           if s==None: s=0
           else: s =int(ls[i])
           ls[i]=s
       #print ls
       y=ls[0]
       if (y<100):
          if (y<40): y=y+2000
          else: y=y+1900
       ls[0]=y
       return mx.DateTime.mktime((ls[0],ls[1],ls[2],ls[3],ls[4],ls[5],None,None,None))
    else:
       return None
    

class BaseList(object):
      def __init__(self):
          self.__List=[]
          self.__slots__=[]
      def inner_CreateItem(self,Params):
          return None
      def inner_AddItem(self,Params):
          item=self.inner_CreateItem(Params)
          self.__List.append(item)
          return item
      def Add(self):
          return self.inner_AddItem(None)
      def GetCount(self):
          return len(self.__List)
      Count=property(GetCount)
      def CheckIndex(self,index):
          if index<0 or index>=self.Count:
             raise Exception,'Invalid index (%d) !'%(index)
      def Delete(self,index):
          self.CheckIndex(index)
          del (self.__List[index])
      def Get(self,index):
          self.CheckIndex(index)
          return self.__List[index]
      def __getitem__(self,index):
          return self.Get(int(index))
      def __setitem__(self,index,value):
          raise Exception,'Item is not writeable !'
      def IndexOf(self,param):
          return -1
      def Clear(self):
          self.__List=[]

AllowedTypes=('int','str','bool','float','date','time','datetime')



class FieldDef(object):
      def __init__(self):
          self.__Name=''
          self.__Caption=''
          self.__Origin=''
          self.__Table=''
          self.__Type='str'
          self.__Lookups={}
          self.__Format=''
          self.__Required=True
          self.__DefValue=None
      def GetName(self):
          return self.__Name
      def SetName(self,value):
          self.__Name=value
      Name=property(GetName,SetName)
      def GetCaption(self):
          return self.__Caption
      def SetCaption(self,value):
          self.__Caption=value
      Caption=property(GetCaption,SetCaption)
      def GetOrigin(self):
          return self.__Origin
      def SetOrigin(self,value):
          self.__Origin=value
      Origin=property(GetOrigin,SetOrigin)
      def GetTable(self):
          return self.__Table
      def SetTable(self,value):
          self.__Table=value
      Table=property(GetTable,SetTable)
      def GetFormat(self):
          return self.__Format
      def SetFormat(self,value):
          self.__Format=value
      Format=property(GetFormat,SetFormat)
      def GetRequired(self):
          return self.__Required
      def SetRequired(self,value):
          self.__Required=value
      Required=property(GetRequired,SetRequired)
      def GetDefValue(self):
          return self.__DefValue
      def SetDefValue(self,value):
          self.__DefValue=value
      DefValue=property(GetDefValue,SetDefValue)
      def GetType(self):
          return self.__Type
      def SetType(self,ntype):
          ntype=str(ntype).lower()
          if not (ntype in AllowedTypes):
             raise Exception,'Invalid field type "%s"'%ntype
          self.__Type=ntype
      Type=property(GetType,SetType)
      def SetStaticLookup(self,LookupData):
          ld=self.__Lookups={}
          ld['static']=1
          ld['data']=LookupData
      def SetSQLLookup(self,tablename,idfield,namefield,sqlwhere=''):
          ld=self.__Lookups={}
          ld['static']=0
          ld['table']=tablename
          ld['id']=idfield
          ld['name']=namefield
          ld['where']=sqlwhere
      def GetIsLookup(self):
          if len(self.__Lookups.keys())>0: return 1
          else: return 0
      IsLookup=property(GetIsLookup)
      def GetIsStaticLookup(self):
          if self.GetIsLookup():
             ld=self.__Lookups
             return ld['static']
          else:
             raise Exception,'Field is not lookup !'
      IsStaticLookup=property(GetIsStaticLookup)
      def GetLookupData(self):
          if self.GetIsStaticLookup():
             ld=self.__Lookups
             return ld['data']
          else:
             raise Exception,'Lookup data is missing !'
      LookupData=property(GetLookupData)
      def GetLookupSQLParams(self):
          if self.GetIsLookup():
             ld=self.__Lookups
             lp=[ld['table'],ld['id'],ld['name'],ld['where']]
             return lp
          else:
             raise Exception,'Field is not lookup !'
      LookupSQLParams=property(GetLookupSQLParams)
      def FormatInt(self,Value,Fmt=''):
          v=long(Value)
          s=str(v)
          l=[]
          ls=len(s);ls1=ls-1
          for idx in range(ls):
              if (idx%3==0) and (idx<>0):# and (idx<>ls-1):
                 l.insert(0,'.')
              l.insert(0,s[ls1-idx])
          if l[0]=='.': del(l[0])
          v="".join(l)
          return v

      def FormatFloat(self,Value,Fmt=''):
          '''
          if Fmt=='':
             return str(Value)
          # Format is two integer - (2.2 is 02.

          '''
          v=float(Value)
          s='%1.2f'%(v)
          ct='.,;-'
          for c in ct:
              f=s.find(c)
              if f<>-1: break
          print s
          if f==-1: raise Exception,'Invalid separator !'
          ssep=s[f]
          sint=s[:f]
          sfrac=s[f+1:]
          sint=self.FormatInt(sint)
          ssep=','
          result='%s%s%s'%(sint,ssep,sfrac)
          return result


      def FormatDateTime(self,Value,Style,ZDTClass=None,Fmt=''):
          v=str(Value)
          dtc=ZDTClass
          if dtc==None:
             dtobj=ParseDateTimeString(Value)
             mye=int(dtobj.year)
             mmo=int(dtobj.month)
             mda=int(dtobj.day)
             mho=int(dtobj.hour)
             mmi=int(dtobj.minute)
             mse=int(dtobj.second)
             if Style=='date':
                s="%04d.%02d.%02d"%(mye,mmo,mda)
             elif Style=='time':
                s="%02d:%02d:%02d"%(mho,mmi,mse)
             elif Style in ['datetime','timestamp']:
                s="%04d.%02d.%02d %02d:%02d:%02d"%(mye,mmo,mda,mho,mmi,mse)
             return s
          else:
             dtobj=self.ZopeDateTimeClass(Value)
             mye=dtobj.year()
             mmo=dtobj.mm()
             mda=dtobj.day()
             mho=dtobj.hour()
             mmi=dtobj.minute()
             mse=dtobj.second()
             if Style=='date':
                s="%04d.%s.%02d"%(mye,mmo,mda)
             elif Style=='time':
                s="%02d:%02d:%02d"%(mho,mmi,mse)
             elif Style in ['datetime','timestamp']:
                s="%04d.%s.%02d %02d:%02d:%02d"%(mye,mmo,mda,mho,mmi,mse)
             else:
                raise Exception,'Invalid DateTime style !'
             return s

      def FormatField(self,aValue,ZDTClass=None):
          ft=self.Type
          fmt=self.Format
          v=aValue
          if ft=='int':
             v=long(v)
             # Formatting
             v=self.FormatInt(v)
          elif ft=='str':
             pass
          elif ft=='bool':
             v=str(v).lower()
             if v in ['0','n','false']: v=False
             elif v in ['1','y','true']: v=True
             else: v=False
             # Formatting
          elif ft=='float':
             v=float(v)
             # Formatting
             v=self.FormatFloat(v)
          elif ft=='date':
             # Formatting
             v=self.FormatDateTime(v,ft,ZDTClass)
          elif ft=='time':
             # Formatting
             v=self.FormatDateTime(v,ft)
          elif ft=='datetime':
             # Formatting
             v=self.FormatDateTime(v,ft)
          v=str(v)
          return v



class FieldDefList(BaseList):
      def inner_CreateItem(self,Params):
          return FieldDef()
      def IndexOf(self,FieldName):
          for i in range(self.Count):
              if self.Get(i).Name.lower()==FieldName.lower():
                 return i
          return -1
      def FieldByName(self,FieldName):
          p=self.IndexOf(FieldName)
          if p==-1: raise Exception,'Invalid Field Name "%s" !'%FieldName
          return self.Get(p)



class GridColumn(object):
      def __init__(self):
          self.__Names=['']
          self.__Width=-1
          self.__Caption=''
          self.__Color=''
          self.__Style=''
      def GetWidth(self):
          return self.__Width
      def SetWidth(self,value):
          self.__Width=int(value)
      Width=property(GetWidth,SetWidth)
      def GetCaption(self):
          return self.__Caption
      def SetCaption(self,value):
          self.__Caption=str(value)
      Caption=property(GetCaption,SetCaption)
      def GetColor(self):
          return self.__Color
      def SetColor(self,value):
          self.__Color=str(value)
      Color=property(GetColor,SetColor)
      def GetStyle(self):
          return self.__Style
      def SetStyle(self,value):
          self.__Style=str(value)
      Style=property(GetStyle,SetStyle)
      def GetNames(self):
          return self.__Names[:]
      def SetNames(self,names):
          self.__Names=ParamToStrList(names,'Invalid field names !')
      Names=property(GetNames,SetNames)

class GridColumnList(BaseList):
      def inner_CreateItem(self,Params):
          return GridColumn()


class Grid(object):
      def __init__(self):
          self.__Cols=GridColumnList()
          self.__Width=-1
          self.__TableNames=[]
          self.__SQL=''
          self.__Selectable=False
          self.__Editable=False
          self.__HeadClassName=''
          self.__CellClassName=''
          self.__TableStyle=''
          self.__ZSQLMethod=None
          self.__FieldDefs=None
          self.__SQLWheres=[]
          self.__SQLOrders=[]
          self.__DataRows=[]
          self.__ItemID=None
          self.__KeyField='ID'
          self.__ZopeDateTimeClass=None
          self.__SelectParams=None
          #self.__slots__=[]

      def SetSelectParams(self,ButtonName,ButtonCaption):
          self.__SelectParams={'buttonname':ButtonName,'buttoncaption':ButtonCaption}

      def GetColumns(self):
          return self.__Cols
      Columns=property(GetColumns)
      def GetWidth(self):
          return self.__Width
      def SetWidth(self,value):
          self.__Width=int(value)
      Width=property(GetWidth,SetWidth)
      def GetSelectable(self):
          return self.__Selectable
      def SetSelectable(self,value):
          self.__Selectable=boolean(value)
      Selectable=property(GetSelectable,SetSelectable)
      def GetEditable(self):
          return self.__Editable
      def SetEditable(self,value):
          self.__Editable=boolean(value)
      Editable=property(GetEditable,SetEditable)
      def GetHeadClassName(self):
          return self.__HeadClassName
      def SetHeadClassName(self,value):
          self.__HeadClassName=str(value)
      HeadClassName=property(GetHeadClassName,SetHeadClassName)
      def GetCellClassName(self):
          return self.__CellClassName
      def SetCellClassName(self,value):
          self.__CellClassName=str(value)
      CellClassName=property(GetCellClassName,SetCellClassName)
      def GetTableStyle(self):
          return self.__TableStyle
      def SetTableStyle(self,value):
          self.__TableStyle=int(value)
      TableStyle=property(GetTableStyle,SetTableStyle)
      '''
      def GetWidth(self):
          return self.__Width
      def SetWidth(self,value):
          self.__Width=int(value)
      Width=property(GetWidth,SetWidth)
      '''
      def GetZSQLMethod(self):
          return self.__ZSQLMethod
      def SetZSQLMethod(self,value):
          self.__ZSQLMethod=value
      ZSQLMethod=property(GetZSQLMethod,SetZSQLMethod)
      def GetTableNames(self):
          return self.__TableNames[:]
      def SetTableNames(self,value):
          self.__TableNames=ParamToStrList(value,'Invalid tablenames !',True)
          print 'a',self.__TableNames
      TableNames=property(GetTableNames,SetTableNames)
      def GetFieldDefs(self):
          return self.__FieldDefs
      def SetFieldDefs(self,value):
          # xxx
          self.__FieldDefs=value
      FieldDefs=property(GetFieldDefs,SetFieldDefs)
      def GetSQLWheres(self):
          return self.__SQLWheres
      def SetSQLWheres(self,value):
          self.__SQLWheres=ParamToStrList(value,'Invalid where conditions !')
      SQLWheres=property(GetSQLWheres,SetSQLWheres)
      def GetSQLOrders(self):
          return self.__SQLOrders
      def SetSQLOrders(self,value):
          self.__SQLOrders=ParamToStrList(value,'Invalid sql orders !')
      SQLOrders=property(GetSQLOrders,SetSQLOrders)
      def GetDataRows(self):
          return self.__DataRows
      def SetDataRows(self,value):
          self.__DataRows=value
      DataRows=property(GetDataRows,SetDataRows)
      def GetItemID(self):
          return self.__ItemID
      def SetItemID(self,value):
          self.__ItemID=value
      ItemID=property(GetItemID,SetItemID)
      def GetKeyField(self):
          return self.__KeyField
      def SetKeyField(self,value):
          self.__KeyField=value
      KeyField=property(GetKeyField,SetKeyField)
      def GetZopeDateTimeClass(self):
          return self.__ZopeDateTimeClass
      def SetZopeDateTimeClass(self,value):
          self.__ZopeDateTimeClass=value
      ZopeDateTimeClass=property(GetZopeDateTimeClass,SetZopeDateTimeClass)
      # Procedures
      def BuildSQL(self):
          fdefs=self.GetFieldDefs()
          #print "FD",fdefs
          tnames=self.GetTableNames()
          #print "TN",tnames
          if (fdefs==None) or (fdefs.Count==0):
             raise Exception,'Invalid or empty grid fielddefs !'
          if len(tnames)==0:
             raise Exception,'Main table name missing !'
          sql=['select']
          fields=[]
          wheres=[]
          tables=tnames[:]
          #print "FD2",fdefs
          for FieldIdx in range(fdefs.Count):
              Field=fdefs.Get(FieldIdx)
              isnormal=True
              org=Field.Origin
              nam=Field.Name
              table=Field.Table.lower()
              if table=='':
                 table=self.GetTableNames()[0]
              else:
                 if not (table in self.GetTableNames()):
                    raise Exception, \
                     'Tablename "%s" is missing from tables !'%table
              if Field.GetIsLookup():
                 if Field.GetIsStaticLookup():
                    pass
                 else:
                    isnormal=False
                    wlookup='(%s.%s=%s.%s)'
                    ltable,lid,lname,lwhere=Field.GetLookupSQLParams()
                    wlookup=wlookup%(table,nam,ltable,lid)
                    wheres.append(wlookup)
                    fullname='%s.%s'%(ltable,lname)
                    fields.append(fullname)
              if isnormal:
                 table=table+'.'
                 fmt='%s%s%s'
                 if org<>'':
                    org=org+' '
                 fullname=(fmt%(table,org,nam)).strip()
                 fields.append(fullname)
          fields=",\n".join(fields)
          tables=",\n".join(tables)
          for s in self.GetSQLWheres():
              wheres.append('(%s)'%s)
          wheres=" and\n".join(wheres)
          orders=",\n".join(self.GetSQLOrders())
          sql.append(fields)
          sql.append('from')
          sql.append(tables)
          if wheres<>'':
             sql.append('where')
             sql.append(wheres)
          sql.append(orders)
          self.__SQL=sql
          return sql

      def LocateID(self,Value,IDField=None):
          fcnt=0
          if IDField==None: IDField=self.KeyField
          for row in self.__DataRows:
              if str(row[IDField])==str(Value):
                 return fcnt
              fcnt+=1
          return -1

      def GenerateGrid(self,NeedFormTag=True):
          res=[]
          if NeedFormTag:
             res+=['<form method="post" action="">']
          s='';w=self.GetWidth()
          if w>0: s=str(w)
          res+=['<table border="1" %s %s>'%(s,self.GetTableStyle())]
          # Get the columns
          realcols=[]
          captions=[]
          widths=[]
          if self.Columns.Count==0:
             for i in range(self.FieldDefs.Count):
                 fd=self.FieldDefs[i]
                 realcols.append([fd.name])
                 captions.append([fs.caption])
                 widths.append(Columns.Width)
          else:
             for i in range(self.Columns.Count):
                 col=self.Columns[i]
                 names=col.GetNames()
                 print "names",names
                 realcols.append(names)
                 cap=col.Caption
                 caps=[cap]
                 if cap=='':
                    l=[]
                    caps=[]
                    for s in names:
                        p=self.FieldDefs.IndexOf(s)
                        if p==-1:
                           raise Exception,'Invalid field name ("%s") !'%s
                        fd=self.FieldDefs[p]
                        if fd.Caption<>'': cap=fd.Caption
                        else: cap=fd.Name
                        caps.append(cap)
                 captions.append(caps)
                 widths.append(-1)
          # Build the header
          res+=['<tr>']
          for idx in range(len(realcols)):
              cols=realcols[idx]
              caption=captions[idx]
              w=widths[idx]
              if w<1: w=""
              else: w=str(w)
              res+=['<td class="fcgrid_headtd" width="%s">'%(w)]
              res+=[str(caption)]
              res+=['</td>']
          res+=['</tr>']
          # Ok, we must build the datas
          rows=self.DataRows
          if (self.ItemID==None):
             if len(rows)>0:
                self.ItemID=(rows[0][self.KeyField])
          if self.LocateID(self.ItemID)==-1:
             self.ItemID=(rows[0][self.KeyField])
          for row in rows:
              res+=['<tr>']
              # We must get the itemid
              itemid=row[self.KeyField]
              # if table is selectable then we must create a routine for it
              if self.Selectable:
                 res+=['<td class="fcgrid_itemtd">']
                 radio='<input class="fcgrid_radio" type="radio" '+\
                       'name="fcgrid_selector" id="fcgrid_selector"'+\
                       'value="%d">'%itemid
                 res+=[radio]
                 res+=['</td>']
              # if table is editable, we must create intf for it
              if self.Editable:
                 res+=['<td class="fcgrid_itemtd">']
                 hrefs=[]
                 bhref='<a border="0" href="%s">%s</a>'
                 hrefs.append((bhref%(self.InsertURL,self.InsertName))%(itemid))
                 hrefs.append((bhref%(self.ModifyURL,self.ModifyName))%(itemid))
                 hrefs.append((bhref%(self.DeleteURL,self.DeleteName))%(itemid))
                 hrefs.append('')
                 hrefs="<br>\n".join(hrefs)
                 res+=[hrefs]
                 res+=['</td>']
              # Data columns
              for idx in range(len(realcols)):
                  cols=realcols[idx]
                  # Three mode
                  lc=len(cols)
                  if lc in [0,1]:
                     if lc==0:
                        data=''
                     else:
                        fn=cols[0]
                        fd=self.FieldDefs.FieldByName(fn)
                        data=fd.FormatField(row[fn],self.ZopeDateTimeClass)
                     res+=['<td class="fcgrid_itemtd">']
                     res+=[str(data)]
                     res+=['</td>']
                  else:
                     res+=['<td class="fcgrid_itemtd">']
                     res+=['<table width="100%" height="100%">']
                     for fn in cols:
                         fd=self.FieldDefs.FieldByName(fn)
                         res+=['<tr>']
                         res+=['<td class="fcgrid_itemtd">']
                         res+=[str(fd.Name)]
                         res+=['</td>']
                         res+=['<td class="fcgrid_itemtd">']
                         data=fd.FormatField(row[fn],self.ZopeDateTimeClass)
                         res+=[str(data)]
                         res+=['</td>']
                         res+=['</tr>']
                     res+=['</table>']
                     res+=['</td>']
              res+=['</tr>']
          if self.Selectable:
             pars=self.__SelectParams
             if pars<>None:
                bn=pars['buttonname']
                bv=pars['buttoncaption']
                res+=['<tr><td class="fcgrid_itemtd" colspan="1000">']
                res+=['<input type="submit" name="%s" id="%s" value="%s">'%(bn,bn,bv)]
                res+=['</td></tr>']
          if NeedFormTag:
             res+=['</form>']
          return "\n".join(res)




-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.zope.org/pipermail/zope/attachments/20040920/ea4e6513/index.htm
-------------- next part --------------




More information about the Zope mailing list