[Zope] Encoding URL Vars

Kapil Thangavelu kvthan@wm.edu
Fri, 21 Jul 2000 17:30:08 -0700


i recently had a problem with encoding url vars in a dtml-call
such as

<dtml-call "RESPONSE.redirect(URL1+'?var_name='+var_name)">


i got a couple suggestions from the list but decided that i'd go ahead
and write a utility function in a python method based on urllib. here
are two python methods. one to encode a dictionary and one to
automatically encode all the form variables in the request. you still
need to add a '?' to the url before a call to the method to signify a
GET.

Python Method ##1

name: url_encode_vars
parameters: vars # a dictionary of variables to be encoded

# Code straight from urllib minor
# changes to get around assignment to sub_scripts,
# access to string module, and namepace issues

global always_safe, quote, quote_plus
always_safe = _.string.letters + _.string.digits + '_,.-'

def quote(s, safe = '/'):
    global always_safe
    safe = always_safe + safe
    res = []
    for c in s:
    	if c not in safe:
	    res.append('%%%02x'%ord(c))
	else:
	    res.append(c)
    return _.string.joinfields(res, '')


def quote_plus(s, safe='/'):
    global quote
    if ' ' in s:
	res = []
	# replaec ' ' with '+'
	l = _.string.split(s, ' ')
	for i in l:
            res.append(quote(i, safe))
	return _.string.join(res, '+')
    else:
	return quote(s, safe)


def urlencode(dict):
     global quote_plus
     l = []
     for k, v in dict.items():
         k = quote_plus(str(k))
         v = quote_plus(str(v))
         l.append(k + '=' + v)
     return _.string.join(l, '&')


return urlencode(vars)

####
example call to above

<dtml-call
"RESPONSE.redirect(URL1+'?'+url_encode_vars({vars={'squishy':1,
'bad_input':'&user=root'}) )">

this isn't always optimal since you might not know all the variables and
you just want to pass along all of the form variables.

hence

PythonMethod #2
name: url_encode_form_vars
parameters: namepace # the namepace='_'


try:
	vars=namespace['REQUEST'].form
	method =  namespace.getitem('url_encode_vars', 0)
	return method(vars)
except:
	pass


#####
example call to above
<dtml-call "RESPONSE.redirect(URL1+'?'+url_encode_form_vars(_))">


Cheers

Kapil