nutools/lib/ulib/support/cgiparams.py

55 lines
1.7 KiB
Python
Executable File

#!/usr/bin/env python
# -*- coding: utf-8 mode: python -*- vim:sw=4:sts=4:et:ai:si:sta:fenc=utf-8
u"""Ce script est prévu pour être utilisé dans un script CGI.
Il permet de lister les paramètres du formulaire et d'y accéder depuis un script bash
"""
import re, cgi
RE_NAME_VALUE = re.compile(r'([a-zA-Z0-9_-]+)(?:=(.*))?$')
def quote(value, q=False):
if value or q:
value = "'%s'" % value.replace("'", "'\\''")
value = re.sub(r"(?<!\\)''", "", value)
return value
else: return ""
def print_scalar(name, value):
print "%s=%s" % (name, quote(value))
def print_array(name, values):
print "%s=(" % name
for value in values:
print quote(value, True)
print ")"
def run_cgiparams():
from optparse import OptionParser
OP = OptionParser(usage=u"\n\t%prog [options] params...", description=__doc__)
o, args = OP.parse_args()
form = cgi.FieldStorage(keep_blank_values=True)
if args:
for nv in args:
mo = RE_NAME_VALUE.match(nv)
if mo is None: continue
fname, defvalue = mo.group(1), mo.group(2)
if defvalue is None: defvalue = ''
vname = fname.replace('-', '_')
values = form.getlist(fname)
if len(values) == 0: print_scalar(vname, defvalue)
elif len(values) == 1: print_scalar(vname, values[0])
else: print_array(vname, values)
else:
for fname in form.keys():
vname = fname.replace('-', '_')
values = form.getlist(fname)
if len(values) == 1: print_scalar(vname, values[0])
else: print_array(vname, values)
if __name__ == '__main__':
run_cgiparams()