def main(): hostname, port = defaultHostname, defaultPort if os.environ.has_key('QUERY_STRING'): if enableCgiTb: import cgitb cgitb.enable() if allowCgiParameters: form = cgi.FormContentDict() hostname = form.get('host', [defaultHostname])[0] try: port = int(form.get('port', [defaultPort])[0]) except: pass else: import getopt options, parameters = getopt.getopt(sys.argv[1:], 'h', ('help', )) for option, argument in options: if option in ['-h', '--help']: usage() sys.exit(0) if len(parameters) > 2: usage() sys.exit(0) if 1 <= len(parameters) <= 2: hostname = parameters[0] if len(parameters) == 2: port = int(parameters[1]) getAndPrintStat(hostname, port)
def test_strict(self): for orig, expect in parse_strict_test_cases: # Test basic parsing d = do_test(orig, "GET") self.assertEqual(d, expect, "Error parsing %s" % repr(orig)) d = do_test(orig, "POST") self.assertEqual(d, expect, "Error parsing %s" % repr(orig)) env = {'QUERY_STRING': orig} fcd = cgi.FormContentDict(env) sd = cgi.SvFormContentDict(env) fs = cgi.FieldStorage(environ=env) if type(expect) == type({}): # test dict interface self.assertEqual(len(expect), len(fcd)) self.assertEqual(sorted(expect.keys()), sorted(fcd.keys())) self.assertEqual(sorted(expect.values()), sorted(fcd.values())) self.assertEqual(sorted(expect.items()), sorted(fcd.items())) self.assertEqual(fcd.get("nonexistent field", "default"), "default") self.assertEqual(len(sd), len(fs)) self.assertEqual(sorted(sd.keys()), sorted(fs.keys())) self.assertEqual(fs.getvalue("nonexistent field", "default"), "default") # test individual fields for key in expect.keys(): expect_val = expect[key] self.assert_(fcd.has_key(key)) self.assertEqual(sorted(fcd[key]), sorted(expect[key])) self.assertEqual(fcd.get(key, "default"), fcd[key]) self.assert_(fs.has_key(key)) if len(expect_val) > 1: single_value = 0 else: single_value = 1 try: val = sd[key] except IndexError: self.failIf(single_value) self.assertEqual(fs.getvalue(key), expect_val) else: self.assert_(single_value) self.assertEqual(val, expect_val[0]) self.assertEqual(fs.getvalue(key), expect_val[0]) self.assertEqual(sorted(sd.getlist(key)), sorted(expect_val)) if single_value: self.assertEqual(sorted(sd.values()), first_elts(sorted(expect.values()))) self.assertEqual( sorted(sd.items()), first_second_elts(sorted(expect.items())))
#!/usr/bin/python import cgitb import json from operator import itemgetter import os import cgi from datetime import datetime, timedelta cgitb.enable() # Ensure working directory is in this folder trim = "/".join(__file__.split("/")[0:-1]) os.chdir(trim) fields = cgi.FormContentDict( ) #Something weird was happening with FieldStorage.., it was claiming to not be indexable #fields = cgi.FieldStorage() UNIX_EPOCH = datetime(year=1970, month=1, day=1) # startTime, name, score1, score2, winner, time with open("scores.txt", "r") as scores_file: data = scores_file.read().replace("\x00", "").split("\n") data = [p.split(" ") for p in data if p != ""] for item in data: item[0] = int(item[0]) item[2] = int(item[2]) item[3] = int(item[3]) item[4] = item[4] == "True" item[5] = float(item[5])
from test_support import verify, verbose
JSONoutput = Json() #use default paths JSON_HEADER = """Content-Type: application/json; charset=utf-8 Access-Control-Allow-Origin: * Access-Control-Allow-Methods: GET """ #Allow cross domain XHR HTTP_HEADER = """Content-Type: text/html; charset=utf-8\n\n """ # Get form arguments and build the flags dict form = cgi.FormContentDict() flags = {} for key, value in form.items(): flags[key] = value[0] if len(flags): print JSON_HEADER print JSONoutput.do( flags ) else: print HTTP_HEADER print JSONoutput._information["json_output_system_note"]
def main(): for orig, expect in parse_qsl_test_cases: result = cgi.parse_qsl(orig, keep_blank_values=True) print repr(orig), '=>', result verify(result == expect, "Error parsing %s" % repr(orig)) for orig, expect in parse_strict_test_cases: # Test basic parsing print repr(orig) d = do_test(orig, "GET") verify(d == expect, "Error parsing %s" % repr(orig)) d = do_test(orig, "POST") verify(d == expect, "Error parsing %s" % repr(orig)) env = {'QUERY_STRING': orig} fcd = cgi.FormContentDict(env) sd = cgi.SvFormContentDict(env) fs = cgi.FieldStorage(environ=env) if type(expect) == type({}): # test dict interface verify(len(expect) == len(fcd)) verify(norm(expect.keys()) == norm(fcd.keys())) verify(norm(expect.values()) == norm(fcd.values())) verify(norm(expect.items()) == norm(fcd.items())) verify(fcd.get("nonexistent field", "default") == "default") verify(len(sd) == len(fs)) verify(norm(sd.keys()) == norm(fs.keys())) verify(fs.getvalue("nonexistent field", "default") == "default") # test individual fields for key in expect.keys(): expect_val = expect[key] verify(fcd.has_key(key)) verify(norm(fcd[key]) == norm(expect[key])) verify(fcd.get(key, "default") == fcd[key]) verify(fs.has_key(key)) if len(expect_val) > 1: single_value = 0 else: single_value = 1 try: val = sd[key] except IndexError: verify(not single_value) verify(fs.getvalue(key) == expect_val) else: verify(single_value) verify(val == expect_val[0]) verify(fs.getvalue(key) == expect_val[0]) verify(norm(sd.getlist(key)) == norm(expect_val)) if single_value: verify(norm(sd.values()) == \ first_elts(norm(expect.values()))) verify(norm(sd.items()) == \ first_second_elts(norm(expect.items()))) # Test the weird FormContentDict classes env = {'QUERY_STRING': "x=1&y=2.0&z=2-3.%2b0&1=1abc"} expect = {'x': 1, 'y': 2.0, 'z': '2-3.+0', '1': '1abc'} d = cgi.InterpFormContentDict(env) for k, v in expect.items(): verify(d[k] == v) for k, v in d.items(): verify(expect[k] == v) verify(norm(expect.values()) == norm(d.values())) print "Testing log" cgi.log("Testing") cgi.logfp = sys.stdout cgi.initlog("%s", "Testing initlog 1") cgi.log("%s", "Testing log 2") if os.path.exists("/dev/null"): cgi.logfp = None cgi.logfile = "/dev/null" cgi.initlog("%s", "Testing log 3") cgi.log("Testing log 4") print "Test FieldStorage methods that use readline" # FieldStorage uses readline, which has the capacity to read all # contents of the input file into memory; we use readline's size argument # to prevent that for files that do not contain any newlines in # non-GET/HEAD requests class TestReadlineFile: def __init__(self, file): self.file = file self.numcalls = 0 def readline(self, size=None): self.numcalls += 1 if size: return self.file.readline(size) else: return self.file.readline() def __getattr__(self, name): file = self.__dict__['file'] a = getattr(file, name) if not isinstance(a, int): setattr(self, name, a) return a f = TestReadlineFile(tempfile.TemporaryFile()) f.write('x' * 256 * 1024) f.seek(0) env = {'REQUEST_METHOD': 'PUT'} fs = cgi.FieldStorage(fp=f, environ=env) # if we're not chunking properly, readline is only called twice # (by read_binary); if we are chunking properly, it will be called 5 times # as long as the chunksize is 1 << 16. verify(f.numcalls > 2) print "Test basic FieldStorage multipart parsing" env = { 'REQUEST_METHOD': 'POST', 'CONTENT_TYPE': 'multipart/form-data; boundary=---------------------------721837373350705526688164684', 'CONTENT_LENGTH': '558' } postdata = """-----------------------------721837373350705526688164684 Content-Disposition: form-data; name="id" 1234 -----------------------------721837373350705526688164684 Content-Disposition: form-data; name="title" -----------------------------721837373350705526688164684 Content-Disposition: form-data; name="file"; filename="test.txt" Content-Type: text/plain Testing 123. -----------------------------721837373350705526688164684 Content-Disposition: form-data; name="submit" Add\x20 -----------------------------721837373350705526688164684-- """ fs = cgi.FieldStorage(fp=StringIO(postdata), environ=env) verify(len(fs.list) == 4) expect = [{ 'name': 'id', 'filename': None, 'value': '1234' }, { 'name': 'title', 'filename': None, 'value': '' }, { 'name': 'file', 'filename': 'test.txt', 'value': 'Testing 123.\n' }, { 'name': 'submit', 'filename': None, 'value': ' Add ' }] for x in range(len(fs.list)): for k, exp in expect[x].items(): got = getattr(fs.list[x], k) verify(got == exp)
###tail = tail + '<br> here are the values from the cgi input => ' + cgikeys[n] if cgikeys[n].upper( ) == "PIOPASS": #don't put in piopass into the dictionary for security reasons. n = n + 1 else: ### tail = tail + '<br> cgikey value => ' + str(form[cgikeys[n]].value) ##not the Page values #should I allow cgi form data to generate a pinp?...it could open a hole where outside code gets executed on the system....a pinp could be a pobj. try: pinpdict[cgikeys[n]] = form[cgikeys[ n]].value #update pinp dictionary with input values pinpdict[cgikeys[n] + '.quote'] = '"%s"' % ( str(form[cgikeys[n]].value) ) #update pinp dictionary with quoted input values n = n + 1 except AttributeError: #this is where a list is happening for a cgikey eg. selectmulti, checkbox fcdlist = cgi.FormContentDict()[cgikeys[n]] fn = 0 fcdlstr = '' for a in fcdlist: if fn == 0: fcdlstr = fcdlist[fn] fcdlstrquote = '"%s"' % (fcdlist[fn]) pinpdict[cgikeys[n] + '.' + str(fn)] = fcdlist[ fn] #update pinp dictionary with input values else: fcdlstr = fcdlstr + ', ' + fcdlist[fn] fcdlstrquote = fcdlstrquote + ', "%s"' % (fcdlist[fn]) pinpdict[cgikeys[n] + '.' + str(fn)] = fcdlist[ fn] #update pinp dictionary with input values fn = fn + 1 pinpdict[cgikeys[n]] = fcdlstr
def main(): for orig, expect in parse_test_cases: # Test basic parsing print repr(orig) d = do_test(orig, "GET") verify(d == expect, "Error parsing %s" % repr(orig)) d = do_test(orig, "POST") verify(d == expect, "Error parsing %s" % repr(orig)) env = {'QUERY_STRING': orig} fcd = cgi.FormContentDict(env) sd = cgi.SvFormContentDict(env) fs = cgi.FieldStorage(environ=env) if type(expect) == type({}): # test dict interface verify(len(expect) == len(fcd)) verify(norm(expect.keys()) == norm(fcd.keys())) verify(norm(expect.values()) == norm(fcd.values())) verify(norm(expect.items()) == norm(fcd.items())) verify(fcd.get("nonexistent field", "default") == "default") verify(len(sd) == len(fs)) verify(norm(sd.keys()) == norm(fs.keys())) verify(fs.getvalue("nonexistent field", "default") == "default") # test individual fields for key in expect.keys(): expect_val = expect[key] verify(fcd.has_key(key)) verify(norm(fcd[key]) == norm(expect[key])) verify(fcd.get(key, "default") == fcd[key]) verify(fs.has_key(key)) if len(expect_val) > 1: single_value = 0 else: single_value = 1 try: val = sd[key] except IndexError: verify(not single_value) verify(fs.getvalue(key) == expect_val) else: verify(single_value) verify(val == expect_val[0]) verify(fs.getvalue(key) == expect_val[0]) verify(norm(sd.getlist(key)) == norm(expect_val)) if single_value: verify(norm(sd.values()) == \ first_elts(norm(expect.values()))) verify(norm(sd.items()) == \ first_second_elts(norm(expect.items()))) # Test the weird FormContentDict classes env = {'QUERY_STRING': "x=1&y=2.0&z=2-3.%2b0&1=1abc"} expect = {'x': 1, 'y': 2.0, 'z': '2-3.+0', '1': '1abc'} d = cgi.InterpFormContentDict(env) for k, v in expect.items(): verify(d[k] == v) for k, v in d.items(): verify(expect[k] == v) verify(norm(expect.values()) == norm(d.values())) print "Testing log" cgi.initlog() cgi.log("Testing") cgi.logfp = sys.stdout cgi.initlog("%s", "Testing initlog 1") cgi.log("%s", "Testing log 2") if os.path.exists("/dev/null"): cgi.logfp = None cgi.logfile = "/dev/null" cgi.initlog("%s", "Testing log 3") cgi.log("Testing log 4")
#!/usr/bin/python # -*- coding: utf-8 -*- """ Script used to retrieve infos from the form, format the informations, give them to the recommandation engine and display the result """ import cgi import cgitb from db.db_module import db_execute_in import re cgitb.enable() # Retrieving informations from the form FORM = cgi.FormContentDict() # search : add recipe_id if 'search' in FORM.keys(): RECI_ID = re.sub(r'_url', '', FORM['search'][0]) REQ = """ UPDATE search SET recipe_id={0} WHERE user_id={1} AND recipe_id IS NULL; """.format(RECI_ID.split('_')[1], RECI_ID.split('_')[0]) db_execute_in([REQ]) # fav if 'fav' in FORM.keys(): FAV_ID = re.sub(r'fav_', '', FORM['fav'][0]) REQ = """
def main(): form = cgi.FormContentDict() archive = os.environ['PATH_TRANSLATED'] try: path = form['file'][0] except KeyError: path = '' tmpdir = '/tmp/%s' % os.getpid() try: os.mkdir(tmpdir, 0755) except os.error: pass f = os.popen('/usr/contrib/bin/gzcat %s | tar tvf - %s' % (archive, path), 'r') listing = f.readlines() if listing: if listing[0][0] == 'd': _write(sys.stdout, 'Content-type: %s\r\n\r\n' % 'text/html') _write(sys.stdout, '<html><head><title>%s</title></head><body><pre>\n' % path) # user asked for a directory - send back a listing listing = listing[1:-1] splpat = regex.symcomp('\(<f>.* \)\(<r>.*\)') deeppat = regex.compile('%s/[^/]*/' % path) pathinfo = os.environ['PATH_INFO'] super = string.join(string.split(path, '/')[:-1], '/') if super: _write(sys.stdout, ' ' * 32) _write( sys.stdout, '<a href="/cgi-bin/tgzextr%s?file=%s"><Up One Level></a>\n' % (pathinfo, super)) for line in map(string.strip, listing): if splpat.match(line) != -1: first = splpat.group('f') rest = splpat.group('r') if deeppat.match(rest) != -1: continue _write(sys.stdout, first[:11] + first[32:]) _write( sys.stdout, '<a href="/cgi-bin/tgzextr%s?file=%s">%s</a>\n' % (pathinfo, rest, rest)) else: fmimetype = mimetypes.get_type(path) _write(sys.stdout, 'Content-type: %s\r\n\r\n' % fmimetype) os.chdir(tmpdir) os.system("/usr/contrib/bin/gzcat %s | tar xf - %s" % (archive, path)) _writelines(sys.stdout, open('%s/%s' % (tmpdir, path)).readlines()) os.unlink('%s/%s' % (tmpdir, path)) path = string.split(path)[:-1] try: while path: dirs = string.join(path) os.rmdir('%s/%s', (tmpdir, dirs)) path = path[:-1] os.rmdir(tmpdir) except os.error: pass