def l2_check(): spine_11_new = [] spine_12_new=[] spine_11_l2_output = connect.connect(device['spine-11']['mgmt_ip'], device['spine-11']['port'], cmd, device['spine-11']['username'], device['spine-11']['password']) for x in spine_11_l2_output: y = x.split() z = ('spine-11', y[0], y[4], y[3]) spine_11_new.append(z) spine_12_l2_output = connect.connect(device['spine-12']['mgmt_ip'], device['spine-12']['port'], cmd, device['spine-12']['username'], device['spine-12']['password']) for x in spine_12_l2_output: y = x.split() z = ('spine-12', y[0], y[4], y[3]) spine_12_new.append(z) a = set(spine_11_ls) - set(spine_11_new) b = set(spine_12_ls) - set(spine_12_new) if not list(a): print 'INFO: L2 from Spine-11 is working fine' if list(a): for m in list(a): print 'ERROR: Link failure between %s:%s and %s:%s' % (m[0],m[1],m[2],m[3]) if not list(b): print 'INFO: L2 from Spine-12 is working fine' if list(b): for m in list(b): print 'ERROR: Link failure between %s:%s and %s:%s' % (m[0],m[1],m[2],m[3])
def bgp_check(): spine_11_new = [] spine_12_new=[] spine_11_l3_output = connect.connect(device['spine-11']['mgmt_ip'], device['spine-11']['port'], cmd, device['spine-11']['username'], device['spine-11']['password']) for x in spine_11_l3_output: y = x.split() if y[7] == 'Established': z = ('spine-11', y[1], y[0]) spine_11_new.append(z) spine_12_l3_output = connect.connect(device['spine-12']['mgmt_ip'], device['spine-12']['port'], cmd, device['spine-12']['username'], device['spine-12']['password']) for x in spine_12_l3_output: y = x.split() if y[7] == 'Established': z = ('spine-12', y[1], y[0]) spine_12_new.append(z) a = set(spine_11_bgp) - set(spine_11_new) b = set(spine_12_bgp) - set(spine_12_new) if not list(a): print 'INFO: All BGP peers are connected from Spine-11' if list(a): for m in list(a): print 'ERROR: BGP failure between %s and %s whose AS is %s' % (m[0],m[2],m[1]) if not list(b): print 'INFO: All BGP peers are connected from Spine-12' if list(b): for m in list(b): print 'ERROR: BGP failure between %s and %s whose AS is %s' % (m[0],m[2],m[1])
def items(self): uncompleted_items_json_data = connect.connect(url="getUncompletedItems", params={'token': self.user.api_token, 'project_id': self.id}) completed_items_json_data = connect.connect(url="getCompletedItems", params={'token': self.user.api_token, 'project_id': self.id}) items = item.ItemList(self.user, self) for item_data in uncompleted_items_json_data: items.append(item.Item(item_data, self.user)) for item_data in completed_items_json_data: items.append(item.Item(item_data, self.user)) return items
def update(self, name=None, color=None, indent=None): params = {'token': self.user.api_token, 'project_id': self.id} if(name): params['name'] = name self.name = name if(color): params['color'] = color self.color = color if(indent): params['indent'] = indent self.indent = indent connect.connect(method="PUT", url="updateProject", params=params)
def test_loseGameReturnsTrueWhenThereIsAnOpponentInGame(self): file = open('gunid', 'r+') file.truncate() file.write( "# User Identification File.\n# Change gunid and username.\n# Rename file to gunid.\ngunid=3\nusername=Benjamin\n" ) file.close() gun = Gun() gun.readIDFile() file = open('gunid', 'r+') file.truncate() file.write( "# User Identification File.\n# Change gunid and username.\n# Rename file to gunid.\ngunid=4\nusername=Thomas\n" ) file.close() gun2 = Gun() gun2.readIDFile() mydb = connect.connect() cursor = mydb.cursor() sql = "INSERT INTO Games (current_state, winner, game_date) VALUES (2, 0, (NOW() - INTERVAL 4 HOUR + INTERVAL 11 MINUTE - INTERVAL 22 SECOND))" cursor.execute(sql) mydb.commit() gun.joinGame() gun2.joinGame() self.assertTrue(gun2.loseGame()) mydb.close()
def test_joinGameCorrectlyAddsUserIntoGame(self): file = open('gunid', 'r+') file.truncate() file.write( "# User Identification File.\n# Change gunid and username.\n# Rename file to gunid.\ngunid=3\nusername=Benjamin\n" ) file.close() gun = Gun() gun.readIDFile() mydb = connect.connect() cursor = mydb.cursor() sql = "INSERT INTO Games (current_state, winner, game_date) VALUES (1, 0, (NOW() - INTERVAL 4 HOUR + INTERVAL 11 MINUTE - INTERVAL 22 SECOND))" cursor.execute(sql) mydb.commit() gun.joinGame() sql = "SELECT * FROM (Games INNER JOIN Game_Users ON Games.id = Game_Users.game_id) WHERE Games.current_state = 1" cursor.execute(sql) myresult = cursor.fetchall() self.assertEqual(len(myresult), 1) #only one row added to database self.assertEqual(myresult[0][5], 3) #gunid is 3 self.assertEqual(myresult[0][6], "Benjamin") #username is Benjamin sql = "UPDATE Games SET current_state=0 WHERE current_state=1" cursor.execute(sql) mydb.commit() mydb.close()
def test_fireShotCorrectlyIncrementsPlayerShotsFiredInDatabase(self): file = open('gunid', 'r+') file.truncate() file.write( "# User Identification File.\n# Change gunid and username.\n# Rename file to gunid.\ngunid=3\nusername=Benjamin\n" ) file.close() gun = Gun() gun.readIDFile() mydb = connect.connect() cursor = mydb.cursor() sql = ("SELECT * FROM Players " "WHERE username='******'").format(gun.username) cursor.execute(sql) myresult = cursor.fetchall() oldShots = myresult[0][3] gun.fireShot() sql = ("SELECT * FROM Players " "WHERE username='******'").format(gun.username) cursor.execute(sql) myresult = cursor.fetchall() newShots = myresult[0][3] mydb.close() self.assertEqual((oldShots + 1), newShots)
def update_schedule_in_db(received_dict): from pymongo.collection import ReturnDocument from connect import connect import os client = connect(os.environ["MONGODB_URI"] if os.environ.get("MONGODB_URI") else "mongodb://localhost:27017/ashoka-bot") db = client.get_default_database() updated_document = db.shuttle_schedules.find_one_and_update( { 'origin': received_dict["origin"] }, { '$set': { 'phone': received_dict['phone'], 'schedule': received_dict['schedule'] } }, projection = { '_id': False }, return_document = ReturnDocument.AFTER, upsert = False ) client.close() return updated_document
def user_object_filter(objects, notification=False, notifier=send_notification.send_mail): notify_list = [] watched_users = queries.query_user_object_list() conn = connect.connect() cur = conn.cursor() if watched_users: for user in watched_users: for item_id, item in objects.iteritems(): if fnmatch.fnmatch(item['username'].encode('utf-8'), user['username']): if item['create'] == 1: action = 'create' elif item['modify'] == 1: action = 'modify' elif item['delete'] == 1: action = 'delete' for item_key in item['tags']: info = (item['timestamp'], item['changeset'], item['username'].encode('utf8'), action, item_key, item['tags'][item_key]) cur.execute("""INSERT INTO history_users_objects (timestamp,changeset,username,action,key,value) VALUES (%s, %s, %s, %s, %s, %s);""", info) conn.commit()
def key_filter(objects, notification=False, notifier=send_notification.send_mail): notify_list = [] watched_keys = queries.query_key_list() conn = connect.connect() cur = conn.cursor() if watched_keys: for key in watched_keys: for item_id, item in objects.iteritems(): for item_key in item['tags']: if fnmatch.fnmatch(item_key,key['key']) and fnmatch.fnmatch(item['tags'][item_key],key['value']): if item['create'] == 1: item['action'] = 1 elif item['modify'] == 1: item['action'] = 2 elif item['delete'] == 1: item['action'] = 4 inserts.insert_key_event(item, item_key, key['id']) notify_list.append([(item['timestamp'], item['changeset'], item['username'].encode('utf8'), item['action'], item_key, item['tags'][item_key])]) if notify_list and notification: send_notification.send_notification(notify_list, 'key', notifier=notifier)
def main(): print """----------- Vault Automation Test -----------""" print """This program executes some test cases to evaluate VAULT""" host = raw_input('Enter the IP Address of the host: ') user = raw_input("Enter the Username of the host: ") password = raw_input("Enter the Password of the host: ") ch = raw_input("Enter the choice of connectivity (SSH/WEB)? ") if (ch == "SSH" or ch == "ssh"): handle = connect.connect(host, user, password) out, err = connect.sendcmd(handle, "uname -a") print("The Machine Details are %s \n" % out.readlines()[0]) out, err = connect.sendcmd(handle, 'vault') print("The Vault Status is %s \n" % out.readlines()) elif (ch == "WEB" or ch == "web"): port = raw_input("Enter the port number of the request: ") handle = web.request(host, "sys/health", port) print web.url(handle + "sys/seal-status") else: print("Enter the Right Choice ! \n") sys.exit() print "\nBEGIN: Test Case Execution ---->\n" print "Basic TestCase: " print """"""
def main(): # Arguments: form = cgi.FieldStorage() sn = form.getvalue("serial_number") db = settings.get_db() if sn: try: con = connect(True, db) cur = con.cursor() cur.execute("INSERT INTO Card SET sn = '{0}'; ".format(sn)) con.commit() con.close() except Exception as ex: base.begin() base.header(title='{0}: add module'.format(db)) base.top(db) print ex print '<center><h3 style="color:red"><i>Serial number "{0}" already exists! It was not added.</i></h3></center>'.format(sn) else: cardid = module.fetch_cardid_from_sn(db,sn) base.begin() base.header_redirect("module.py?db={0}&card_id={1}".format(db,cardid)) base.top(db) else: base.begin() base.header_redirect("home.py?db={0}".format(db),1) base.top(db) print '<center><h3 style="color:red"><i>Tried to input null serial number. Do not do that.</i></h3></center>'.format(sn) base.bottom()
def history_keys(action): conn = connect.connect() cur = conn.cursor() if action in ['create', 'c']: cur.execute(""" CREATE TABLE history_keys ( id SERIAL NOT NULL PRIMARY KEY, wid INTEGER NOT NULL, userid BIGINT NOT NULL, key TEXT NOT NULL, value TEXT NOT NULL, element TEXT NOT NULL, username TEXT NOT NULL, changeset BIGINT NOT NULL, timestamp TEXT NOT NULL, action SMALLINT NOT NULL ); """) elif action in ['truncate', 't']: cur.execute(""" TRUNCATE TABLE history_keys; """) elif action in ['drop', 'delete', 'd']: cur.execute(""" DROP TABLE history_keys; """) else: raise NotImplementedError(error_message) conn.commit()
def add_whitelisted_user(username, reason, author, authorid): """ Add whitelisted user that is not picked up in tracking. Inputs ------ username : str Username to track reason : str Reason to track user author : str User adding tracking entry authorid : int Userid of user adding entry """ conn = connect.connect() cur = conn.cursor() info = (username, reason, author, authorid) cur.execute("""INSERT INTO whitelisted_users (username, reason, author, authorid) VALUES (%s, %s, %s, %s);""", info) conn.commit()
def history_filters(action): conn = connect.connect() cur = conn.cursor() if action in ['create', 'c']: cur.execute(""" CREATE TABLE history_filters ( id SERIAL NOT NULL PRIMARY KEY, flag INT NOT NULL, username TEXT NOT NULL, changeset BIGINT NOT NULL, timestamp TEXT NOT NULL, quantity TEXT NOT NULL ); """) elif action in ['truncate', 't']: cur.execute(""" TRUNCATE TABLE history_filters; """) elif action in ['drop', 'delete', 'd']: cur.execute(""" DROP TABLE history_filters; """) else: raise NotImplementedError(error_message) conn.commit()
def register(email, full_name, password, timezone): if len(password) < 5: return "Password should be at least 5 characters long" params={'email': email, 'full_name': full_name, 'password': password, 'timezone':timezone} json_data, status, response = connect.connect(url="register", params=params, ssl=True) return json_data, status, response
def _run(args, config): connection = connect.connect(args, config) cursor = connection.cursor() cursor.callproc("sync_admin.reset_device_secret", keywordParameters={ "device_uuid": args.device})
def Portage_fetch_attach(test_id): db = connect(0) cur = db.cursor() cur.execute( 'SELECT attach_id, attachmime, attachdesc, originalname FROM Attachments WHERE test_id=%(tid)s ORDER BY attach_id' % {'tid': test_id}) return cur.fetchall()
def fetch_list_module(): db = connect(0) cur = db.cursor() cur.execute("SELECT attach_id FROM Attachments ORDER by Attachments.attach_id ASC") rows = cur.fetchall() return rows
def watched_keys(action): conn = connect.connect() cur = conn.cursor() if action in ['create', 'c']: cur.execute(""" CREATE TABLE watched_keys ( id SERIAL NOT NULL PRIMARY KEY, key TEXT NOT NULL, value TEXT NOT NULL, reason TEXT, author TEXT, authorid BIGINT, email TEXT ); """) elif action in ['truncate', 't']: cur.execute(""" TRUNCATE TABLE watched_keys; """) elif action in ['drop', 'delete', 'd']: cur.execute(""" DROP TABLE watched_keys; """) else: raise NotImplementedError(error_message) conn.commit()
def fetch_tests(db, cardid, attachments=True, inclusive=True): # Get a list of tests for this card: con = connect(False, db) cur = con.cursor() # Fetch: revoked_ids = fetch_revoked(db, cardid) tests = OrderedDict() for testtype_dict in fetch_types(db, inclusive=inclusive): cur.execute("SELECT People.person_name, Test.day, Test.successful, Test.comments, Test_Type.name, Test.test_id FROM Test, Test_Type, People, Card WHERE Test_Type.test_type={0} AND Card.card_id={1} AND People.person_id=Test.person_id AND Test_Type.test_type=Test.test_type_id AND Test.card_id = Card.card_id ORDER BY Test.day ASC".format(testtype_dict["testtype_id"], cardid)) test_dicts = [{ "tester": item[0], "time": item[1], "passed": item[2], "comments": item[3], "type": item[4], "test_id": item[5], "revoked": (False, True)[bool(item[5] in revoked_ids)], } for item in cur.fetchall()] result_list = [] for test_dict in test_dicts: cur.execute("SELECT Attachments.attach_id, Attachments.attachmime, Attachments.attachdesc, Attachments.originalname FROM Attachments WHERE Attachments.test_id={0}".format(test_dict["test_id"])) test_dict["attachments"] = [{ "id": item[0], "type": item[1], "description": item[2], "name": item[3], } for item in cur.fetchall()] result_list.append(test_dict) tests[(testtype_dict["testtype_id"], testtype_dict["testtype_name"])] = result_list return tests
def _run(args, config): file_path = os.path.abspath(args.file_path) release, build = args.release, args.build if args.hash: file_size = get_file.get_file_size(file_path) file_hash = args.hash else: file_size, file_hash = get_file.get_file_size_and_hash(file_path) if None in [release, build]: (extracted_release, extracted_build) = _extract_repo_release_and_build(file_path) if release is None: release = extracted_release if build is None: build = extracted_build connection = connect.connect(args, config) cursor = connection.cursor() repo_uuid = cursor.callfunc("sync_admin.add_repo", cx_Oracle.STRING, keywordParameters={ "release": release, "build": build, "file_path": file_path, "file_size": file_size, "file_hash": file_hash}) output.print_value(repo_uuid, "repo_uuid", args.output)
def fetch_revoked(db, cardid): # Get a list of all tests for this card that were revoked: con = connect(False, db) cur = con.cursor() cur.execute("SELECT TestRevoke.test_id FROM TestRevoke, Test WHERE Test.card_id={cardid} AND Test.test_id=TestRevoke.test_id".format(cardid=cardid)) testids = [item[0] for item in cur.fetchall()] return testids
def fetch_revokes(db, sn): con = connect(False, db) cur = con.cursor() cur.execute("SELECT TestRevoke.test_id, TestRevoke.comment FROM TestRevoke, Test, Card WHERE Card.sn = {sn} AND Card.card_id = Test.card_id AND Test.test_id = TestRevoke.test_id".format(sn=sn)) rows = cur.fetchall() # list of (test_id, comment) items # return {test[0]: test[1] for test in rows} # For >= Python 2.7 return dict((test[0], test[1]) for test in rows)
def complete_items(api_token, ids): params={'token': api_token, 'ids': ids} if in_history : params['in_history'] = in_history return connect.connect(url="completeItems", params=params)
def _run(args, config): connection = connect.connect(args, config) cursor = connection.cursor() cursor.callproc("sync_admin.remove_repo", keywordParameters={ "repo_uuid": args.repo})
def update_recurring_date(api_token, ids): params={'token': api_token, 'ids': ids} if js_date : params['js_date'] = js_date return connect.connect(url="updateRecurringDate", params=params)
def get_uncompleted_items(api_token, project_id, js_date=None): params={'token': api_token, 'project_id': project_id} if js_date : params['js_date'] = js_date return connect.connect(url="getUncompletedItems", params=params)
def update_item(api_token, item_id, content=None, date_string=None, priority=None, indent=None, item_order=None, js_date=None): params={'token': api_token, 'id': item_id} if content : params['content'] = content if date_string : params['date_string'] = date_string if priority : params['priority'] = priority if indent : params['indent'] = indent if item_order : params['item_order'] = item_order if js_date : params['js_date'] = js_date return connect.connect(url="updateItem", params=params)
def fetch_list_module(): db = connect(0) cur = db.cursor() cur.execute("SELECT sn, Card_id FROM Card ORDER by Card.sn ASC") rows = cur.fetchall() return rows
def _run(args, config): connection = connect.connect(args, config) cursor = connection.cursor() cursor.callproc("sync_admin.unlock_vm_instance", keywordParameters={ "vm_instance_uuid": args.vm_instance})
def history_all_changesets(action): conn = connect.connect() cur = conn.cursor() if action in ['create', 'c']: cur.execute(""" CREATE TABLE history_all_changesets ( id SERIAL NOT NULL PRIMARY KEY, changeset TEXT NOT NULL, username TEXT NOT NULL, timestamp TEXT NOT NULL, created TEXT, modified TEXT, deleted TEXT ); """) elif action in ['truncate', 't']: cur.execute(""" TRUNCATE TABLE history_all_changesets; """) elif action in ['drop', 'delete', 'd']: cur.execute(""" DROP TABLE history_all_changesets; """) else: raise NotImplementedError(error_message) conn.commit()
def add_test(person_id, test_type, serial_num, success, comments): if success: success = 1 else: success = 0 db = connect(1) cur = db.cursor() if serial_num: cur.execute("SELECT card_id FROM Card WHERE sn = %(n)d" %{"n":serial_num}) row = cur.fetchone() card_id = row[0] sql="INSERT INTO Test (person_id, test_type_id, card_id, successful, comments, day) VALUES (%s,%s,%s,%s,%s,NOW())" # This is safer because Python takes care of escaping any illegal/invalid text items=(person_id,test_type,card_id,success,comments) cur.execute(sql,items) test_id = cur.lastrowid db.commit() return test_id else: print '<div class ="row">' print '<div class = "col-md-3">' print '<h3> Attempt Failed. Please Specify Serial Number </h3>' print '</div>' print '</div>' add_test_template(serial_num)
def add_watched_user(username, reason, author, authorid, email): """ Add user to watched user list for tracking. Inputs ------ username : str Username to track reason : str Reason to track user author : str User adding tracking entry authorid : int Userid of user adding entry email : str, option Email address for notification of events """ conn = connect.connect() cur = conn.cursor() info = (username, reason, author, authorid, email) cur.execute("""INSERT INTO watched_users (username, reason, author, authorid, email) VALUES (%s, %s, %s, %s, %s);""", info) conn.commit()
def add_watched_object(element, reason, author, authorid, email): """ Add object to watched object list. Inputs ------ element : str Object to track, with type specified as single letter prepended to object id (e.g. node 322 is 'n322') reason : str Reason to track user author : str User adding tracking entry authorid : int Userid of user adding entry email : str, option Email address for notification of events """ conn = connect.connect() cur = conn.cursor() info = (element, reason, author, authorid, email) cur.execute("""INSERT INTO watched_objects (element, reason, author, authorid, email) VALUES (%s, %s, %s, %s, %s);""", info) conn.commit()
def create(userid): #might need to change field names later conn = c.connect() temp = conn.read('sessions', {'userid': userid}) # print temp if temp: conn.delete('sessions', {'userid': userid}) conn.clear() newid = conn.custom(""" SELECT MAX(id) as id FROM sessions """)[0]['ID'] if newid: newid += 1 else: newid = 1 #change format of the expiration if needed here #%b # if now.day + 2 > 30 : # day = -1 # expdate = str((day + 2)) + now.strftime("-%b-") + str(now.year)# + " " + str(now.second) + ":" + str(now.minute) + ":" + str(now.hour) # print expdate #expdate = "%d-%s-%d %d:%d" % (now.day + 2, now.strftime("%b"), now.year, now.minute, now.hour) # conn.create('sessions', {'userid' : userid, 'id' : newid, 'expired' : expdate}) conn.create('sessions', {'userid': userid, 'id': newid}) return newid
def add_watched_key(key, value, reason, author, authorid, email): """ Add key/value combination to key/value tracking list. Inputs ------ key : str Key to track; can be wildcard value : str Key value to track; can be wildcard reason : str Reason to track user author : str User adding tracking entry authorid : int Userid of user adding entry email : str, option Email address for notification of events """ conn = connect.connect() cur = conn.cursor() info = (key, value, reason, author, authorid, email) cur.execute("""INSERT INTO watched_keys (key, value, reason, author, authorid, email) VALUES (%s, %s, %s, %s, %s, %s);""", info) conn.commit()
def login(fields, cookie): if fields.has_key('user') and fields.has_key('password'): user = fields['user'].value #.value password = fields['password'].value #.value db = connect.connect() temp = db.read('users', {'userid': user}) #print temp # testing # user does exist and password matches if temp and temp[0]['PASSWORD'] == password: # create session cookie sid = sessions.create(user) newcookie = 'id=' + str(sid) # redirect to catalogue menu page t = loader('loggedin') c = Context({}) #TODO print http_response(t.render(c), newcookie) # no match else: t = loader('login') c = Context({'errors': 'Incorrect username or password. Also, I slept with your sister.'}) print http_response(t.render(c)) # go back to login page with error message else: t = loader('login') c = Context({}) print http_response(t.render(c))
def handle_command(from_no, message): receiver = db.getReceiver(from_no) if connect.is_connect_requested(message): if receiver == db.IBM_RECEIVER: connect.connect(from_no, message) else: messaging.send_messages(from_no, [ "You are already connected to a statefarm agent.", "To disconnect first message\n@statefarm disconnect" ]) elif connect.is_stop_requested(message): if receiver != db.IBM_RECEIVER: connect.disconnect(from_no, receiver) else: messaging.send_messages(from_no, [ "You are not connected to any statefarm agent.", "To connect first message\nconnect agent/community" ]) elif is_register_command(message): if message == "register as agent": db.updateUserType(from_no, db.TYPE_AGENT) messaging.send_messages(from_no, [ "You are now registered as statefarm agent.", "We will connect you to the user when asked for" ]) elif message == "register as user": db.updateUserType(from_no, db.TYPE_USER) messaging.send_messages(from_no, [ "You are now a user.", "You can talk to our chatbot or conenct to statefarm agent" ]) else: messaging.send_message( from_no, "We cannot understand your command.\nMessage @statefarm list commands to get the commands" ) elif message == "list commands": messaging.send_messages(from_no, [ "Statefarm is here to help you", "Use @statefarm to send statefarm commands\n\"@statefarm connect to agent\" \tConnects you to agent\n\"@statefarm connect to community\" \tConnects you to community\n\"@statefarm disconnect\" \tDisconnects you\n\"@statefarm register as agent\" \Registers you as agent\n\"@statefarm register as user\" \Registers you as user\n" ]) else: messaging.send_message( from_no, "We cannot understand your command.\nMessage @statefarm list commands to get the commands" )
def _run(args, config): connection = connect.connect(args, config) cursor = connection.cursor() cursor.callproc("sync_admin.modify_vm_instance_name", keywordParameters={ "vm_instance_uuid": args.vm_instance, "vm_instance_name": args.name})
def _run(args, config): connection = connect.connect(args, config) cursor = connection.cursor() cursor.callproc("sync_admin.modify_device_repo", keywordParameters={ "device_uuid": args.device, "repo_uuid": args.repo})
def addTestToRevokeList(test_id): db = connect(1) cur = db.cursor() cur.execute("INSERT INTO TestRevoke SET test_id=%i,comment='%s'" % (test_id, comments)) db.commit()
def dbconnect(): # Connect to the database con = connect() Base.metadata.bind = con # Creates a session DBSession = sessionmaker(bind=con) dbsession = DBSession() return dbsession
def get_items_by_id(api_token, ids, js_date=None): #ids contains a list of items id's params = {'token': api_token, 'ids': ids} if js_date: params['js_date'] = js_date return connect.connect(url="getItemsById", params=params)
def update_orders(api_token, project_id, item_id_list): params = { 'token': api_token, 'project_id': project_id, 'item_id_list': item_id_list } return connect.connect(url="updateOrders", params=params)
def _run(args, config): connection = connect.connect(args, config) cursor = connection.cursor() cursor.callproc("sync_admin.remove_vm", keywordParameters={ "vm_uuid": args.vm, "cascade": False})
def definition(scheme): cnx = connect('root', 'mysqlpassword', 'localhost', 'worklist') cursor = cnx.cursor() request = ("SELECT definition from `schema` where `scheme`= %s") cursor.execute(request, (scheme, )) definition = cursor.fetchall()[0] definition = definition[0].encode('utf8') print '\n', definition
def _run(args, config): connection = connect.connect(args, config) cursor = connection.cursor() cursor.callproc("sync_admin.remove_device", keywordParameters={ "device_uuid": args.device, "cascade": args.cascade })
def _run(args, config): connection = connect.connect(args, config) cursor = connection.cursor() cursor.callproc("sync_admin.remove_vm_instance", keywordParameters={ "vm_instance_uuid": args.vm_instance, "hard_removal": args.hard })
def _run(args, config): connection = connect.connect(args, config) cursor = connection.cursor() vm_config = cursor.callfunc("sync_admin.get_vm_config", cx_Oracle.CURSOR, keywordParameters={"vm_uuid": args.vm}) output.print_cursor(vm_config, None, args.output)
def signout(): global session if 'dir' in session: dir = session['dir'] os.system('rm -rf ' + dir) session.pop('dir', None) conn, cur = connect() conn.close() return render_template('sign-in.html')
def inRevokeList(test_id): db = connect(0) cur = db.cursor() cur.execute("SELECT test_id FROM TestRevoke where test_id=%i" % test_id) rows = cur.fetchall() #print rows return not rows == []
def __init__(self): """ Constructor for the Gun class. Postconditions: The gun will be active with no id and no username. """ self.id = 0 self.username = "******" self.mydb = connect.connect() self.cursor = self.mydb.cursor() self.url = "https://people.eecs.ku.edu/~b040w377/laserpi.html"
def _run(args, config): connection = connect.connect(args, config) cursor = connection.cursor() shared_secret = cursor.callfunc("sync_admin.get_device_secret", cx_Oracle.STRING, keywordParameters={ "device_uuid": args.device}) output.print_value(shared_secret, "shared_secret", args.output)
def remove_watched_user_object(username): """ Remove user from object composite user tracking list. """ conn = connect.connect() cur = conn.cursor() cur.execute( """DELETE FROM watched_users_objects WHERE username = %s;""", username)
def Portage_fetch(test_type_id, card_sn): db = connect(0) cur = db.cursor() cur.execute( "SELECT People.person_name, Test.day, Test.successful, Test.comments, Test_Type.name, Test.test_id FROM Test, Test_Type, People, Card WHERE Test_Type.test_type = %(test_id)s AND Card.sn = %(sn)s AND People.person_id = Test.person_id AND Test_Type.test_type=Test.test_type_id AND Test.card_id = Card.card_id ORDER BY Test.day ASC" % { 'test_id': test_type_id, 'sn': card_sn }) return cur.fetchall()
def __init__(self, top=None): _bgcolor = '#d9d9d9' # X11 color: 'gray85' _fgcolor = '#000000' # X11 color: 'black' _compcolor = '#d9d9d9' # X11 color: 'gray85' _ana1color = '#d9d9d9' # X11 color: 'gray85' _ana2color = '#d9d9d9' # X11 color: 'gray85' top.geometry("1160x450+154+180") top.title("Registered Books") '''self.Button1 = Button(self.Frame1,command=lambda:switch_frame(top,Home)) self.Button1.place(relx=0.78, rely=0.0, height=25, width=147) self.Button1.configure(activebackground="#d9d9d9") self.Button1.configure(background="#a0d9d9") self.Button1.configure(borderwidth="2") self.Button1.configure(text="Go Back to Home") self.Button1.configure(width=147)''' self.Button1 = Button(top, command=lambda: switch_frame(top, Statistics)) self.Button1.place(relx=0.05, rely=0.85, height=35, width=147) self.Button1.configure(activebackground="#d9d9d9") self.Button1.configure(background="#a0d9d9") self.Button1.configure(borderwidth="3") self.Button1.configure(text='''Back''') self.Button1.configure(width=147) conn = connect.connect() cur = conn.cursor() sql = "select Book_Id,Name,Edition,Publisher,Total_Stock,Current_Stock from Book" cur.execute(sql) data = cur.fetchall() height = len(data) + 1 width = 7 self.t = Entry(top) head = [ "Book_Id", "Name", "Edition", "Publisher", "Total_Stock", "Current_Stock" ] for i in range(height): # Rows for j in range(width): # Columns self.b = Entry(top, justify="center") if i == 0: if j == 0: self.b.insert(len("S.No."), "S.No.") else: self.b.insert(len(head[j - 1]), head[j - 1]) else: if j == 0: self.b.insert(len(str(i)), i) else: self.b.insert(len(str(data[i - 1][j - 1])), data[i - 1][j - 1]) self.b.grid(row=i, column=j) self.b.configure(state="readonly")
def update_project(api_token, project_id, name=None, color=None, indent=None): params = {'token': api_token, 'project_id': project_id} if name: params['name'] = name if color : params['color'] = color if indent : params['indent'] = indent return connect.connect(url="updateProject", params=params)
def add_project(api_token, name, color=None, indent=None, order=None): params = {'token': api_token, 'name': name} if color : params['color'] = color if indent : params['indent'] = indent if order: params['order'] = order return connect.connect(url="addProject", params=params)
def take_data(flag): result = [] cnx = connect('root', 'mysqlpassword', 'localhost', 'users_data') cursor = cnx.cursor() if flag in "get users": result = list_users(cursor) if flag in "get homedir": result = get_user_home_dir("nikitosik", cursor) if flag in "get token": result = get_user_token("nikitosik", cursor) return result