[Python编程(第4版)].(Programming.Python.4th.Edition).Mark.Lutz.文字版

(yzsuai) #1

Example 15-21. PP4E\Internet\Web\cgi-bin\formMockup.py


"""
Tools for simulating the result of a cgi.FieldStorage()
call; useful for testing CGI scripts outside the Web
"""


class FieldMockup: # mocked-up input object
def init(self, str):
self.value = str


def formMockup(**kwargs): # pass field=value args
mockup = {} # multichoice: [value,...]
for (key, value) in kwargs.items():
if type(value) != list: # simple fields have .value
mockup[key] = FieldMockup(str(value))
else: # multichoice have list
mockup[key] = [] # to do: file upload fields
for pick in value:
mockup[key].append(FieldMockup(pick))
return mockup


def selftest():


use this form if fields can be hardcoded


form = formMockup(name='Bob', job='hacker', food=['Spam', 'eggs', 'ham'])
print(form['name'].value)
print(form['job'].value)
for item in form['food']:
print(item.value, end=' ')


use real dict if keys are in variables or computed


print()
form = {'name': FieldMockup('Brian'), 'age': FieldMockup(38)} # or dict()
for key in form.keys():
print(form[key].value)


if name == 'main': selftest()


When we place our mock-up class in the module formMockup.py, it automatically
becomes a reusable tool and may be imported by any script we care to write.† For
readability, the dummy field simulation class has been renamed FieldMockup here. For
convenience, we’ve also added a formMockup utility function that builds up an entire
form dictionary from passed-in keyword arguments. Assuming you can hardcode the
names of the form to be faked, the mock-up can be created in a single call. This module
includes a self-test function invoked when the file is run from the command line, which
demonstrates how its exports are used. Here is its test output, generated by making
and querying two form mock-up objects:


† Assuming, of course, that this module can be found on the Python module search path when those scripts
are run. Since Python searches the current directory for imported modules by default, this generally works
without sys.path changes if all of our files are in our main web directory. For other applications, we may
need to add this directory to PYTHONPATH or use package (directory path) imports.


Refactoring Code for Maintainability | 1197
Free download pdf