def test_Size(self): target_root = '/tmp/work/__TEST__' target_dummy = os.path.join(target_root, 'a.dummy') self.__MakeDummy(target_dummy, 1024) #s = Directory(target_root) s = Directory(target_root) self.assertEqual(1024, s.Size) path_b = os.path.join(target_root, 'B') Directory.Create(path_b) self.__MakeDummy(os.path.join(path_b, 'b.dummy'), 1024) self.assertEqual(2048, s.Size) path_c = os.path.join(target_root, 'C') Directory.Create(path_c) self.__MakeDummy(os.path.join(path_c, 'c.dummy'), 1024) self.assertEqual(3072, s.Size) path_bb = os.path.join(target_root, 'B/BB') Directory.Create(path_bb) self.__MakeDummy(os.path.join(path_bb, 'bb.dummy'), 1024) self.assertEqual(4096, s.Size) Directory.Delete(target_root)
def make_qsub_spline_mc(run_name, production, data_type): """make spline command for mc files""" flattree_dir = Directory('%s/%s/%s' % (FLATTREEBASE, production, run_name.low())) if not flattree_dir.exists(): print 'ERROR: there is no directory' print '\"%s\"' % (flattree_dir.get()) return None flatttree_dir_list = '-L %s' % (flattree_dir.get()) queue = '-q %s' % (QUEUE) hosts = '-N %s' % (HOSTS) minutes = '-M %s' % (MCMIN) memory = '-m %s' % (MEM) output_path_name = Directory('%s/%s/%s' % (SPLINEBASE, production, run_name.low())) run_type = '-r %s' % (data_type) if not output_path_name.exists(): print 'WARNING: directory' print '\"%s\"' % (output_path_name.get()) print 'does not exist. Will create it now' # output_path_name.mkdir() output_path = '-p %s' % (output_path_name.get()) output_name = '-o %s_spline' % (run_name.upper_case()) this_run = ShellCommand('nohup %s' % (QSUBSPLINE)) this_run.add(flatttree_dir_list) this_run.add(queue) this_run.add(hosts) this_run.add(memory) this_run.add(minutes) this_run.add(run_type) this_run.add(output_path) this_run.add(output_name) return this_run
def __init__(self, root, fileBuilder, directoryBuilder): assert (root is not None and fileBuilder is not None and directoryBuilder is not None) self._root = Directory(root, None, directoryBuilder, fileBuilder) self.directoryBuilder = directoryBuilder self.fileBuilder = fileBuilder self.dircount = 1
def test_print_length_none(self, capfd): d = Directory() d.print_length() out, err = capfd.readouterr() assert out == "0 entries in directory\n" assert len(getattr(d, "directory")) == 0
def test_mv_tree(self): target = '/tmp/work/__TEST__/a.txt' self.assertTrue(not File.IsExist(target)) self.assertTrue(not File.IsExist('/tmp/work/__TEST_2__/a.txt')) d = File(target) self.assertEqual(target, d.Path) with self.assertRaises(FileNotFoundError) as e: d.mv('/tmp/work/__TEST_2__/a.txt') d.mk('B/b.txt') self.assertEqual(target, d.Path) self.assertTrue(File.IsExist('/tmp/work/__TEST__/B/b.txt')) self.assertTrue(not File.IsExist('/tmp/work/__TEST__/a.txt')) d.mk() d.mv('/tmp/work/__TEST_2__/a.txt') self.assertEqual('/tmp/work/__TEST_2__/a.txt', d.Path) self.assertTrue(File.IsExist('/tmp/work/__TEST_2__/a.txt')) self.assertTrue(not File.IsExist(target)) self.assertTrue(Directory.IsExist('/tmp/work/__TEST_2__')) self.assertTrue(not File.IsExist('/tmp/work/__TEST_2__/B/b.txt')) Directory.Delete('/tmp/work/__TEST_2__') Directory.Delete('/tmp/work/__TEST__')
def test_print_directory_empty(self, capfd): d = Directory() d.print_directory() out, err = capfd.readouterr() assert out == "Directory is empty\n" assert len(getattr(d, "directory")) == 0
def make_qsub_niwg_weights_mc(run_name, production, data_type): """make niwg_weights command for mc files""" bincorr_dir = Directory('%s/%s/%s' % (BINCORRBASE, production, run_name.low())) if not bincorr_dir.exists(): print 'ERROR: there is no directory' print '\"%s\"' % (bincorr_dir.get()) return None bincorr_dir_list = '-L %s' % (bincorr_dir.get()) queue = '-q %s' % (QUEUE) hosts = '-N %s' % (HOSTS) minutes = '-M %s' % (MCMIN) memory = '-m %s' % (MEM) output_path_name = Directory('%s/%s/%s' % (NIWGWEIGHTSBASE, production, run_name.low())) run_type = '-r %s' % (data_type) if not output_path_name.exists(): print 'WARNING: directory' print '\"%s\"' % (output_path_name.get()) print 'does not exist. Will create it now' # output_path_name.mkdir() output_path = '-p %s' % (output_path_name.get()) output_name = '-o %s_niwg_weights' % (run_name.upper_case()) this_run = ShellCommand('nohup %s' % (QSUBNIWGWEIGHTS)) this_run.add(bincorr_dir_list) this_run.add(queue) this_run.add(hosts) this_run.add(memory) this_run.add(minutes) this_run.add(run_type) this_run.add(output_path) this_run.add(output_name) return this_run
def make_qsub(run_name, production): """makes a MC qsubmitter.py command class for a particular RN class input""" flattree_dir = Directory(join(FLATTREEBASE, production, run_name.low())) if not flattree_dir.exists(): print 'ERROR: there is no directory' print '\"%s\"' % (flattree_dir.get()) return None flattree_dir_list = '-L %s' % (flattree_dir.get()) queue = '-q %s' % (QUEUE) hosts = '-N %s' % (HOSTS) minutes = '-M %s' % (MCMIN) memory = '-m %s' % (MEM) output_path_name = Directory('%s/%s/%s' % (RUNSYSTBINCORRBASE, production, run_name.low())) if not output_path_name.exists(): print 'WARNING: directory' print '\"%s\"' % (output_path_name.get()) print 'does not exist. Will create it now' output_path = '-p %s' % (output_path_name.get()) output_name = '-o %s' % (run_name.upper_case()) this_run = ShellCommand('nohup %s' % (QSUBRUNSYSTBINCORR)) this_run.add(flattree_dir_list) this_run.add(memory) this_run.add(queue) this_run.add(hosts) this_run.add(minutes) this_run.add(output_path) this_run.add(output_name) return this_run
def test_print_length_one(self, capfd): directory = {"George Zipper": "[email protected]/555 294 4929/IT/IT Director/U of Y/\n"} d = Directory(directory) d.print_length() out, err = capfd.readouterr() assert out == "1 entry in directory\n" assert len(getattr(d, "directory")) == 1
def setUp(self): self.Directory1 = Directory() self.Directory2 = Directory() self.Directory2.data.append("firstAccount") self.Directory2.data.append("secondAccount") self.Directory2.data.append("lastAccount") self.Directory2.manyItems = 3 self.Account1 = account()
def test_Path(self): target_root = '/tmp/work/__TEST__' target_dummy = os.path.join(target_root, 'a.dummy') self.__MakeDummy(target_dummy, 1024) s = Directory(target_root) self.assertEqual('/tmp/work/__TEST__', s.Path) Directory.Delete(target_root)
def check_directory_run_lists(directory): """Given the directory with the run lists, loop over run lists""" test_dir = Directory(directory) if not test_dir.exists(): print 'The directory \"%s\" does not exist!' % (directory) return for run_list_name in sorted(os.listdir(directory)): check_run_list_file(os.path.join(directory, run_list_name))
def test_field_fail_2(self, capfd): name = "Rachel Wood" d = Directory({name: "[email protected]/283 482 4929/IT/IT Person/U of A/\n"}) d.edit_entry(name, "*****@*****.**", "job title") out, err = capfd.readouterr() assert out == "Invalid field entered\n" assert name in getattr(d, "directory")
def test_name_fail_2(self, capfd): d = Directory({"Rachel Wood": "[email protected]/283 482 4929/IT/IT Person/U of A/\n"}) new_rachel = "Rachel WOOD" d.edit_entry(new_rachel, "*****@*****.**", "email") out, err = capfd.readouterr() assert out == "Entry does not exist\n" assert new_rachel not in getattr(d, "directory")
def test_GetChangedMeta(self): target_root = '/tmp/work/__TEST__' target_dummy = os.path.join(target_root, 'a.dummy') self.__MakeDummy(target_dummy, 1024) self.assertTrue(hasattr(Directory, 'GetChangedMeta')) self.assertTrue(hasattr(Directory, 'GetCreated')) print(Directory.GetChangedMeta(target_dummy)) print(Directory.GetCreated(target_dummy)) Directory.Delete(target_root)
def test_Stat(self): target_root = '/tmp/work/__TEST__' target_dummy = os.path.join(target_root, 'a.dummy') self.__MakeDummy(target_dummy, 1024) s = Directory(target_root) self.assertEqual(Directory, type(s)) self.assertEqual(os.stat_result, type(s.Stat)) Directory.Delete(target_root)
def test_name_fail(self, capfd): d = Directory({"Rachel Wood": "[email protected]/283 482 4929/IT/IT Person/U of A/\n"}) person = "George Zip" d.edit_entry(person, "*****@*****.**", "email") out, err = capfd.readouterr() assert out == "Entry does not exist\n" assert person not in getattr(d, "directory")
def test_print_entry_success(self, capfd): name = "Megan Bloom" d = Directory({name: "[email protected]/555 294 4929/IT/IT Director/U of Y/\n"}) d.print_entry(name) out, err = capfd.readouterr() assert name in getattr(d, "directory") assert out == name + "/[email protected]/555 294 4929/IT/IT Director/U of Y/\n"
def test_UnArchive(self): self.__make_archive() self.assertTrue(not Directory.IsExist('/tmp/work/__TEST__')) Directory.UnArchive('/tmp/work/__TEST__.zip') self.assertTrue(Directory.IsExist('/tmp/work/__TEST__')) self.assertTrue(Directory.IsExist('/tmp/work/__TEST__/A')) self.assertTrue(os.path.isfile('/tmp/work/__TEST__/A/a.txt')) Directory.Delete('/tmp/work/__TEST__') os.remove('/tmp/work/__TEST__.zip')
def test_print_entry_fail(self, capfd): person = "George Zip" d = Directory({"Megan Bloom": "[email protected]/555 294 4929/IT/IT Director/U of Y/\n"}) d.print_entry(person) out, err = capfd.readouterr() assert person not in getattr(d, "directory") assert out == "Entry does not exist\n"
def test_ChangedMeta(self): target_root = '/tmp/work/__TEST__' target_dummy = os.path.join(target_root, 'a.dummy') self.__MakeDummy(target_dummy, 1024) s = Directory(target_root) self.assertTrue(hasattr(s, 'ChangedMeta')) self.assertTrue(hasattr(s, 'Created')) print(s.ChangedMeta) print(s.Created) Directory.Delete(target_root)
def test_Move_single(self): target = '/tmp/work/__TEST__/a.txt' self.assertTrue(not File.IsExist(target)) self.assertTrue(not File.IsExist('/tmp/work/__TEST_2__')) File.Create(target) File.Move(target, '/tmp/work/__TEST_2__/b.txt') self.assertTrue(not File.IsExist(target)) self.assertTrue(File.IsExist('/tmp/work/__TEST_2__/b.txt')) Directory.Delete('/tmp/work/__TEST_2__') Directory.Delete('/tmp/work/__TEST__')
def __make_archive(self): target = '/tmp/work/__TEST__' self.assertTrue(not Directory.IsExist(target)) Directory.Create(target) Directory.Create(os.path.join(target, 'A')) pathlib.Path(os.path.join(target, 'A/a.txt')).touch() Directory.Archive(target, target + '.zip') self.assertTrue(os.path.isfile(target + '.zip')) Directory.Delete(target)
def test_constructor_attrs(): d = Directory() z = Directory(None) c = Directory({"key": "value"}) e = Directory({4: "value here"}) assert getattr(d, "directory") == {} assert getattr(z, "directory") == {} assert getattr(c, "directory") == {"key": "value"} assert getattr(e, "directory") == {4: "value here"}
def setUp(self): self.Directory1 = Directory() self.Directory2 = Directory() self.account1 = instructor("firstAccount") self.account2 = teachingAssistant("secondAccount") self.account3 = instructor("lastAccount") self.Directory2.data.append(self.account1) self.Directory2.data.append(self.account2) self.Directory2.data.append(self.account3) self.Directory2.manyItems = 3
def test_success_2(self, capfd): name = "Rachel Wood" d = Directory({name: "[email protected]/283 482 4929/IT/IT Person/U of A/\n"}) d.edit_entry(name, " 555 555 5555 ", "PHONE") out, err = capfd.readouterr() new_directory = getattr(d, "directory") assert out == "Entry updated\n" assert new_directory == {name: "[email protected]/ 555 555 5555 /IT/IT Person/U of A/\n"} assert name in new_directory
def test_DiskUsage(self): target_root = '/tmp/work/__TEST__' target_dummy = os.path.join(target_root, 'a.dummy') self.__MakeDummy(target_dummy, 1024) self.assertTrue(hasattr(Directory, 'DiskUsage')) res = Directory.DiskUsage(target_dummy) self.assertTrue(hasattr(res, 'total')) self.assertTrue(hasattr(res, 'used')) self.assertTrue(hasattr(res, 'free')) print(Directory.DiskUsage(target_dummy)) Directory.Delete(target_root)
def test_print_length_multiple(self, capfd): directory = { "George Zipper": "[email protected]/555 294 4929/IT/IT Director/U of Y/\n", "Megan Bloom": "[email protected]/204 294 4919/Marketing/Marketing Doctor/U of Q/\n" } d = Directory(directory) d.print_length() out, err = capfd.readouterr() assert out == "2 entries in directory\n" assert len(getattr(d, "directory")) == 2
def copy_files_to_destination_directory(self): for current_folder_original in self.directories: if current_folder_original.lower().startswith('20'): current_dir = Directory((self.directory_path + current_folder_original), self.picture_destination_directory, self.movie_destination_directory) current_dir.copy_files_to_destination_directory() current_dir.print_details self.file_count += len(current_dir.files) self.files_copied += current_dir.files_copied self.files_not_copied += current_dir.files_not_copied self.files_with_date_found += current_dir.files_with_date_found self.files_without_date_found += current_dir.files_without_date_found
def test_remove_failure(self, capfd): directory = {"Jason Jones": "[email protected]/382 284 4891/IT/IT Person/U of K"} d = Directory(directory) fake_emp = "Joe Green" d.remove_employee(fake_emp) out, err = capfd.readouterr() current_dir = getattr(d, "directory") assert fake_emp not in current_dir assert out == "Entry does not exist\n"
def test_remove_success1(self, capfd): emp_remove = "Jason Jones" directory = {emp_remove: "[email protected]/382 284 4891/IT/IT Person/U of K"} d = Directory(directory) d.remove_employee(emp_remove) out, err = capfd.readouterr() current_dir = getattr(d, "directory") assert emp_remove not in current_dir assert current_dir == {} assert out == "Entry deleted\n"
class DirectorySchema(object): """Represents a directory schema based on a project representation. It will be in charge of building de directory tree and adding the files""" def __init__(self, root, fileBuilder, directoryBuilder): assert( root is not None and fileBuilder is not None and directoryBuilder is not None) self._root = Directory(root, None, directoryBuilder, fileBuilder) self.directoryBuilder = directoryBuilder self.fileBuilder = fileBuilder self.dircount = 1 @property def root(self): return self._root.name @property def dirCount(self): return self.dircount def addDirectory(self, directory): """ adds a directory to the directory schema. args: directory(string), the full path of the directory""" assert(directory is not None and directory != self.root) self._root.addDir(directory) self.dircount += 1 def addFile(self, filepath): """adds a file to a specific directory. args: filename(string), the name of the filename directory(string), the full path of the directory where the file would be inserted""" assert(filepath is not None) self._root.addFile(filepath) def buildRepresentation(self): """ builds the structure of the shhiiieeeet""" self._root.build()
def __init__(self, root, fileBuilder, directoryBuilder): assert( root is not None and fileBuilder is not None and directoryBuilder is not None) self._root = Directory(root, None, directoryBuilder, fileBuilder) self.directoryBuilder = directoryBuilder self.fileBuilder = fileBuilder self.dircount = 1
def __init__(self, form, defaultVars={}, searchPath=["."], autoDispatch=1, **props): """ <documentation type="constructor"> <synopsis> Initialize the instance. As mentioned, you will not be creating instances of WebForm (nor should you). Instead, make a subclass and delegate initialization from your subclass' __init__ method. </synopsis> <param name="form"> cgi.FieldStorage(), passed down upon initialization by the WebFormDispatcher class. </param> <param name="defaultVars"> a set of variables that represent default values. These values come from a .conf file that matches the class name of the WebForm subclass. The WebFormDispatcher reads the .conf file and creates this for you automagically. </param> <param name="searchPath"> list of directories to be searched for HTML (or any included file being referenced from within your HTML code). This is used by the WriteProcessor instance when generating code from the <xref class="WebForm" method="encode"/> method. </param> <param name="encodeTarget"> The name of the HTML file to be used when generating code. This is initialized to None here but actually is initialized by the WebDispatcher when dynamically creating an instance of any WebForm subclass. </param> </documentation> """ if props.has_key('config_dir'): self.config_dir = props['config_dir'] else: self.config_dir = '.' self.form = form self.argv = sys.argv[:] confVars = self.parseConfFile() self.cookies = [] cookie = self.loadCookie() if cookie != None: self.cookies.append(cookie) self.startingCookieCount = 1 else: self.startingCookieCount = 0 self.formVars = Directory({}) self.formVars.update(defaultVars) self.formVars.update(confVars) self.hiddenVars = [] self.fileVars = Directory({}) self.searchPath = searchPath self.setContentStandard() self.extractFormVariables(form) self.encodeTarget = None self.prefix = "" self.autoDispatch = autoDispatch
def __init__(self, name): Directory.__init__(self, name, None) return
def add_directory(self, new_directory="New Directory"): from Directory import Directory os.mkdir(os.path.join(FileSystem.get_current_working_directory(self), new_directory)) directory = Directory() directory.set_directory_name(new_directory) return directory
class WebForm: """ <documentation type="class"> <synopsis> WebForm is intended to be an abstract class. (There isn't much way in Python to enforce its use per se.) Thus it should not be instantiated directly. Instead a subclass should be created. Generally, the subclass only needs to do the following: 1. Delegate initialization to this class from its __init__ method. This is very easily done as follows: WebForm.__init__(self, form, defaultVars, searchPath) 2. Override the process() method with your customized business logic. Your business logic can assume that form data has been posted and any default bindings are initialized. There are a number of methods that can be called from within the process() method to do useful WebForm operations. These are discussed in the tutorial example. 3. Optionally, override the addRules() method to specify looping style rules. You'll see in the tutorial that looping rules typically are used to fill in certain types of HTML elements, such as tables, selection lists, checkboxes, etc. </synopsis> <attribute name="formVars"> The variables from 'input' tags defined in the form doing the POST. </attribute> <attribute name="fileVars"> The variables that correspond to uploaded files. Everyone will need to let me know if additional APIs are needed for the purpose of working with uploaded files. For now, you will be able to get the contents of the file without trouble, since the <xref module="cgi"/> module already addresses this consideration. </attribute> <attribute name="searchPath"> Where to find any included files. </attribute> <attribute name="prefix"> This is only used if you ask WebForm to bind all entries in formVars as variables. The binding process allows your business logic to make references such as 'self.[prefix][form-var] = ...' or '[var] = self.[prefix][form-var]' instead of having to refer to self.formVars[var] or self.getFormVar(var). Having the prefix makes it possible to minimize the likelihood of clobbering your object's namespace when the bindings are actually made. This particular attribute is initialized to the empty string. To override it, you can use the setPrefix() method in your overridden process() method. </attribute> </documentation> """ def __init__(self, form, defaultVars={}, searchPath=["."], autoDispatch=1, **props): """ <documentation type="constructor"> <synopsis> Initialize the instance. As mentioned, you will not be creating instances of WebForm (nor should you). Instead, make a subclass and delegate initialization from your subclass' __init__ method. </synopsis> <param name="form"> cgi.FieldStorage(), passed down upon initialization by the WebFormDispatcher class. </param> <param name="defaultVars"> a set of variables that represent default values. These values come from a .conf file that matches the class name of the WebForm subclass. The WebFormDispatcher reads the .conf file and creates this for you automagically. </param> <param name="searchPath"> list of directories to be searched for HTML (or any included file being referenced from within your HTML code). This is used by the WriteProcessor instance when generating code from the <xref class="WebForm" method="encode"/> method. </param> <param name="encodeTarget"> The name of the HTML file to be used when generating code. This is initialized to None here but actually is initialized by the WebDispatcher when dynamically creating an instance of any WebForm subclass. </param> </documentation> """ if props.has_key('config_dir'): self.config_dir = props['config_dir'] else: self.config_dir = '.' self.form = form self.argv = sys.argv[:] confVars = self.parseConfFile() self.cookies = [] cookie = self.loadCookie() if cookie != None: self.cookies.append(cookie) self.startingCookieCount = 1 else: self.startingCookieCount = 0 self.formVars = Directory({}) self.formVars.update(defaultVars) self.formVars.update(confVars) self.hiddenVars = [] self.fileVars = Directory({}) self.searchPath = searchPath self.setContentStandard() self.extractFormVariables(form) self.encodeTarget = None self.prefix = "" self.autoDispatch = autoDispatch def extractFormVariables(self, form, depth=0): for var in form.keys(): try: if type(form[var]) == type([]): form_var = form[var][0] else: form_var = form[var] if form_var.filename == None: self.formVars[var] = form_var.value else: VAR_DIR = '/%s' % var self.fileVars[var] = (form_var.filename, form_var.file) self.fileVars.create(var) self.fileVars.cd(var) self.fileVars['filename'] = form_var.filename self.fileVars['file'] = form_var.file self.fileVars.cd('/') if type(form[var]) == type([]): VAR_DIR = '/%s' % var self.formVars.create(var) self.formVars.cd(var) self.formVars[var] = [] varCount = 0 for form_var in form[var]: if form_var.filename == None: self.formVars["%s_%d"%(var,varCount)] = form_var.value self.formVars[var].append(form_var.value) varCount = varCount + 1 self.formVars.cd('/') except: raise "WebFormException", str(var) + "=" + str(form[var]) def getFieldStorage(self): return self.form def parseConfFile(self): # Now load the configuration file for the form. Every form is required # to have one--no exceptions. This allows you to supply (for example) # default values for variables. The WebForm class will actually # register every variable appearing here as an actual attribute of # the WebForm subclass instance. formDefaults = {} try: formId = self.__class__.__name__ configFile = self.config_dir + '/' + formId + '.conf' confParser = ConfigParser.ConfigParser() confParser.read( configFile ) optionList = confParser.options(formId) try: optionList.remove('__name__') except: pass for option in optionList: optionValue = confParser.get(formId, option) formDefaults[option] = optionValue except: # If any problem occurs in the ConfigParser, we are going to # return whatever we were able to get. pass return formDefaults # This method (internal) loads a cookie from the environment. def loadCookie(self): if os.environ.has_key("HTTP_COOKIE"): try: cookie = SimpleCookie() cookie.load(os.environ["HTTP_COOKIE"]) except CookieError: server = smtplib.SMTP('localhost') excf = StringIO.StringIO() traceback.print_exc(file=excf) server.sendmail('*****@*****.**',['*****@*****.**'],\ "Subject: Cookies choked in WebForm processing!\n\n%s\nHTTP_COOKIE looks like:\n%s\n" % (excf.getvalue(), os.environ["HTTP_COOKIE"])) server.quit() return None if len(cookie.keys()): return cookie else: return None else: return None # This method tells you whether any cookies are present int the form. def hasCookies(self): return len(self.cookies) > 0 # This method returns the list of cookies to a client. def getCookies(self): return self.cookies # This method allocates a cookie and links it onto the list of cookies. # It's basically a factory method. def getNewCookie(self): cookie = SimpleCookie() self.cookies.append(cookie) return cookie # This method will tell you whether any cookie can be found that matches # a list of vars. Matching occurs if all of the vars are found. An empty # To use this method, simply pass as many vars as you'd like to check. # e.g. matchCookie('user','key') as in Jason's examples. def matchOneCookie(self,*vars): if len(vars) < 1: return None for cookie in self.cookies: matched = 1 for var in vars: if not cookie.has_key(var): matched = 0 break if matched: return cookie return None def matchAllCookies(self, *vars): if len(vars) < 1: return None L=[] for cookie in self.cookies: matched = 1 for var in vars: if not cookie.has_key(var): matched = 0 break if matched: L.append(cookie) return L def setContentType(self,mimeTypeName): self.contentType = 'Content-type: ' + mimeTypeName + '\n\n' def setContentStandard(self): self.setContentType('text/html') def removeContentHeader(self): self.contentType = None def setSearchPath(self, searchPath): self.searchPath = searchPath def setPrefix(self,prefix): if type(prefix) == type(""): self.prefix = prefix # This method allows you to bind the form variables BY NAME and spare # yourself the agony of having to do self.var = form[var].value calls. # Here we also provide the ability to prepend a prefix to the variable # name. This method will NOT clobber any pre-existing binding in this # object (self). # # To make sure everyone understands what's going on here: # Suppose your form has some variables. Variables come from various # tags, such as <INPUT name="someVar" value="someValue">. After this # call, your Form instance (or subclass) will have self.someVar # (or self.<prefix>someVar) as an attribute. def bindVars(self, prefix=None): """ <documentation type="method"> <synopsis> This method will take all of the entries defined in <xref class="WebForm" attribute="formVars">formVars</xref> and make actual instance variables in the current object using Python's setattr() method. The name of the instance variable will be whatever is contained in <xref class="WebForm" attribute="prefix"/> followed by the actual name appearing in the 'input' tag from the form. As these variables are effectively 'cached' in the current object, the companion routine <xref class="WebForm" method="flushVars"/> must be called to ensure the variables are actually written through for the next form (usually needed for processing hidden variables). </synopsis> </documentation> """ if not prefix: prefix = self.prefix for var in self.formVars.keys(): if not self.__dict__.has_key(prefix + var): setattr(self,prefix + var,self.formVars[var]) def flushVars(self, prefix=None): """ <documentation type="method"> <synopsis> This method writes all of the instance variables previously bound to the current object back to <xref class="WebForm" attribute="formVars"/>. Python's getattr() is used to find all such variables (as well as any new variables that may have been added by the <xref class="WebForm" method="addFormVar"/> method. </synopsis> </documentation> """ if not prefix: prefix = self.prefix for var in self.formVars.keys(): if self.__dict__.has_key(prefix + var): self.formVars[var] = getattr(self,prefix + var) def addVars(self, env): """ <documentation type="method"> <synopsis> This method allows you to take a dictionary of bindings and add them to <xref class="WebForm" attribute="formVars"/> This can be particularly useful for dumping the result of a database selection, a dynamically' generated list of options, etc. </synopsis> <param name="env"> The dictionary of bindings. </param> </documentation> """ for var in env.keys(): self.formVars[var] = env[var] def addVar(self, name, value): """ <documentation type="method"> <synopsis> This method allows you to take a dictionary of bindings and add them to <xref class="WebForm" attribute="formVars"/> This can be particularly useful for dumping the result of a database selection, a dynamically' generated list of options, etc. </synopsis> <param name="env"> The dictionary of bindings. </param> </documentation> """ self.formVars[name] = value def markHidden(self,var): """ <documentation type="method"> <synopsis> This method allows you to take a dictionary of bindings and add them to <xref class="WebForm" attribute="formVars"/> This can be particularly useful for dumping the result of a database selection, a dynamically' generated list of options, etc. </synopsis> <param name="env"> The dictionary of bindings. </param> </documentation> """ if self.formVars.has_key(var): self.hiddenVars.append(var) def getFormVar(self, var): """ <documentation type="method"> <synopsis> This method allows you to take a dictionary of bindings and add them to <xref class="WebForm" attribute="formVars"/> This can be particularly useful for dumping the result of a database selection, a dynamically' generated list of options, etc. </synopsis> <param name="env"> The dictionary of bindings. </param> </documentation> """ if self.formVars.has_key(var): return self.formVars[var] else: return None def getFormVarDirectory(self): return self.formVars def getFileVarDirectory(self): return self.formVars def getFileName(self, var): try: VAR_DIR = '/%s' % var self.fileVars.cd(var) fileName = self.fileVars['filename'] self.fileVars.cd('/') return fileName except: return None def getFileHandle(self, var): try: VAR_DIR = '/%s' % var self.fileVars.cd(var) fileHandle = self.fileVars['file'] self.fileVars.cd('/') return fileHandle except: return None def process(self): """ <documentation type="method"> <synopsis> This method is effectively an NOP. Your subclass should override this method to do some useful business logic, such as querying the database, defining variables to fill in dynamically generated elements, etc. </synopsis> </documentation> """ pass def setEncodeFileName(self, fileName): """ <documentation type="method"> <synopsis> This allows you to change what web page is going to come up next. It is usually a reference to an HTML file, although it does not have to be, since WebForm always makes sure to generate a content HTML header when doing code generation. </synopsis> <param name="fileName"> The top-level file to be used for doing code generation </param> </documentation> """ self.encodeTarget = fileName def encode(self, emitStrategy=Emitter.Emitter(), text=None): """ <documentation type="method"> <synopsis> Generate the code after the business logic from your subclass' <xref class="WebForm" method="process"/> method is executed. </synopsis> <param name="additionalVars"> Any last-minute bindings you wish to establish. Generally, you should use the methods <xref class="WebForm" method="addFormVar"/> and <xref class="WebForm" method="addFormVars"/> to make additional bindings from within your subclass' <xref class="WebForm" method="process"/> method. </param> </documentation> """ # Check whether the strategy was specified by name # Construct object of that type if possible. # If not, use StringEmitter. if type(emitStrategy) == type(''): emitStrategy = Emitter.createEmitter(emitStrategy) # If the emitStarategy is not a proper subclass of Emitter, # replace with a StringEmitter instance. if not isinstance(emitStrategy, Emitter.Emitter): emitStrategy = Emitter.Emitter() newEnv = self.formVars.copy() #for var in additionalVars.keys(): # newEnv[var] = additionalVar[var] if self.encodeTarget != None: if self.autoDispatch: # If there were incoming cookies, we only write # the *new* cookies. self.startingCookieCount can only # be 0 or 1, based on the condition in __init__(). for cookie in self.cookies[self.startingCookieCount:]: emitStrategy.emit(`cookie` + '\n') # Content goes next. if self.contentType: emitStrategy.emit(self.contentType) # Emit any "initial" text (i.e. stuff to be prepended, usually # from stray print statements in the process() method. if text: emitStrategy.emit(text) # This is the actual content, i.e. rendering of the page. wp = WriteProcessor.WriteProcessor(self.encodeTarget, \ self.searchPath, newEnv, \ emitStrategy) self.addRules(wp) wp.process() # else: # should probably encode to standard output by default... return emitStrategy.getResult() def addFormVarRule(self,wp): """ <documentation type="method"> <synopsis> This rule allows you to generate a nice looking table of all variables defined in the WebForm. Should your subclass provide its own rules, using the <xref class="WebForm" method="addRules"/> method, it will be necessary to call this method explicitly or the <xref class="WebForm" method="addDefaultVars"/> method. </synopsis> <param name="wp"> The WriteProcessor instance being used for code generation (supplied by the <xref class="WebForm" method="encode"> method, which is called immediately after the <xref class="WebForm" method="process"> method. </param> </documentation> """ env = {} for var in self.formVars.keys(): varName = cgi.escape(var) varValue = self.formVars[varName] varType = type(varValue) varType = cgi.escape(`varType`) varValue = cgi.escape(`varValue`) env[varName] = (varType,varValue) if len(env) == 0: env['N/A'] = ('N/A','N/A') wp.addLoopingRule('WebForm_VarName',\ '(WebForm_VarType, WebForm_VarValue)', env) def addHiddenVarRule(self,wp): """ <documentation type="method"> <synopsis> This rule allows you to add all hidden variables (easily) to the next WebForm. Should your subclass provide its own rules, using the <xref class="WebForm" method="addRules"/> method, it will be necessary to call this method explicitly or the <xref class="WebForm" method="addDefaultVars"/> method. </synopsis> </documentation> """ env = {} for var in self.hiddenVars: env[var] = self.formVars[var] if len(env) == 0: env['N/A'] = 'N/A' wp.addLoopingRule('WebForm_HiddenVarName','WebForm_HiddenVarValue',\ env) def addDefaultRules(self,wp): """ <documentation type="method"> <synopsis> This will add rules for emitting hidden variables easily and dumping all variables for the purpose of debugging. This is equivalent to calling both <xref class="WebForm" method="addHiddenVarRule"/> and <xref class="WebForm" method="addFormVarRule"/>. The same comments apply when you override the <xref class="WebForm" method="addRules"/> method. </synopsis> <param name="wp"> The WriteProcessor object being used, which is supplied automatically for you. </param> </documentation> """ self.addFormVarRule(wp) self.addHiddenVarRule(wp) def addRules(self,wp): """ <documentation type="method"> <synopsis> Subclasses will override this method to supply their own rules. When overriding this method, the <xref class="WebForm" method="addDefaultRules"> method should be called to establish some useful default rules that are designed to facilitate debugging and propagation of hidden variables. </synopsis> <param name="wp"> The WriteProcessor object being used, which is supplied automatically for you. </param> </documentation> """ self.addDefaultRules(wp)