def validate(self): self.row1Validator = validator.Validator(self.lineEdit_row1, self.pushButton_save, self.statusbar) self.row1Validator.numberValidator() if not self.statusBarIsEmpty(): return self.row2Validator = validator.Validator(self.lineEdit_row2, self.pushButton_save, self.statusbar, self.lineEdit_row1) self.row2Validator.rowValidator() if not self.statusBarIsEmpty(): return self.col1Validator = validator.Validator(self.lineEdit_col1, self.pushButton_save, self.statusbar) self.col1Validator.letterValidator() if not self.statusBarIsEmpty(): return self.col2Validator = validator.Validator(self.lineEdit_col2, self.pushButton_save, self.statusbar, self.lineEdit_col1) self.col2Validator.colValidator() if not self.statusBarIsEmpty(): return return self.row1Validator.isValid() or \ self.row2Validator.isValid() or \ self.col1Validator.isValid() or \ self.col2Validator.isValid()
def run(session): batcher = preprocessing.Batcher(config.SUBSAMPLE_THRESHOLD, config.TEST_MODE) num_batches = batcher.num_batches(config.BATCH_SIZE) graph = graph_fns.build_graph( vocab_size=batcher.vocab_size(), num_embedding_units=config.NUM_EMBEDDING_UNITS, num_negative_samples=config.NUM_NEGATIVE_SAMPLES, ) session.run(tf.global_variables_initializer()) run_info = RunInfo( session=session, graph=graph, saver=tf.train.Saver(), batcher=batcher, validator=validator.Validator(batcher.vocab_size(), graph.embedding_matrix), batch_size=config.BATCH_SIZE, window_size=config.WINDOW_SIZE, batches_per_epoch=num_batches, batches_per_logging=int(num_batches * config.LOGGING_FREQUENCY), batches_per_save=int(num_batches * config.SAVING_FREQUENCY), batches_per_validation=int(num_batches * config.VALIDATION_FREQUENCY), ) for epoch_idx in range(1, config.NUM_EPOCHS + 1): run_epoch(run_info, epoch_idx)
def check_line_for_match(entities_list, gnd_list): all_keys = set([]) all_keys.update(gnd_list.keys()) all_keys.update(entities_list.keys()) for key in all_keys: gnd_value = gnd_list.get(key, 'O') entity_value = entities_list.get(key, 'O') main_value = gnd_value if gnd_value == 'O': main_value = entity_value if (main_value not in parking_label_dict.keys()): obj_label = validator.Validator(main_value) else: obj_label = parking_label_dict[main_value] if gnd_value == 'O': obj_label.FN = obj_label.FN + 1 else: if gnd_value == entity_value: obj_label.TP = obj_label.TP + 1 else: obj_label.FP = obj_label.FP + 1 parking_label_dict[main_value] = obj_label
def generate(self): mazeSize = (self.mazeSizeRow.get(), self.mazeSizeCol.get()) print ("Maze size - ", mazeSize) multiplePaths = self.multiplePaths.get() print ("Multiple paths - ", multiplePaths) startPos = (self.startPosX.get() - 1, self.startPosY.get() - 1) print ("Start Position - ", startPos) endPos = (self.endPosX.get() - 1, self.endPosY.get() - 1) print ("End Position - ", endPos) directory = self.directory print ("Directory - ", self.directory) filename = self.filename.get() print ("Filename - ", filename) print("Validating...") val_obj = validator.Validator() result = val_obj.validateInput(self.minMazeSize, mazeSize, startPos, endPos, directory, filename) if not(result is None): msgbox.showerror(title="Error!", message=result) else: print("Success!!!") self.generateMaze(mazeSize, startPos, endPos, directory, filename)
class LoginHandler(render.Handler): validator = validator.Validator() def set_secure_cookie(self, name, val): cookie_val = hash_cookie.make_secure_val(val) self.response.headers.add_header('Set-Cookie', '%s=%s; Path=/' % (name, cookie_val)) def render_front(self, username="", password="", error_login=""): self.render("form_login.html", username=username, password=password, error_login=error_login) def get(self): self.render_front() def post(self): in_username = self.request.get('username') in_password = self.request.get('password') error_login = "******" if self.validator.exist_username( in_username) and self.validator.valid_bbdd_password( in_username, in_password): self.set_secure_cookie('valid', str(in_username)) self.redirect("/blog/welcome") else: self.render_front(in_username, "", error_login)
def setUp(self): self.read = reader.FileReader() self.valid = validator.Validator() self.db = database.DatabaseMaker() self.con = controller.Controller() self.cmd = command_line.DomainCmd(self.con) self.chart = display.PyGal()
def __init__(self, baseURL, searchDate, targetDomain, includeDomainList, nonArchiveOrgDomain): #logging self.logger = logging.getLogger(__name__) #user provided options self.baseURL = baseURL #archive.org's base URL (http(s)://web.archive.org) self.searchDate = searchDate #user's chosen archive date yyyymmddhhmmss self.targetDomain = targetDomain self.includeDomainList = includeDomainList self.nonArchiveOrgDomain = nonArchiveOrgDomain #record any ignored domains so user can refine search if required self.foundDomainsList = list() #tracking crawled links self.crawledList = list() #links already crawled self.savedLinks = list() #save all of the crawled links for later processing #init other vars self.asterixInURL = None #functions for performing basic data validation self.dataCheck = validator.Validator() #searching archive.org can be very slow, let user know program is still working using basic progress bar self.progressCounter = 1 #functions for extracting data from URLs self.urlDataExtractor = urlDataExtractor.URLDataExtractor()
def assert_valid(self, spec, schema): try: v = validator.Validator(spec, schema) v.validate() return v except SpecError, err: self.fail(err)
def test_nested(self): data = { "title": "Master Linux with Maher", "author": { "name": "Maher", "dob": "11-01-1996", "email": "*****@*****.**", "co_authors": ["Monica", "Ziad"] }, "pages": 120, "creation_date": "15/12/2015" } rules = { "title": "string", "author": "array", "author.name": "string", "author.dob": "date", "author.email": "email", "author.co_authoers": "array", "pages": "number", "creation_date": "date" } valid = vld.Validator(data,rules) self.assertEqual(valid.getFailedAttributes(),None)
def test_custom(self): attr = { "dob": "Date of Birth", "author.name": "Name of Author" } errs = { "dob": "Some custom date err", "author.name": "Another custom err" } data = { "dob": 20, "author": { "name": 21 } } rules = { "dob": "date", "author": "array", "author.name": "string" } valid = vld.Validator(data,rules,customAttributes = attr,customErrorMessage = errs) for attr in list(attr.values()): self.assertIn(attr, valid.getFailedAttributes()) for err in list(errs.values()): self.assertIn(err,valid.getErrorMessages())
def validate(): """ Run ESLint validation using settings from the current TextMate environment. Return a list of issues. """ eslint_command = os.environ.get('TM_JAVASCRIPT_ESLINT_ESLINT', 'eslint') the_validator = validator.Validator(eslint_command) filename = os.environ.get('TM_FILEPATH', None) input_is_html = not os.environ['TM_SCOPE'].startswith('source.js') line_offset = int(os.environ.get('TM_INPUT_START_LINE', 1)) - 1 cwd = get_cwd() try: issues = the_validator.run(filename=filename, input_is_html=input_is_html, line_offset=line_offset, cwd=cwd) except validator.ValidateError as err: context = { 'BASE_PATH': BASE_PATH, 'timestamp': time.strftime('%c'), 'errorMessage': err.message, } if err.path: context['searchPath'] = err.path html = ASHES_ENV.render('error_eslint_path.html', context) else: html = ASHES_ENV.render('error_eslint_other.html', context) print(html) sys.exit() return issues
def fix(): """ Run the eslint --fix command against the current file. """ if 'TM_FILEPATH' not in os.environ: # ignore if file is not saved return if not os.environ['TM_SCOPE'].startswith('source.js'): # refuse to run against HTML-embedded JavaScript return eslint_command = os.environ.get('TM_JAVASCRIPT_ESLINT_ESLINT', 'eslint') the_validator = validator.Validator(eslint_command) filename = os.environ['TM_FILEPATH'] cwd = get_cwd() try: the_validator.fix(filename, cwd) except validator.ValidateError as err: context = { 'BASE_PATH': BASE_PATH, 'timestamp': time.strftime('%c'), 'errorMessage': err.message, } if err.path: context['searchPath'] = err.path html = ASHES_ENV.render('error_eslint_path.html', context) else: html = ASHES_ENV.render('error_eslint_other.html', context) print(html) sys.exit() mate = os.environ['TM_MATE'] subprocess.call([mate, '--clear-mark=warning', filename])
def assert_invalid(self, spec, schema, expected_error_type, expected_message): try: v = validator.Validator(spec, schema) v.validate() self.fail("Expected failed validation.") return except SpecError, err: self.assertTrue(expected_error_type is SpecError, "Error type should be SpecError")
def main(): options, args = parse_options() known_issues = create_known_issues(options.idl_syntax_known_issues) error_counts = [0] skipped_error_counts = [0] def report_error(rule, target, target_type, error_message): error_counts[0] += 1 target_path = target_type.get_target_path(target) if should_suppress_error(known_issues, rule, target_path): skipped_error_counts[0] += 1 else: debug_infos = target_type.get_debug_info_list(target) sys.stderr.write("violated rule: {}\n".format( rule.__class__.__name__)) sys.stderr.write("target path : {}\n".format(target_path)) for i, debug_info in enumerate(debug_infos): if i == 0: sys.stderr.write("related files: {}\n".format( str(debug_info.location))) else: sys.stderr.write(" {}\n".format( str(debug_info.location))) sys.stderr.write("error message: {}\n\n".format(error_message)) # Register rules rule_store = validator.RuleStore() validator.rules.register_all_rules(rule_store) # Validate database = web_idl.file_io.read_pickle_file(options.web_idl_database) validator_instance = validator.Validator(database) validator_instance.execute(rule_store, report_error) # Report errors if error_counts[0] - skipped_error_counts[0] > 0: sys.exit("Error: Some IDL files violate the Web IDL rules") # Create a file for the purpose of timestamp of a successful completion. if options.output: with open(options.output, mode="w") as file_obj: file_obj.write("""\ # This file was created just for the purpose of timestamp of a successful # completion, mainly in order to corporate with a build system. """) file_obj.write("Command line arguments:\n") file_obj.write(" --web_idl_database = {}\n".format( options.web_idl_database)) file_obj.write(" --idl_syntax_known_issues = {}\n".format( options.idl_syntax_known_issues)) file_obj.write("Results:\n No new error\n")
def getPost(self): """tworzy pole z obiektem Post - pusty dla nowej wiadomości lub konkretny dla danej wiadomości""" if self.insert: self.post = database.Post() else: key = db.Key(self.id) postsTem = database.Post.gql("WHERE __key__ = :1", key) self.post = postsTem.fetch(1)[0] val = validator.Validator() val.loadPost(self.post)
def main(): options, args = parse_options() # Register rules rule_store = validator.RuleStore() validator.rules.register_all_rules(rule_store) # Validate database = web_idl.file_io.read_pickle_file(options.web_idl_database) validator_instance = validator.Validator(database) validator_instance.execute(rule_store)
def test_cascade(self): rules = { "dob" : "required|date", "pages": "required|number|min:5|max:20", "author.name" : "required|string", } data = { "dob": "11-9-1996", "pages": 15, "author": { "name": "asd" } } valid = vld.Validator(data,rules) self.assertEqual(valid.getFailedAttributes(),None)
def test_instance_add_exceptions(self): """ Test that exceptions can be added to an instance's exceptions management lists unless one occurs already in the "other" list, in which case a ValueError is raised. """ a_validator = validator.Validator(1) self.assertEqual(a_validator.pass_exceptions, []) self.assertEqual(a_validator.fail_exceptions, []) # Basic assignment to exception lists is OK. a_validator.pass_exceptions = [IOError] a_validator.fail_exceptions = [TabError] self.assertEqual(a_validator.pass_exceptions, [IOError]) self.assertEqual(a_validator.fail_exceptions, [TabError]) # A second assignment to exception lists results in a list # with two Exceptions. a_validator.pass_exceptions = a_validator.pass_exceptions.append( OSError) a_validator.fail_exceptions = a_validator.fail_exceptions.append( NotImplementedError) self.assertEqual(len(a_validator.pass_exceptions), 2) self.assertTrue(IOError in a_validator.pass_exceptions) self.assertTrue(OSError in a_validator.pass_exceptions) self.assertEqual(len(a_validator.fail_exceptions), 2) self.assertTrue(TabError in a_validator.fail_exceptions) self.assertTrue(NotImplementedError in a_validator.fail_exceptions) # Trying to add an exception that's already in the "other" list # raises a ValueError exception. Check when the list being modified # was previously empty and when it was not; also make sure it doesn't # do anything funky when ValueError is the duplicate exception in # question. a_validator.pass_exceptions = [] a_validator.fail_exceptions = [ValueError] self.assertRaises( # Hmm, this is a property, right? How to do this? Don't think # assertRaises will work, just have to wrap in try and check the # result after. )
def create_connections(self): ''' Create the connection objects from the validators info file and store them as a triple arr[0] = hostname, arr[1] = ip, int(arr[2]) = port ''' f = open('../validators_temp.txt', 'r') for line in f: arr = line.split(' ') if self.hostname == arr[0] and self.address == (arr[1], int( arr[2])): continue else: v = validator.Validator(hostname=arr[0], addr=arr[1], port=int(arr[2]), bind=False) self.connections.append(v) f.close()
def main(): # We keep these global to share state graph between workers spawned by # multiprocess. Passing it every time is slow. global options, xml_file global dfa global worker_validator options, xml_file = ParseOptions() dfa = dfa_parser.ParseXml(xml_file) worker_validator = validator.Validator(validator_dll=options.validator_dll, decoder_dll=options.decoder_dll) assert dfa.initial_state.is_accepting assert not dfa.initial_state.any_byte sys.stderr.write('%d states\n' % len(dfa.states)) num_suffixes = dfa_traversal.GetNumSuffixes(dfa.initial_state) num_instructions = sum( num_suffixes[t.to_state] for t in dfa.initial_state.forward_transitions.values()) sys.stderr.write('%d instructions\n' % num_instructions) tasks = dfa_traversal.CreateTraversalTasks(dfa.states, dfa.initial_state) sys.stderr.write('%d tasks\n' % len(tasks)) pool = multiprocessing.Pool() results = pool.imap_unordered(Worker, tasks) total = 0 num_valid = 0 node_cache = trie.NodeCache() full_trie = node_cache.empty_node # The individual workers create subtries that we merge in and compress here. for count, valid_count, sub_trie, in results: total += count num_valid += valid_count full_trie = node_cache.Merge(full_trie, sub_trie) sys.stderr.write('%.2f%% completed\n' % (total * 100.0 / num_instructions)) sys.stderr.write('%d instructions were processed\n' % total) sys.stderr.write('%d valid instructions\n' % num_valid) trie.WriteToFile(options.trie_path, full_trie)
def main(): options, args = parse_options() def report_error(rule, target, debug_info, error_message): sys.stderr.write("{}\n{}\n".format(str(debug_info.location), error_message)) # Register rules rule_store = validator.RuleStore() validator.rules.register_all_rules(rule_store) # Validate database = web_idl.file_io.read_pickle_file(options.web_idl_database) validator_instance = validator.Validator(database) error_counts = validator_instance.execute(rule_store, report_error) # Report errors if error_counts > 0: sys.exit("Error: Some IDL files violate the Web IDL rules")
def main(): parser = optparse.OptionParser(__doc__) parser.add_option('-b', '--bitness', type=int, help='The subarchitecture: 32 or 64') parser.add_option('-a', '--gas', help='Path to GNU AS executable') parser.add_option('-d', '--objdump', help='Path to objdump executable') parser.add_option('-v', '--validator_dll', help='Path to librdfa_validator_dll') parser.add_option('-o', '--out', help='Output file name (instead of sys.stdout') (options, args) = parser.parse_args() if options.bitness not in [32, 64]: parser.error('specify -b 32 or -b 64') if not (options.gas and options.objdump and options.validator_dll): parser.error('specify path to gas, objdump, and validator_dll') if options.out is not None: out_file = open(options.out, "w") else: out_file = sys.stdout validator_inst = validator.Validator(validator_dll=options.validator_dll) try: for file in args: ProcessSuperinstructionsFile(file, validator_inst, options.bitness, options.gas, options.objdump, out_file) finally: if out_file is not sys.stdout: out_file.close()
def test_validator_1(self): """ Test that initialization and check works properly for a variety of criteria and targets. """ validator_1 = validator.Validator(1) # Confirm that exactly one parameter is required. self.assertRaises(TypeError, validator_1.check) self.assertRaises(TypeError, validator_1.check, 1, 2) # Confirm that checks that should return True, do so. self.assertTrue(validator_1.check(1)) self.assertTrue(validator_1.check(True)) # Confirm that checks that should return False, do so. self.assertFalse(validator_1.check(None)) self.assertFalse(validator_1.check(0)) self.assertFalse(validator_1.check('a')) self.assertFalse(validator_1.check([])) self.assertFalse(validator_1.check([1, 2, 3])) self.assertFalse(validator_1.check(False))
def test_basic(self): data = { "username": "******", "password": "******", "email": "*****@*****.**", "creditcard": { "id": 82325, "name": "mr. maher", "age": 21, }, "creation": "10/12/2009", "dob": "12-12-1996", "phone": "+970200200200" } rules = { "username": "******", "password": "******", "email": "required|email", "credicard": "array", "creditcard.id": "number", "creditcard.name": "string", "creditcard.age": "number|min:18", "creation": "required|date", "dob":"date", "phone":"phone" } valid = vld.Validator(data,rules) print(valid.wrong) self.assertEqual(valid.getFailedAttributes(),None) data["username"] = 123 valid.updateValidation(data,rules) self.assertEqual(valid.getFailedAttributes(),["username"]) del data["password"] valid.updateValidation(data,rules) for asserts in ["username","password"]: self.assertIn(asserts,valid.getFailedAttributes())
def addDataset(self, identifier, doc=None): """Adds a dataset to the graph. Parameters: ----------- identifier : str Non-urlencoded DataOne identifier doc : XML Element An XML element containing a result from the Solr index which contains a number of fields relating to a dataset. Returns: None """ if self.model is not None: raise Exception( "Model existed when addDataset was called. This means the last Model wasn't cleaned up after finishing." ) self.createModel() # Get Solr fields if they weren't passed in if doc is None: doc = dataone.getSolrIndexFields(identifier) identifier = dataone.extractDocumentIdentifier(doc) identifier_esc = urllib.unquote(identifier).decode('utf8') dataset_node = RDF.Uri(self.graph.ns['d1dataset'] + identifier_esc) self.add(dataset_node, 'rdf:type', 'geolink:Dataset') # Delete if dataset is already in graph if self.datasetExists(identifier): logging.info( "Dataset with identifier %s already exists. Deleting then re-adding.", identifier) self.deleteDataset(identifier) scimeta = dataone.getScientificMetadata(identifier) records = processing.extractCreators(identifier, scimeta) vld = validator.Validator() # Add Dataset triples first, we'll use them when we add people # to match to existing people by the current dataset's 'obsoletes' field self.addDatasetTriples(dataset_node, doc) # Add people and organizations people = [p for p in records if 'type' in p and p['type'] == 'person'] organizations = [ o for o in records if 'type' in o and o['type'] == 'organization' ] # Always do organizations first, so peoples' organization URIs exist for organization in organizations: organization = vld.validate(organization) self.addOrganization(organization) for person in people: person = vld.validate(person) self.addPerson(person) # Commit or reject the model here if self.model is None: raise Exception( "Model was None. It should have been an RDF.Model.") self.insertModel() self.model = None # Remove the model since we're done return
import validator as validator import recipe.steps.model as steps_model validator = validator.Validator() steps = steps_model.Steps() class Validator(object): @staticmethod def is_object_id(_id): validator.is_object_id(_id) return True @staticmethod def is_index_valid(_id, index): validator.is_int("index", index) validator.is_between_x_y("index", int(index), 0, steps.get_steps_length(_id)) return True
if options.bitness not in [32, 64]: parser.error('specify -b 32 or -b 64') if len(args) != 1: parser.error('specify one xml file') (xml_file, ) = args return options, xml_file options, xml_file = ParseOptions() # We are doing it here to share state graph between workers spawned by # multiprocess. Passing it every time is slow. dfa = dfa_parser.ParseXml(xml_file) worker_validator = validator.Validator(validator_dll=options.validator_dll, decoder_dll=options.decoder_dll) def main(): assert dfa.initial_state.is_accepting assert not dfa.initial_state.any_byte print(len(dfa.states), 'states') num_suffixes = dfa_traversal.GetNumSuffixes(dfa.initial_state) # We can't just write 'num_suffixes[dfa.initial_state]' because # initial state is accepting. total_instructions = sum( num_suffixes[t.to_state] for t in dfa.initial_state.forward_transitions.values())
class SignUpHandler(render.Handler): validator = validator.Validator() def set_secure_cookie(self, name, val): cookie_val = hash_cookie.make_secure_val(val) self.response.headers.add_header('Set-Cookie', '%s=%s; Path=/' % (name, cookie_val)) def render_front(self, username="", password="", verify="", error_username="", error_password="", error_verify="", email="", error_email=""): self.render("form_signup.html", username=username, password=password, verify=verify, error_username=error_username, error_password=error_password, error_verify=error_verify, email=email, error_email=error_email) def get(self): self.render_front() def post(self): in_username = self.request.get('username') in_password = self.request.get('password') in_verify = self.request.get('verify') in_email = self.request.get('email') err_msg = { 'error_username': "", 'error_password': "", 'error_verify': "", 'error_email': "" } is_valid_username = self.validator.valid_username(in_username) if (not is_valid_username): err_msg['error_username'] = self.validator.MSG_ERR_USER else: exist_user = self.validator.exist_username(in_username) if exist_user: err_msg['error_username'] = self.validator.MSG_EXIST_USER is_valid_password = self.validator.valid_sign_password(in_password) is_valid_match_pwd = self.validator.valid_match_pwd( in_password, in_verify) if (not is_valid_password): err_msg['error_password'] = self.validator.MSG_ERR_PWD else: if (not is_valid_match_pwd): err_msg['error_verify'] = self.validator.MSG_ERR_V_PWD is_valid_email = self.validator.valid_email(in_email) if (not is_valid_email): err_msg['error_email'] = self.validator.MSG_ERR_EMAIL if err_msg['error_username'] == "" and err_msg[ 'error_password'] == "" and err_msg[ 'error_verify'] == "" and err_msg['error_email'] == "": password_hash = salt.make_pw_hash(in_username, in_password) u = user.User(username=in_username, password=password_hash.split(",")[0], salt=password_hash.split(",")[1]) u.put() self.set_secure_cookie('valid', str(in_username)) self.redirect("/blog/welcome") else: self.render_front(in_username, "", "", err_msg['error_username'], err_msg['error_password'], err_msg['error_verify'], in_email, err_msg['error_email'])
def make_insert(self): if not self.user: self.response.out.write('<html><body><head><meta http-equiv="content-type" content="text/html; charset=utf-8" /></head><h1> Nie jesteś zalogowany. <br/><a href="/news"> Powrót </a> </h1><body/><html/>') return #exit() self.getPost() #wspólne dla obu akcji self.post.title = self.request.get('title') self.post.body = db.Text(self.request.get('body')) val = validator.Validator() val.validatePost(self.post) #dodawanie obrazków - jeżeli nie są puste if self.request.get('img0'): img0 = self.request.get('img0') whatResize = self.check_resize(img0) if whatResize is "w": img0 = images.resize(img0,width=520) elif whatResize is "h": img0 = images.resize(img0,height=350) if img0: self.post.img0 = db.Blob(img0) if self.request.get('img1'): img1 = self.request.get('img1') whatResize = self.check_resize(img1) if whatResize is "w": img1 = images.resize(img1,width=520) elif whatResize is "h": img1 = images.resize(img1,height=350) if img1: self.post.img1 = db.Blob(img1) if self.request.get('img2'): img2 = self.request.get('img2') whatResize = self.check_resize(img2) if whatResize is "w": img2 = images.resize(img2,width=520) elif whatResize is "h": img2 = images.resize(img2,height=350) if img2: self.post.img2 = db.Blob(img2) if self.request.get('img3'): img3 = self.request.get('img3') whatResize = self.check_resize(img3) if whatResize is "w": img3 = images.resize(img3,width=520) elif whatResize is "h": img3 = images.resize(img3,height=350) if img3: self.post.img3 = db.Blob(img3) #data d = datetime.date.today() month = [' stycznia ',' lutego ',' marca ',' kwietnia ',' maja ',' czerwca ',' lipca ',' sierpnia ',' września ',' października ',' listopada ',' grudnia '] if self.insert: authorRes = database.Authors.gql("WHERE email =:1",self.user.email()) self.post.author = authorRes.fetch(1)[0].key() departRes = database.Department.gql("WHERE department = :1", self.department) self.post.department = departRes.fetch(1)[0].key() self.post.creation_date = datetime.datetime.utcnow() self.post.creation_dateStr = str(d.day) self.post.creation_dateStr += month[d.month -1] self.post.creation_dateStr += str(d.year) self.post.edit_dateStr = "" else: self.post.edit_dateStr = str(d.day) self.post.edit_dateStr += month[d.month -1] self.post.edit_dateStr += str(d.year) self.post.put() self.redirect('/pieceofnews?&id=%s' % (self.post.key()) )
def setUp(self): self.read = reader.FileReader() self.valid = validator.Validator() self.db = database.DatabaseMaker()