[Zope] ext.method to pythonscript - simple question

Duncan Booth duncan@rcp.co.uk
Wed, 11 Apr 2001 09:49:08 +0100


> Having some {very} rudimentary trouble translating External Python
> Method work done many moons ago into [Zope]PythonScripts. If someone
> could shine just a little light apples-for-apples, I would really
> appreciate it.
> 
> ExternalMethod
> 
> #gettext.py
> def gettext(self):
>     print "gettext"
>     params = urllib.urlencode({'message': Do you understand
> now?','name':'Zope Lover','status':'done'})
>     return params
> 
> Please what is the correct syntax for this as PythonScript in Zope231?

Create a python script 'gettext' and paste the following into the 
body:
------------- begin gettext -------------
def urlencode(dict):
    """Encode a dictionary of form entries into a URL query string."""
    from Products.PythonScripts.standard import url_quote_plus
    from string import join
    l = []
    for k, v in dict.items():
        k = url_quote_plus(str(k))
        v = url_quote_plus(str(v))
        l.append(k + '=' + v)
    return join(l, '&')

dict = {'message': 'Do you understand now?',
      'name':'Zope Lover','status':'done'}

params = urlencode(dict)
return params
------------- end gettext -------------

The main problem is that you cannot import urllib into a python 
script, nor is there a direct equivalent of urlencode available to the 
script. However you can copy the definition of urlencode from urllib, 
and the two functions you need urllib.quote_plus and string.join are 
both importable (or the equivalent function is).
The next problem is that the urlencode function cannot access 
variables in the script outside itself, so the imports need to be 
moved into the function. You could also define urlencode as a 
separate python script if you want to reuse it, but if you only need 
it in one place if can just be a local function.

-- 
Duncan Booth                                             duncan@rcp.co.uk