petstore populate.py :  » Web-Frameworks » pyswarm » pyswarm-0.7.1 » PetStore » scripts » Python Open Source

Home
Python Open Source
1.3.1.2 Python
2.Ajax
3.Aspect Oriented
4.Blog
5.Build
6.Business Application
7.Chart Report
8.Content Management Systems
9.Cryptographic
10.Database
11.Development
12.Editor
13.Email
14.ERP
15.Game 2D 3D
16.GIS
17.GUI
18.IDE
19.Installer
20.IRC
21.Issue Tracker
22.Language Interface
23.Log
24.Math
25.Media Sound Audio
26.Mobile
27.Network
28.Parser
29.PDF
30.Project Management
31.RSS
32.Search
33.Security
34.Template Engines
35.Test
36.UML
37.USB Serial
38.Web Frameworks
39.Web Server
40.Web Services
41.Web Unit
42.Wiki
43.Windows
44.XML
Python Open Source » Web Frameworks » pyswarm 
pyswarm » pyswarm 0.7.1 » PetStore » scripts » petstore-populate.py
#!/usr/bin/env python
# -*- coding: utf8 -*-

# $Id: petstore-populate.py 568 2007-05-01 18:02:20Z ahatzis $

#   pyswarm - Model-driven development of Python applications
#   -------------------------------------------------------------------------
#
#   Copyright (C) 2006-2007 Free Software Foundation Europe e.V.
#
#   The main author of pyswarm is Anastasios Hatzis, though contributions
#   are welcome from others. An author list can be found in the file AUTHORS.
#   This program is free software; you can redistribute it and/or modify
#   it under the terms of the GNU General Public License as published by
#   the Free Software Foundation; either version 2 of the License, or
#   (at your option) any later version.
#
#   This program is distributed in the hope that it will be useful,
#   but WITHOUT ANY WARRANTY; without even the implied warranty of
#   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#   GNU General Public License for more details.
#
#   You should have received a copy of the GNU General Public License along
#   with this program; if not, write to the Free Software Foundation, Inc.,
#   51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
#   The licensor of pyswarm is the Free Software Foundation Europe
#   (FSFE), Fiduciary Program, Sumatrastrasse 25, 8006 Zrich,
#   Switzerland, email:ftf@fsfeurope.org.
#
#   -------------------------------------------------------------------------
#   http://pyswarm.sourceforge.net/
#   =========================================================================

"""pyswarm Tutorial For Newbies: Client Module populate.py
Example Client Module for populating the AdM of PetStore


This module is an example how a client can access an pyswarm
application by importing the logic-component AdM, instancing Operation
objects, retrieving the primary object of AdM, retrieving objects
associated with or creating new objects, counting and browsing through
collected objects, and retrieving their attribute values.

Execute this module with-out arguments at least one time, so the
component is populated, before trying out the suggested code
modifications.

Start reading the code comments in the controlling script below, than
the comments in the populate() method.

More information provided in the pyswarm Tutorial For Newbies.

"""
# First we need to import the AdM module.
# The path starts with the system package PetStore, via node package Internet
# and sub-package Shop, logic-component package AdM, and then the
# logic-component module AdM which has the same name as the logic-component
# package.
from petstore.internet.contacts.adm.adm import *


# This method under circum conditions is called by the controlling script below.
def populate():
    """This method creates dummy entity objects: Recipients,
    WebAddresses, PoboxAddresses, and GeoAddresses. All of them owned
    by the primary object.

    """
    oOp = comp.createOp() # create an Operation object
    prime = comp.getPrimaryEntity(oOp)    # retrieve the primary object
    ownedRecipients = prime.getRecipientsOfAddressBook(oOp) # see control script
    addressees = ['linda', 'paul', 'aysha', 'john', 'anne', 'hugo', 'maria']
    for strName in addressees:
        newAddressee = prime.newRecipient(oOp, strName) # create new Recipient
                    # first parameter again the Operation object - not in model!
                    # then the parameter specified in the model.
        ownedRecipients.insert(oOp, newAddressee) # insert the created Recipient
                    # object into the collection of Recipient objects we
                    # retrieved. By doing so they new object is associated
                    # with the same opposite object as the rest of collection,
                    # speak: with the primary object.

                    # creating new WebAddress, PoboxAddress, GeoAddress:
        newWeb = prime.newWebAddress(oOp, 'WebAddress of '+strName, 'http://www.'+strName+'.com')
        newPobox = prime.newPoboxAddress(oOp, 'PoboxAddress of '+strName, 'de', '11122', strName + ' City', '987 654')
        newGeo = prime.newGeoAddress(oOp, 'GeoAddress of '+strName, 'de', '22333', strName + ' City', strName + ' Road', '5 '+strName[0])

                    # creating new Telephone:
        strNumber = ''
        for s in strName:
            strNumber+='-'+s
        newTele = prime.newTelephone(oOp, 'Telephone of '+strName, 'de', '0800', strNumber, True, False)

                    # retrieve an Address collection of primary object
                    # so we can associate the Addresses with the primary object
                    # by calling inser on the new collection.
        booksAddies = prime.getAddressesOfAddressBook(oOp)
        booksAddies.insert(oOp, newWeb)
        booksAddies.insert(oOp, newPobox)
        booksAddies.insert(oOp, newGeo)
        booksAddies.insert(oOp, newTele)

                    # repeat this for the association between the new
                    # Recipient and the new Addresses.
        recipientsAddies = newAddressee.getAddressesOfRecipient(oOp)
        recipientsAddies.insert(oOp, newWeb)
        recipientsAddies.insert(oOp, newPobox)
        recipientsAddies.insert(oOp, newGeo)
        recipientsAddies.insert(oOp, newTele)

    oOp.commit() # commit the Operation, so the write access is executed.
                # This is an ACID transaction, if any single step fails
                # the entire transaction is reverted as if nothing happened.

    oOp.close() # close the Operation
    print 'OK. New Recipients and Addresses created.'

# The following code controls if a primary object exists in AdM. It counts the
# quantity of Recipient and Address objects owned by and associated with the
# primary object.
#
# If no Recipients and Addresses found, the script calls populate() to
# create some of them.
#
# If already objects exist the script doesn't call populate(), instead printing
# some information on the objects found.

comp = Adm() # instanciate new object of the logic-component class

oOp = comp.createOp() # create an Operation object
# Operation objects are used for read/write access in all parts of the
# application. If an Operation is modifying data --write access-- it can be
# considered as a transaction, having a begin and an end. Due to PostgreSQL
# write operations are transaction safe.
# But the Operation object contains additional information, making them
# available in all modules envolved during an Operation.

prime = comp.getPrimaryEntity(oOp) # the component offers a method to retrieve
                                  # primary object
                                  # The Operation object has to be provided
                                  # as parameter as in almost all methods.

if prime:     # if a primary object has been returned...
    print 'Primary object found. Entity ID of primary object:',prime.strEID(oOp)
    addresses = prime.getAddressesOfAddressBook(oOp)    # for each association-
                # role a getter method has been generated. The method name is
                # a conjunction of 'get' and the name of the association-role
                # where the object(s) to retrieve reside. Since we apply the
                # method on primary object which is an AddressBook and we want
                # to get the associated Address objects, we use the
                # association-role AddressesOfAddressBook.
                # The oOp parameter has to be provided.
                # What is returned is a collection of associated objects,
                # more concrete a collector. Collections are not in any
                # case result of an association, but collectors are.
                # You can call special methods on collections,
                # e.g. for counting:
    lCountA = addresses.count(oOp, None, None)    # count() counts the objects
                # found in the collection. The quantity returned is a Long type.
                # count() offers you two parameters to filter the collection,
                # effecting the quantity that is count. Here both parameters
                # are not set.
                # The first after oOp is the classifier. Provide a string with
                # the name of a sub-class of the opposite role's class to
                # restrict which objects should be count. Since Address has
                # a plenty of sub-classes, you can use one of them to classify
                # the collection you want to count, e.g. 'Telephone' to get
                # all associated Telephone objects counted, or 'ZipAddress'
                # for all ZipAddress objects, which can be either GeoAddress
                # or PoboxAddress objects. Uncomment the next line for test:
    print 'ZipAddresses found:', addresses.count(oOp, 'ZipAddress', None)
    pageA = addresses.getPage(oOp)
    for addy in pageA:
        print addy.printLetter(oOp, True), '\n'
                # The last parameter is used for criteria. Provide a string
                # with criteria filter as you probably know from SQL WHERE
                # clauses. Thus you can filter all objects with a specific
                # attribute value. If classifying ZipAddresses it could be
                # counting all objects with the zipCode '11122'. Please note
                # that we need to unmask ' and " characters with a \.
    print 'ZipAddresses with zipCode=11122 found:', addresses.count(oOp, 'ZipAddress', '\"zipCode\"=\'11122\'')

                # You can also use AND or OR combinations, also in conjunction
                # with priorizing brackets, e.g.
                # "locationName"='Munich' AND ("zipCode"='11122' OR "zipCode"='222333')

                # You can also use UPPER(value) or LOWER(value) to compare
                # values case-insensitive, e.g. LOWER("name")=LOWER('LinDA')

                # Another example worth to try out are LIKE comparisons, e.g.
                # "subject" LIKE '%a%'
                # which applies to all entries containing the lower character 'a'
    print 'Addresses with subject containing letter "a" found:', addresses.count(oOp, None, '\"subject\" LIKE \'%a%\'')

    addressees = prime.getRecipientsOfAddressBook(oOp) # according to the
                # example with retrieving associated Address objects, but
                # here Recipient objects.

    lCountR = addressees.count(oOp)    # counting the collection of objects.
                # Note that you can leave away the parameters if you don't
                # need. But if you leave away classifier but want to use
                # the criteria, you need to name the parameter. Try this:
    print 'Recipients with name ending with letter "a" found:', addressees.count(oOp, strCriteria='\"name\" LIKE \'%a\'')

    print lCountR, 'Recipients found, owning a total of ', lCountA, ' Addresses.'
    if lCountR == 0 and lCountA == 0: # at first call of this module,
                # no objects will be counted. Thus call populate()
        populate()
    else:
        # print some information on the found recipients and their addresses
        print 'Already created Recipients and Addresses. So modifying the subject of all address objects.\n\n'

        pageR = addressees.getPage(oOp) # retrieve the collection of objects
                # pagewise. The first two parameters after oOp, here not
                # used, are the same as in count(). strClassifier for
                # classifying which type of objects you want in the page,
                # and strCriteria to filter based on attribute values.
                # The third parameter is strOrdering, which allows you
                # to get the objects ordered, e.g. sorted descending by a
                # given attribute, e.g. the entityID (=EID).

#        pageR = addressees.getPage(oOp, strOrdering='\"entityID\" DESC')
#        pageR = addressees.getPage(oOp, strOrdering='\"name\" ASC')

                # The fourth parameter is nPageSize, for the number of
                # objects to be retrieved per page, e.g. 5 - if set to None
                # or not provided it will retrieve a page with all objects
                # in collection to the page
                # Finally the fifth parameter nPage is used to specify
                # the page-number of a page with objects you want to retrieve
                # from collection. Only makes sense as far as nPageSize is not
                # None and nPageSize is less than the count() number if the
                # same filter is applied in getPage() and count().

        for addressee in pageR:
            print ''
            print 'Addresses of:', addressee.getName(oOp), '( EID:', addressee.strEID(oOp), ', VID:', addressee.strVID(oOp), ', last record:', addressee.strRecordedOn(oOp), ')'

            addies = addressee.getAddressesOfRecipient(oOp)
            pageA = addies.getPage(oOp)    # By classifying the retrieved page
                        # to a sub-class of Address it would be possible to
                        # call and print more sub-class specific attributes
                        # Classify to 'Telephone' and you could print
                        # addy.getPrefix(oOp), str(addy.isVoice(oOp)), ...

            for addy in pageA:
                addy.setSubject(oOp, addy.getSubject(oOp)+'x*')
                print '    Subject:', addy.getSubject(oOp), ', class:', addy.classEntity(oOp)
                print '        EID:', addy.strEID(oOp), ', VID:', addy.strVID(oOp), ', last record:', addy.strRecordedOn(oOp)
        oOp.commit() # the entire transaction is written to the database (ACID applies)
                     # which means that all write accesses to objects via this operation
                     # object are considered as a single database transaction.
        oOp.close()  # close the Operation object (no further use)
else:
    # no primary object found.
    oOp.close() # close the Operation object
    print 'No primary object found. Please execute setup.py in AdM-DB directory for creating one.'
www.java2java.com | Contact Us
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.