Welcome, guest | Sign In | My Account | Store | Cart

create dictionary-like object that mimics the cgi.FieldStorage() object having both a .value property, and a .getvalue() method

Python, 35 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# The FakeStorage class mimics the FieldStorage object in this limited respect:
# 1. we can initialize our dummy 'form' like this:
#     form = FakeStorage()
#     form['sparqlQuery'] = "query string"
#     
# and access it like this:
#     form.getvalue("sparqlQuery")
#     
# OR
# 
# 2. we can initialize it as an ordinary dict like this:
#     form = {"serialize": FakeStorage('serialization format string')}
#     
# and access it like this:
#     form["serialize"].value


    class FakeStorage(dict):
        def __init__(self, s=None):
            self.value = s
        def getvalue(self, k):
            return self[k]

# opt. 1:
     form = FakeStorage()
     form['sparqlQuery'] = "query string"

# then access the form thus:
    form.getvalue("sparqlQuery")

# opt. 2: initialize `form` as an ordinary dict:
    form = {'serialize': FakeStorage('n3')}

# and access it like this:
    form["serialize"].value

There's probably a much smarter way to do this in the CGI module or in urllib, but this is my quick and dirty solution. I wanted to be able to run cgi scripts from the command line where there was no incoming request from a web page. Typically the FieldStorage object in an ordinary request from the web page is created thus: form = cgi.FieldStorage() and then accessed using form['key'].value or by means of the getvalue() method: form.getvalue('key'). I wanted to be able create a mock request so that the script could be executed from the command line, or from within my editor during development or debugging.

NB: the cgi.FieldStorage.getvalue() method has an optional second argument providing a default value. FakeStorage does not.

Created by Jon Crump on Thu, 18 Jun 2015 (MIT)
Python recipes (4591)
Jon Crump's recipes (1)

Required Modules

Other Information and Tasks