def post(self): json_data = request.get_json(force=True) # get recipient from the json_data fields = {} fields["identity"] = json_data['email'] fields["name"] = json_data['name'] recipient = Recipient(fields) # get the template from db template_col = DAO().get_collection('certificate_template') template = template_col.find_one({}, {"_id": 0}) # get deep copy of the template as cert cert = deepcopy(template) # get the config config = Config().get() # call instantiate_assertion and instantiate_recipient uid = str(uuid.uuid4()) issued_on = helpers.create_iso8601_tz() instantiate_assertion(cert, uid, issued_on) instantiate_recipient(cert, recipient, config.additional_per_recipient_fields, config.hash_emails) # get the config config = Config().get() # post it to blockchain # first instantiate handlers chain = config.chain if chain == Chain.ethereum_mainnet or chain == Chain.ethereum_ropsten: from cert_issuer.blockchain_handlers import ethereum certificate_batch_handler, transaction_handler, connector = ethereum.instantiate_blockchain_handlers( config, False) else: from cert_issuer.blockchain_handlers import bitcoin certificate_batch_handler, transaction_handler, connector = bitcoin.instantiate_blockchain_handlers( config, False) certificate_batch_handler.certificates_to_issue = [cert] issuer = Issuer(certificate_batch_handler=certificate_batch_handler, transaction_handler=transaction_handler, max_retry=config.max_retry) tx_id = issuer.issue(config.chain) issued_cert = certificate_batch_handler.certificates_to_issue[0] issued_cert_to_insert = deepcopy(issued_cert) cert_col = DAO().get_collection("certificates") cert_col.insert_one(issued_cert_to_insert) return issued_cert
def test_empty(self): data1 = DAO([]) assert data1.is_empty() testDataContent = [ '648:abcdefghi', '517:QjhWkizN5t', '323:dwcIY99gTN1', '653:UlfY2UvMfeuX' ] data2 = DAO(testDataContent) assert not data2.is_empty()
def get(self, inp): query = inp["query"] if("city" not in query): return 418, "Impossible de trouver la ville ou mauvais appel (._. )" if("act" in query): r = DAO().guess_City_byGActivity(query["city"], query["act"]) else: r = DAO().guess_input_positions(query["city"]) return { "code": 200, "header": [], "content": "application/json", "res": str.encode(JSONDecEncoder().encode(r)) }
def unzip(standardization_input): dao = DAO() pubMedRetrievals = dao.findAllForUnzip(PubMedRetrieval) for pubMedRetrieval in pubMedRetrievals: print pubMedRetrieval.filename file = os.path.join( standardization_input + "/" + pubMedRetrieval.download_path, pubMedRetrieval.filename) xml_file_path = file + ".xml" if os.path.isfile(file): with open(xml_file_path, 'w') as xml_file: with gzip.open( os.path.join( standardization_input + "/" + pubMedRetrieval.download_path, pubMedRetrieval.filename), 'rb') as f: file_content = f.read() xml_file.write(file_content) xml_file.flush() xml_file.close() print pubMedRetrieval.filename + " unzip" pubMedRetrieval.unzip = 1 pubMedRetrieval.unzip_datetime = datetime.now() pubMedRetrieval.unzip_path = pubMedRetrieval.download_path dao.save(pubMedRetrieval) else: print("The file " + file + " not exist, please review and download again ")
def update_value(): try: column = request.form.get("column", None) value = request.form.get(column, None) surgeon_id = request.form.get("surgeon_id", None) if value and surgeon_id: dao = DAO() success = dao.update(column, surgeon_id, value) return jsonify(success) # if column == "training": # value = json.loads(value) # dao = DAO() # success = dao.update_training(value, surgeon_id) # return jsonify(success) # else: # dao = DAO() # success = dao.update(column, surgeon_id, value) # return jsonify(success) else: pass except Exception as e: raise e return jsonify({"Error": "Something went wrong"})
def test_rate_db(self): dao = DAO(self.dsn) registry = Registry('test') registry.save_data("% BTG 1", dao) self.assertEqual(dao.get_member('test'), [('test', 600, None, None)]) self.assertEqual(dao.get_conditions(), [('test', 1, 'BTG', '%', 1.0)])
def get(self, id): ''' verify a certificate according to id ''' cert_col = DAO().get_collection("certificates") cert = cert_col.find_one({'id': URN_UUID_PREFIX + id}, {'_id': 0}) return verify_certificate_json(cert)
def get(self): ''' return all the certs ''' cert_col = DAO().get_collection("certificates") certs = cert_col.find({}, {'_id': 0}) return list(certs)
def insert_csv_to_db(csvfile, siteName='Ebay'): db = Database() dao = DAO(db) item_ = Item() brand_ = Brand() category_ = Category() with open(csvfile, 'r') as file: f = csv.reader(file,delimiter = ',') for row in f: try: item_.category = classify(item_.imagePath, CATEGORY) if item_.category is None: raise ValueError("Category cannot be Null") item_.site = siteName item_.itemName = row[1] item_.itemPrice = row[2] item_.url = row[0] item_.imagePath = row[3] item_.brand = 'NULL' brand_.brandName = 'NULL' category_.catName = item_.category category_.catCode = '' dao.insert_item(item=item_, brand=brand_, category=category_) except Exception as e: print("Error{}".format(e) ) pass
def main(): st = SensorTag("B0:B4:48:C9:99:06") if not st.connected: print("Could not connect to sensortag") return #Wait for initial data gathering to be done time.sleep(1) db = DAO("sensor_data.sqlite") jb = JSONBuilder(db) data = None while (True): db.open(True) data = st.read(uuid_constants.IRTEMP_DATA_UUID) obj_temp = convert.irtemp(data[0:len(data) // 2]) amb_temp = convert.irtemp(data[len(data) // 2:]) db.store_irtemp(data, obj_temp, amb_temp) print("--------------------IR Temperature Sensor------------------") print("IR Object Temp = " + str(round(obj_temp, 2)) + " C, IR Ambient Temp = " + str(round(amb_temp, 2)) + " C") data = st.read(uuid_constants.HUMID_DATA_UUID) humid_temp = convert.humid_temp(data[0:len(data) // 2]) humidity = convert.humid(data[len(data) // 2:]) db.store_humid(data, humid_temp, humidity) print("-----------------------Humidity Sensor---------------------") print("Temperature = " + str(round(humid_temp, 2)) + " C, Humidity = " + str(round(humidity, 2)) + " %RH") data = st.read(uuid_constants.BARO_DATA_UUID) baro_temp = convert.baro(data[0:len(data) // 2]) baro_pres = convert.baro(data[len(data) // 2:]) db.store_baro(data, baro_temp, baro_pres) print("--------------------------Barometer------------------------") print("Temperature = " + str(round(baro_temp, 2)) + " C, Barometric Pressure = " + str(round(baro_pres, 2)) + " hPa/millibars") data = st.read(uuid_constants.OPTI_DATA_UUID) lux = convert.opti(data) db.store_opti(data, lux) print("-----------------------Optical Sensor----------------------") print("Light = " + str(round(lux, 2)) + " Lux") db.close() db.open(False) jb.buildFile("current") jb.buildFile("history") db.close() cron_jobs.reset_alarms() time.sleep(READING_DELAY) db.close()
def dbimport(sname, dbname, uname, upass): """Import data from db using DAO""" dao = DAO(sname, dbname, uname, upass) if dao.connect(): dao.query() dao.close() rdict = dao.get() return rdict
def post(self, inp): if("city" in inp["data"].keys()): return { "code": 200, "header": [], "content": "application/json", "res": str.encode(JSONDecEncoder().encode(DAO().get_City_Pos(inp["data"].getvalue("city")))) } return 418, "wait !!"
def tos(): try: dao = DAO() tos_content = dao.get_page_content("tos") return render_template("tos.html", content = tos_content) except Exception as e: return "Your request cannot be processed"
def init_certificate_template(config): template = create_certificate_template(config) col = DAO().get_collection("certificate_template") if col.find_one(): _id = col.find_one()["_id"] selector = {"_id": _id} col.replace_one(selector, template) else: col.insert_one(template) print(template)
def why_acms(): try: dao = DAO() why_acms_content = dao.get_page_content("why_acms") return render_template("why_acms.html", content = why_acms_content) except Exception as e: return "Your request cannot be processed"
def about_us(): try: dao = DAO() about_us_content = dao.get_page_content("about_us") return render_template("about_us.html", content = about_us_content) except Exception as e: return "Your request cannot be processed"
def init_issuer_id(config): issuer_id = generate_issuer_file(config) col = DAO().get_collection("issuer_id") if col.find_one(): _id = col.find_one()["_id"] selector = {"_id": _id} col.replace_one(selector, issuer_id) if not col.find_one(): col.insert_one(issuer_id) print(issuer_id)
def getCommunityCode(communityName): dao = DAO() querySQL = "SELECT * FROM community" results = dao.query(querySQL) for result in results: if result[1] == communityName: return result[2] return None
def get(self, inp): query = inp["query"] if ("city" not in query): return 418, "Impossible de trouver les installations sans ville ou mauvais appel (._. )" if ("city" in query and "range" in query and "act" in query): r = DAO().get_installation(query["city"], query["act"], int(query["range"])) else: if ("city" in query and "range" in query and "act" not in query): r = DAO().get_installation(query["city"], "", int(query["range"])) else: if ("city" in query and "range" not in query and "act" in query): r = DAO().get_installation(query["city"], query["act"]) else: # "city" in query and "range" not in query and "act" not in query r = DAO().get_installation(query["city"], "") return { "code": 200, "header": [], "content": "application/json", "res": str.encode(JSONDecEncoder().encode(r)) }
def update_checkbox(): try: checked = request.form.get("checked", None) _id = request.form.get("surgeon_id", None) if _id: dao = DAO() doit = dao.update("uneditable", _id, int(checked)) return jsonify(doit) except Exception as e: print(str(e))
def run_command(self, config): ''' Runs the command via a subprocess ''' dao = DAO(config) try: dao.put_log(str(datetime.now()) + " " + self.build_command()) p = subprocess.check_output(self.interface + " " + self.build_command(), shell=True, stderr=subprocess.STDOUT) dao.put_log(str(datetime.now()) + " " + p) except subprocess.CalledProcessError as cpe: dao.put_log(str(datetime.now()) + " " + cpe.cmd) dao.put_log(str(datetime.now()) + " " + cpe.output)
def get(self, inp): query = inp["query"] if ("act" not in query): return 418, "Impossible de trouver l'activitée ou mauvais appel (._. )" if ("city" in query and "range" in query): r = DAO().guess_Activities_byGCity(query["city"], query["act"], int(query["range"])) else: if ("city" in query): r = DAO().guess_Activities_byGCity(query["city"], query["act"]) else: r = [ act["ActLib"] for act in DAO().guess_input_activites(query["act"]) ] return { "code": 200, "header": [], "content": "application/json", "res": str.encode(JSONDecEncoder().encode(r)) }
def get_current_surgeons(): logger = Logger() try: dao = DAO() # lat, lng = request.form["lat"], request.form["lng"] surgeons = dao.get_surgeons() return jsonify(surgeons) except Exception as e: logger.log(str(e)) return "Your request cannot be processed at this time"
def all_systems_go(): dao = DAO(session()) instance = ClockServer(dao) server = SimpleXMLRPCServer(("localhost", 8080), requestHandler=RequestHandler, logRequests=False, allow_none=True) server.register_introspection_functions() server.register_instance(instance) mainlog.info("The server is running") server.serve_forever()
def main(self): xml_data_all_files = self.__get_xml_all_files() dao_58 = DAO(HOST_58, DATABASE_58, USER_58, PASSWD_58) dao_45 = DAO(HOST_45, DATABASE_45, USER_45, PASSWD_45) record_inserted = 0 self.__create_file_with_xml_without_latlng(xml_data_all_files) # Making inserts try: for filename, xml_data in xml_data_all_files.items(): record_inserted += self.__execute_inserts( xml_data, dao_45, dao_58, filename) print('The XML from {} was inserted with Successfully'.format( filename)) except Exception as exc: dao_58.conn.rollback() dao_45.conn.rollback() sys.exit('{}\n Rollback successfully'.format(exc)) else: dao_58.conn.commit() dao_45.conn.commit() self.success_messages(record_inserted)
def test_find(self): testDataContent = [ '648:abcdefghi', '517:QjhWkizN5t', '323:dwcIY99gTN1', '653:UlfY2UvMfeuX' ] data1 = DAO(testDataContent) found = data1.find('abcdefghi') assert found.tasktime == '648' and found.taskstring == 'abcdefghi' notFound = data1.find('nonexistent') assert notFound is None
def test_add_entry(self): data1 = DAO([]) assert data1.is_empty() data1.add_entry('648', 'abcdefghi') assert not data1.is_empty() found = data1.find('abcdefghi') assert found.tasktime == '648' and found.taskstring == 'abcdefghi' with pytest.raises(Exception): data1.add_entry('648', 'abcdefghi') data1.add_entry('000', 'abcdefghi')
def test_advance_time(self): testDataContent = [ '648:abcdefghi', '517:QjhWkizN5t', '323:dwcIY99gTN1', '653:UlfY2UvMfeuX' ] data1 = DAO(testDataContent) with pytest.raises(Exception): data1.advance_time('nonexistent', '30') data1.advance_time('abcdefghi', '30') assert data1.find('abcdefghi').tasktime == '678'
def test_remove_entry(self): testDataContent = [ '648:abcdefghi', '517:QjhWkizN5t', '323:dwcIY99gTN1', '653:UlfY2UvMfeuX' ] data1 = DAO(testDataContent) assert data1.find('abcdefghi') data1.remove_entry('abcdefghi') assert data1.find('abcdefghi') is None with pytest.raises(Exception): data1.remove_entry('abcdefghi')
def retrieve_documents(self, assessor, query_id, doc_retrieval_count): """ Get documents documents from assessment index for given assessor and query id. If there aren't enough documents in assessor index, it will be fetched from crawled index. :param assessor: assessor id :param query_id: query id :param doc_retrieval_count: total docs to retrieve :return: """ dao = DAO() if not dao.index_exists(): dao.create_index() existing_doc_count = 0 else: existing_doc_count = dao.get_doc_count(assessor, query_id) print 'existing count', existing_doc_count if existing_doc_count < doc_retrieval_count: dao.add_additional_docs(existing_doc_count, doc_retrieval_count, assessor, query_id) assessment_list = dao.retrieve_docs(assessor, query_id, doc_retrieval_count) doc_list = [] for doc in assessment_list: doc_index_id = doc.get_index_id() doc_query_id = doc.get_query_id() doc_assessor_ = doc.get_assessor() doc_url = doc.get_document() doc_grade = doc.get_grade() doc_list.append({ 'index_id': doc_index_id, 'query_id': doc_query_id, 'assessor': doc_assessor_, 'document': doc_url, 'grade': doc_grade }) return doc_list