[Zope-DB] How lunch SQL request from python script ?

Charlie Clark charlie at egenix.com
Fri Jan 19 07:31:59 EST 2007


Am 19.01.2007, 12:22 Uhr, schrieb CERETTO Thierry <t.ceretto at chu-nancy.fr>:

Thierry,

keep replies on the mailing list so that others can learn from them.

> Hi,
> Thanks Charlie, your method works well (after some hours of labor...)
> My code below (not finalized, but, for Zope/Python/MySsql newbies, can  
> be useful for to start...)

Yes, except that it's not really very Pythonic and we're the number of  
script kiddies out there picking up the language we need to try and  
encourage the good stuff.

> from Products.PythonScripts.standard import html_quote
> from string import split

No! strings have got the split() method (since Python 1.6)

> request = container.REQUEST
> RESPONSE =  request.RESPONSE
> # Get argument(s)
> criteres = mot_MAJ
> # Test

Assuming the criteria are coming from some web form there should be no  
need to split a string, they should already be available as a list.

> #for cc in criteres.split(' '):
>   #print cc.upper()
> # Counter
> countResults = 0
> # Loop through arguments
> for c in criteres.split(' '):
>   # Lecture_mots iS "Z SQL method" in Zope (ZMI) which use a "Z MySQL  
> database connection"
>   results = context.lecture_mots(critere='%'+c.upper()+'%')

I'd actually use upper() in the DB query but it doesn't make much  
difference

>   if len(results) == 0:  # if not results is a nicer way to write this
>       print 'No results for ' + c
>   else:
>       countResults = len(results)
>       print str(countResults) + ' results for ' + c
>       for ligne in results:
>           print '<h3>' + ligne[1] + '</h3>'
>               # Test
>               #for colonne in ligne:
>                   #print colonne
> return results

Do not use a PythonScript to generate user readable output! Use it simply  
to control your SQL query and pass the results to a template to display  
which look something like this.
<tal:block tal:define="results context/myScript">

<h3 tal:repeat="ligne results" tal:content="ligne/id"></h3>
</tal:block>

As you actually wish to list the results by criteria then you should pass  
the criteria to the script in a template loop but I'll leave that to you.

Charlie


More information about the Zope-DB mailing list