def thread_restore(thread_id): db = connect() cursor = db.cursor() try: cursor.execute("""SELECT * FROM Thread WHERE id=%s """, (thread_id, )) dels = cursor.fetchone() if dels: cursor.execute("""UPDATE Post SET isDeleted=0 WHERE thread=%s""", (thread_id, )) cursor.execute("""UPDATE Thread SET isDeleted=0 WHERE id=%s """, (thread_id, )) results = { "code": 0, "response": { "thread": thread_id, } } cursor.close() db.commit() db.close() return results else: return response_dict[1] except MySQLdb.IntegrityError: return response_dict[4]
def getStudentTTestGroupDBList(group1, group2): list_group_queue = [] try: conn = mysql_connect.connect() sql = mysql_connect.get_student_ttest_sql_group_select() conn.autocommit = True cursor = conn.cursor() cursor.execute(sql, ( group1, group2, )) if cursor: for row in cursor: group_test_row = Tsparkcore.print_Group_DB(row) list_group_queue.append(group_test_row) print row except: import traceback traceback.print_exc() conn.rollback() finally: if cursor: cursor.close() conn.close() return list_group_queue
def update(event, context): if validate_data(event): try: conn = mysql_connect.connect() param = json.loads(event['body']) user_param = event['pathParameters'] with conn.cursor() as cursor: sql = "UPDATE `dinesh_users` set `name` = %s,`username` = %s,`email` = %s,`password` = %s,`updated_on` = %s where id = %s " cursor.execute(sql, ( param['name'], param['username'], param['email'], param['password'], datetime.datetime.now(), user_param['user_id'])) conn.commit() status_code = 200 body = { "message": "User updated successfully" } except: status_code = 403 body = { "message": "Something went wrong please try again" } finally: conn.close() else: status_code = 400 body = { "message": "Please enter all the values" } response = { "statusCode": status_code, "body": json.dumps(body) } return response
def get_user(event, context): conn = mysql_connect.connect() params = event['pathParameters'] with conn.cursor() as cursor: sql = "select `id`,`first_name`, `last_name`,`username`,`mobile`, `site_id` from `user` where id = %s;" cursor.execute(sql, params['user_id']) result = cursor.fetchone() conn.commit() headers = ['id', 'first_name', 'last_name', 'username', 'mobile', 'site_id'] user_data = dict(zip(headers, result)) status_code = 200 body = { "data": user_data } try: pass except: status_code = 403 body = { "message": "Something went wrong please try again" } finally: if(conn): conn.close() return { "statusCode": status_code, "body": json.dumps(body) }
def profile_update(about, user, name): db = connect() cursor = db.cursor(MySQLdb.cursors.DictCursor) try: cursor.execute(""" UPDATE users SET name = %s, about = %s WHERE email = %s""", (name, about, user)) cursor.execute(""" SELECT * FROM users WHERE email = %s""", (user,)) str = cursor.fetchone() print str results = { "code": 0, "response": { "about": str['about'], "email": str['email'], "followers": func_followers(user), "following": func_following(user), "id": str['id'], "isAnonymous": bool(str['isAnonymous']), "name": str['name'], "subscriptions": func_subscribe(user), "username": str['username'] } } cursor.close() db.commit() db.close() return results except MySQLdb.IntegrityError as e: return response_dict[4]
def updateDescribeAnalysisStatus(uuID): conn = None cursor = None try: conn = mysql_connect.connect() sql = mysql_connect.get_Describe_Analysis_update() conn.autocommit = True cursor = conn.cursor() cursor.execute(sql, (time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())), uuID)) conn.commit() except: import traceback traceback.print_exc() if conn: conn.rollback() finally: if cursor: cursor.close() if conn: conn.close() return
def delete_user(event, context): conn = mysql_connect.connect() params = event['pathParameters'] if data_is_valid(params): try: with conn.cursor() as cursor: sql = "delete from `user` where id = %s;" cursor.execute(sql, params['user_id']) conn.commit() status_code = 200 body = { "message": "User deleted successfully" } except: status_code = 403 body = { "message": "Something went wrong please try again" } finally: if(conn): conn.close() return { "statusCode": status_code, "body": json.dumps(body) } else: body = { "message": "Please enter valid data" } return { "statusCode": 400, "body": json.dumps(body) }
def getDescribeAnalysiscList(): list_ask_queue = [] cursor = None conn = None try: conn = mysql_connect.connect() sql = mysql_connect.get_describe_analysisc_sql_select() conn.autocommit = True cursor = conn.cursor() cursor.execute(sql) if cursor: for row in cursor: list_ask_queue.append(print_DescribeAnalysis_DB(row)) print row except: import traceback traceback.print_exc() if conn: conn.rollback() finally: if cursor: cursor.close() if conn: conn.close() return list_ask_queue
def thread_unsubscribe(thread_id, follower_email): db = connect() cursor = db.cursor() try: cursor.execute( """SELECT * FROM subscriptions WHERE thread = %s AND user = %s """, (thread_id, follower_email)) dels = cursor.fetchone() print follower_email, thread_id if dels: cursor.execute( """DELETE FROM subscriptions WHERE thread = %s AND user = %s """, (thread_id, follower_email)) results = { "code": 0, "response": { "thread": thread_id, "user": follower_email, } } cursor.close() db.commit() db.close() return results else: return response_dict[1] except MySQLdb.IntegrityError: return response_dict[4]
def detail(email): db = connect() cursor = db.cursor(MySQLdb.cursors.DictCursor) try: email = email.replace("%40", "@") print email cursor.execute(""" SELECT * FROM users WHERE email=%s""", (email,)) str = cursor.fetchone() if not str: return response_dict[1] else: print str results = { "about": str["about"], "email": str["email"], "followers": func_followers(email), "following": func_following(email), "id": str['id'], "isAnonymous": bool(str['isAnonymous']), "name": str['name'], "subscriptions": func_subscribe(email), "username": str['username'] } cursor.close() db.commit() db.close() return results except MySQLdb.IntegrityError as e: if e[0] == 1062: return response_dict[5] elif e[0] == 1452: return response_dict[1] else: print e return response_dict[4]
def thread_subscribe(thread_id, follower_email): db = connect() cursor = db.cursor() try: cursor.execute( """INSERT INTO subscriptions (thread,user) VALUES (%s,%s)""", (thread_id, follower_email)) results = { "code": 0, "response": { "thread": thread_id, "user": follower_email, } } cursor.close() db.commit() db.close() return results except MySQLdb.IntegrityError as e: print e[0] if e[0] == 1062: return response_dict[5] elif e[0] == 1452: return response_dict[1] else: return response_dict[4]
def save_result_db(inputID, result): conn = None cursor = None try: conn = mysql_connect.connect() sql = mysql_connect.update_math_in_out_sql_result() conn.autocommit = True cursor = conn.cursor() cursor.execute(sql, (result, time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())), inputID)) conn.commit() except: import traceback traceback.print_exc() if conn: conn.rollback() finally: if cursor: cursor.close() if conn: conn.close() return
def status(): db = connect() cursor = db.cursor() try: cursor.execute("""SELECT count(*) FROM Forum """) count_forum = cursor.fetchone() cursor.execute("""SELECT count(*) FROM Post """) count_post = cursor.fetchone() cursor.execute("""SELECT count(*) FROM Thread """) count_thread = cursor.fetchone() cursor.execute("""SELECT count(*) FROM User """) count_user = cursor.fetchone() result = { "code": 0, "response": { "user": count_user[0], "thread": count_thread[0], "forum": count_forum[0], "post": count_post[0] } } cursor.close() db.commit() db.close() return result except MySQLdb.Error: return response_dict[4]
def profile_update(about, user, name): db = connect() cursor = db.cursor() try: cursor.execute(""" UPDATE User SET name=%s,about=%s WHERE email=%s""", (name, about, user)) cursor.execute(""" SELECT * FROM User WHERE email=%s""", (user, )) str = cursor.fetchone() print str results = { "code": 0, "response": { "about": str[2], "email": str[4], "followers": func_followers(user), "following": func_following(user), "id": str[0], "isAnonymous": bool(str[5]), "name": str[3], "subscriptions": func_subscribe(user), "username": str[1] } } cursor.close() db.commit() db.close() return results except MySQLdb.IntegrityError as e: return response_dict[4]
def create_post(date, thread, message, user, forum, is_approved, is_highlighted, is_spam, is_deleted, is_edited, parent): db = connect() cursor = db.cursor() try: if parent is None: is_root = 0 path = ' ' else: is_root = 1 cursor.execute("""SELECT path FROM Post WHERE id = %s""", (parent,)) path = cursor.fetchone()[0] cursor.execute("""INSERT INTO Post (date, thread, message, user, forum, isApproved, isHighlighted, isSpam, isDeleted, isEdited,parent,isRoot) VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s) """, (date, thread, message, user, forum, is_approved, is_highlighted, is_spam, is_deleted, is_edited, parent, is_root)) cursor.execute(""" SELECT * FROM Post WHERE forum=%s AND user=%s AND message=%s AND thread=%s """, (forum, user, message, thread)) db_id = cursor.fetchone() results = { "code": 0, "response": { "date": date, "forum": forum, "id": db_id[0], "isApproved": is_approved, "isDeleted": is_deleted, "isEdited": is_edited, "isHighlighted": is_highlighted, "isSpam": is_spam, "message": message, "parent": db_id[5], "thread": thread, "user": user } } post_id = cursor.lastrowid base36 = int2str(int(post_id), radix=36) path += str(len(base36)) + base36 cursor.execute("""UPDATE Post SET path = %s WHERE id = %s""", (path, post_id)) cursor.execute(""" SELECT count(*) FROM Post WHERE thread=%s and isDeleted=0""", (thread,)) posts_count = cursor.fetchone() cursor.execute(""" UPDATE Thread SET posts=%s WHERE id=%s""", (str(posts_count[0]), thread)) print posts_count[0] cursor.close() db.commit() db.close() return results except MySQLdb.IntegrityError as e: if e[0] == 1062: return response_dict[5] elif e[0] == 1452: return response_dict[1] else: return response_dict[4]
def getStudentTTestDBAskCalcList(): list_ask_queue = [] conn = None cursor = None try: conn = mysql_connect.connect() sql = mysql_connect.get_student_ttest_sql_select() conn.autocommit = True cursor = conn.cursor() cursor.execute(sql) if cursor: for row in cursor: list_ask_queue.append(print_StudentTtest_DB(row)) print row except: import traceback traceback.print_exc() if conn: conn.rollback() finally: if cursor: cursor.close() if conn: conn.close() return list_ask_queue
def saveDescribeAnalysisResultToDB(idKey, uuId, dict_id, result_dict): if result_dict is None: return conn = None cursor = None try: conn = mysql_connect.connect() sql = mysql_connect.get_Describe_Analysis_result_sql_replace() conn.autocommit = True cursor = conn.cursor() cursor.execute( sql, (idKey, uuId, dict_id, result_dict, time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())))) conn.commit() except: import traceback traceback.print_exc() if conn: conn.rollback() finally: if cursor: cursor.close() if conn: conn.close() return
def change_format(begin, end): ''' changes the format of dates from YYYYMMDD to YYYY-MM-DD HH:mm Args: begin is a date in YYYYMMDD end is a date in YYYYMMDD ''' if len(begin) != 8 or len(end) != 8: exit(-1) try: int(begin) int(end) except (TypeError, ValueError): exit(-1) try: newBegin = begin[0:4] + '-' + begin[4:6] + '-' + begin[6:8] + " 00:00" newEnd = end[0:4] + '-' + end[4:6] + '-' + end[6:8] + ' 23:59' except (TypeError, ValueError): exit(-1) con = connect(newBegin, newEnd) if con is None: exit(-2) else: dataFile = open("company_trans_%s_%s.dat" % (begin, end), "wb") for i in con: print(i)
def get_math_input_list(): list_ask_queue = [] cursor = None conn = None try: conn = mysql_connect.connect() sql = mysql_connect.get_math_in_out_sql_list() conn.autocommit = True cursor = conn.cursor() cursor.execute(sql) if cursor: for row in cursor: list_ask_queue.append(print_math_in_DB(row)) except: import traceback traceback.print_exc() if conn: conn.rollback() finally: if cursor: cursor.close() if conn: conn.close() return list_ask_queue
def thread_subscribe(thread_id, follower_email): db = connect() cursor = db.cursor() try: cursor.execute("""INSERT INTO Thread_followers (thread_id,follower_email) VALUES (%s,%s)""", (thread_id, follower_email)) results = { "code": 0, "response": { "thread": thread_id, "user": follower_email, } } cursor.close() db.commit() db.close() return results except MySQLdb.IntegrityError as e: print e[0] if e[0] == 1062: return response_dict[5] elif e[0] == 1452: return response_dict[1] else: return response_dict[4]
def list_user_forum(since_id, order, limit, forum): db = connect() cursor = db.cursor(MySQLdb.cursors.DictCursor) try: if since_id is None: since_id = " " else: since_id = " AND `id` >= " + since_id if limit is None: limit = " " else: limit = ' LIMIT ' + limit cursor.execute( """SELECT * FROM User WHERE email IN (SELECT DISTINCT user FROM Post WHERE forum = %s)""" + since_id + " ORDER BY name " + order + limit + " ;", (forum, )) array = [] users = [i for i in cursor.fetchall()] for user in users: user = detail(user['email']) array.append(user) results = {"code": 0, "response": array} return results except MySQLdb.Error: return response_dict[4]
def thread_unsubscribe(thread_id, follower_email): db = connect() cursor = db.cursor() try: cursor.execute("""SELECT * FROM Thread_followers WHERE thread_id=%s AND follower_email=%s """, (thread_id, follower_email)) dels = cursor.fetchone() print follower_email, thread_id if dels: cursor.execute("""DELETE FROM Thread_followers WHERE thread_id=%s AND follower_email=%s """, (thread_id, follower_email)) results = { "code": 0, "response": { "thread": thread_id, "user": follower_email, } } cursor.close() db.commit() db.close() return results else: return response_dict[1] except MySQLdb.IntegrityError: return response_dict[4]
def create_forum(name, short_name, user): db = connect() cursor = db.cursor() try: cursor.execute("""SELECT * FROM User WHERE email=%s""", (user,)) cursor.execute("""INSERT INTO Forum (name,short_name,user) VALUES (%s,%s,%s) """, (name, short_name, user)) cursor.execute(""" SELECT id FROM Forum WHERE name=%s """, (name,)) db_id = cursor.fetchone() print db_id results = { "code": 0, "response": { "id": db_id[0], "name": name, "short_name": short_name, "user": user } } cursor.close() db.commit() db.close() return results except MySQLdb.IntegrityError as e: if e[0] == 1062: return response_dict[5] elif e[0] == 1452: return response_dict[1] else: return response_dict[4]
def create_forum(name, short_name, user): db = connect() cursor = db.cursor() try: cursor.execute("""SELECT * FROM User WHERE email=%s""", (user, )) cursor.execute( """INSERT INTO Forum (name,short_name,user) VALUES (%s,%s,%s) """, (name, short_name, user)) cursor.execute(""" SELECT id FROM Forum WHERE name=%s """, (name, )) db_id = cursor.fetchone() print db_id results = { "code": 0, "response": { "id": db_id[0], "name": name, "short_name": short_name, "user": user } } cursor.close() db.commit() db.close() return results except MySQLdb.IntegrityError as e: if e[0] == 1062: return response_dict[5] elif e[0] == 1452: return response_dict[1] else: return response_dict[4]
def detail(email): db = connect() cursor = db.cursor() try: email = email.replace("%40", "@") print email cursor.execute(""" SELECT * FROM User WHERE email=%s""", (email, )) str = cursor.fetchone() if not str: return response_dict[1] else: print str results = { "about": str[2], "email": str[4], "followers": func_followers(email), "following": func_following(email), "id": str[0], "isAnonymous": bool(str[5]), "name": str[3], "subscriptions": func_subscribe(email), "username": str[1] } cursor.close() db.commit() db.close() return results except MySQLdb.IntegrityError as e: if e[0] == 1062: return response_dict[5] elif e[0] == 1452: return response_dict[1] else: print e return response_dict[4]
def list_user_forum(since_id, order, limit, forum): db = connect() cursor = db.cursor(MySQLdb.cursors.DictCursor) try: if since_id is None: since_id = " " else: since_id = " AND `id` >= " + since_id if limit is None: limit = " " else: limit = ' LIMIT ' + limit cursor.execute("""SELECT * FROM User WHERE email IN (SELECT DISTINCT user FROM Post WHERE forum = %s)""" + since_id + " ORDER BY name " + order + limit + " ;", (forum,)) array = [] users = [i for i in cursor.fetchall()] for user in users: user = detail(user['email']) array.append(user) results = {"code": 0, "response": array} return results except MySQLdb.Error: return response_dict[4]
def create_thread(forum, title, is_closed, user, date, message, slug, is_deleted): db = connect() cursor = db.cursor() try: cursor.execute("""INSERT INTO Thread (forum,title,isClosed,user,date,message,slug,isDeleted) VALUES (%s,%s,%s,%s,%s,%s,%s,%s) """, (forum, title, is_closed, user, date, message, slug, is_deleted)) cursor.execute(""" SELECT * FROM Thread WHERE forum=%s AND user=%s AND title=%s""", (forum, user, title)) db_id = cursor.fetchone() results = { "code": 0, "response": { "date": date, "forum": forum, "id": db_id[0], "isClosed": bool(is_closed), "isDeleted": bool(db_id[3]), "message": message, "slug": slug, "title": title, "user": user, } } cursor.close() db.commit() db.close() return results except MySQLdb.IntegrityError as e: if e[0] == 1062: return response_dict[5] elif e[0] == 1452: return response_dict[1] else: return response_dict[4]
def thread_open(thread_id): db = connect() cursor = db.cursor() try: cursor.execute("""SELECT * FROM threads WHERE id = %s """, (thread_id, )) dels = cursor.fetchone() if dels: cursor.execute( """UPDATE threads SET isClosed = FALSE WHERE id = %s """, (thread_id, )) results = { "code": 0, "response": { "thread": thread_id, } } cursor.close() db.commit() db.close() return results else: return response_dict[1] except MySQLdb.IntegrityError: return response_dict[4]
def create_post(date, thread, message, user, forum, is_approved, is_highlighted, is_spam, is_deleted, is_edited, parent): db = connect() cursor = db.cursor() try: path = '' if parent is None: is_root = 0 else: is_root = 1 cursor.execute("""SELECT path FROM posts WHERE id = %s""", (parent,)) path = cursor.fetchone() cursor.execute("""INSERT INTO posts (date, thread, message, user, forum, isApproved, isHighlighted, isSpam, isDeleted, isEdited,parent,isRoot) VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s) """, (date, thread, message, user, forum, is_approved, is_highlighted, is_spam, is_deleted, is_edited, parent, is_root)) cursor.execute(""" SELECT * FROM posts WHERE forum=%s AND user=%s AND message=%s AND thread=%s """, (forum, user, message, thread)) db_id = cursor.fetchone()[0] results = { "code": 0, "response": { "date": date, "forum": forum, "id": db_id, "isApproved": is_approved, "isDeleted": is_deleted, "isEdited": is_edited, "isHighlighted": is_highlighted, "isSpam": is_spam, "message": message, "parent": parent, "thread": thread, "user": user } } post_id = cursor.lastrowid base36 = int2str(int(post_id), radix=36) path += str(len(base36)) + base36 cursor.execute("""UPDATE posts SET path = %s WHERE id = %s""", (path, post_id)) cursor.execute(""" SELECT count(*) FROM posts WHERE thread = %s and isDeleted = FALSE""", (thread,)) posts_count = cursor.fetchone()[0] cursor.execute(""" UPDATE threads SET posts = %s WHERE id = %s""", (str(posts_count), thread)) print posts_count cursor.close() db.commit() db.close() return results except MySQLdb.IntegrityError as e: if e[0] == 1062: return response_dict[5] elif e[0] == 1452: return response_dict[1] else: return response_dict[4]
def follow(follower, followee): db = connect() cursor = db.cursor() try: cursor.execute(""" SELECT * FROM User WHERE email=%s""", (followee, )) str = cursor.fetchone() cursor.execute(""" SELECT * FROM User WHERE email=%s""", (follower, )) str2 = cursor.fetchone() if str2: cursor.execute( """INSERT INTO User_followers (User,Followers) VALUES (%s,%s) """, (follower, followee)) cursor.execute( """ SELECT Followers FROM User_followers WHERE User=%s""", (follower, )) followers = cursor.fetchall() cursor.execute( """ SELECT User FROM User_followers WHERE Followers=%s""", (follower, )) following = cursor.fetchall() cursor.execute( """ SELECT count(*) FROM Thread_followers WHERE follower_email=%s""", (followee, )) count_subscribe = cursor.fetchone() print str results = { "code": 0, "response": { "about": str[2], "email": str[4], "followers": func_followers(follower), "following": func_following(follower), "id": str[0], "isAnonymous": bool(str[5]), "name": str[3], "subscriptions": count_subscribe[0], "username": str[1] } } cursor.close() db.commit() db.close() return results else: return response_dict[1] except MySQLdb.IntegrityError as e: if e[0] == 1062: return response_dict[5] elif e[0] == 1452: return response_dict[1] else: return response_dict[4] except TypeError as e: print e results = response_dict[1] return results
def user_post_list(user, order, since, limit): db = connect() cursor = db.cursor() try: query = """SELECT * FROM Post WHERE user=%s """ query_params = (user, ) if since is not None: query += "AND date >= %s " query_params += (since, ) query += "ORDER BY date " + order + " " if limit is not None: query += "LIMIT %s;" query_params += (int(limit), ) cursor.execute(query, query_params) array = [] for db_id in cursor.fetchall(): maps = { "date": db_id[1].strftime("%Y-%m-%d %H:%M:%S"), "dislikes": db_id[13], "forum": db_id[5], "id": db_id[0], "isApproved": bool(db_id[7]), "isDeleted": bool(db_id[11]), "isEdited": bool(db_id[9]), "isHighlighted": bool(db_id[8]), "isSpam": bool(db_id[10]), "likes": db_id[12], "message": db_id[3], "parent": db_id[6], "points": int(db_id[16]), "thread": db_id[2], "user": db_id[4] } array.append(maps) print array results = {"code": 0, "response": array} cursor.close() db.commit() db.close() return results except MySQLdb.Error as e: print e return response_dict[1] except TypeError as e: print e return response_dict[1] except MySQLdb.IntegrityError as e: if e[0] == 1062: return response_dict[5] elif e[0] == 1452: print e return response_dict[1] else: return response_dict[4]
def convDate(beg_date, end_date): """ Takes beginning date and end date as parameters to query the database. Converts the inputs to proper format YYYY-MM-DD hh:mm Args: beg_date: date in YYYYMMDD format end_date: date in YYYYMMDD format Returns: """ db = read_db_config() if(len(str(beg_date)) != 8 or len(str(end_date)) != 8): print("Improper date format. Please use the format <YYYYMMDD>") #Exit code 255 in Bash exit(-1) #Convert to list to add elements convB_date = list(str(beg_date)) convE_date = list(str(end_date)) #Add dashes, whitespace, and time #Year convB_date.insert(4, "-") convE_date.insert(4, "-") #Month convB_date.insert(7, "-") convE_date.insert(7, "-") #Time (whitespace) convB_date.insert(11, " ") convE_date.insert(11, " ") #Time (value) convB_date.insert(12, "00:00") convE_date.insert(12, "23:59") #Assign to new variables for database query bDate = "".join(convB_date) eDate = "".join(convE_date) #Connect to database and retrieve contents for display contents = connect(bDate, eDate) if not contents: print("No data for given date range") #Exit code 254 in Bash exit(-2) #The fun part, making the fixed length record. #Should always be 47 characters long #Index, Name, Size, Type #[0], Transaction ID, 5, int #[1], Transaction date, 12, int #[2], Card number, 6, int #[3], Prod qty, 2, int #[4], Prod amt, 6, int #[5], Prod desc, 10, str #[6], Prod total, 6, int for entry in contents: print('{0:05d}{1:012d}{2:06d}{3:02d}{4:06d}{5:10}{6:06d}'.format(int(entry[0]), int(entry[1]), int(entry[2]), int(entry[3]), int(entry[4]), entry[5], int(entry[6])))
def list_thread_forum(since, order, limit, forum, related): db = connect() cursor = db.cursor(MySQLdb.cursors.DictCursor) try: query = """SELECT * FROM threads WHERE forum = %s """ query_params = (forum,) if since is not None: query += "AND date >= %s " query_params += (since,) query += "ORDER BY date " + order + " " if limit is not None: query += "LIMIT %s;" query_params += (int(limit),) cursor.execute(query, query_params) array = [] for db_id in cursor.fetchall(): maps = { #"date": str(db_id['date']), "dislikes": db_id["dislikes"], "forum": db_id["forum"], "id": db_id['id'], "isClosed": bool(db_id["isClosed"]), "isDeleted": bool(db_id["isDeleted"]), "likes": db_id["likes"], "message": db_id["message"], "points": db_id["points"], "posts": db_id["posts"], "slug": db_id["slug"], "title": db_id["title"], "user": db_id["user"] } maps.update({'date': str(db_id['date'])}) array.append(maps) print array for iter in array: if 'user' in related: user = detail(iter['user']) iter.update({'user': user}) if 'forum' in related: forum = detail_forum(None, iter['forum']) iter.update({'forum': forum}) results = { "code": 0, "response": array } return results except MySQLdb.Error: return response_dict[4]
def func_following(email): db = connect() cursor = db.cursor(MySQLdb.cursors.DictCursor) cursor.execute(""" SELECT follower FROM followers WHERE followee = %s """, (email,)) following = [i['follower'] for i in cursor.fetchall()] cursor.close() db.commit() db.close() print following return following
def func_subscribe(email): db = connect() cursor = db.cursor(MySQLdb.cursors.DictCursor) cursor.execute(""" SELECT thread FROM subscriptions WHERE user=%s""", (email,)) subscribe = [i['thread'] for i in cursor.fetchall()] cursor.close() db.commit() db.close() print subscribe return subscribe
def func_followers(email): db = connect() cursor = db.cursor(MySQLdb.cursors.DictCursor) cursor.execute(""" SELECT Followers FROM User_followers WHERE User=%s """, (email,)) followers = [i['Followers'] for i in cursor.fetchall()] cursor.close() db.commit() db.close() print followers return followers
def func_subscribe(email): db = connect() cursor = db.cursor(MySQLdb.cursors.DictCursor) cursor.execute(""" SELECT thread_id FROM Thread_followers WHERE follower_email=%s""", (email,)) subscribe = [i['thread_id'] for i in cursor.fetchall()] cursor.close() db.commit() db.close() print subscribe return subscribe
def list_thread_forum(since, order, limit, forum, related): db = connect() cursor = db.cursor() try: query = """SELECT * FROM Thread WHERE forum = %s """ query_params = (forum,) if since is not None: query += "AND date >= %s " query_params += (since,) query += "ORDER BY date " + order + " " if limit is not None: query += "LIMIT %s;" query_params += (int(limit),) cursor.execute(query, query_params) array = [] for db_id in cursor.fetchall(): maps = { "date": db_id[5].strftime("%Y-%m-%d %H:%M:%S"), "dislikes": db_id[10], "forum": db_id[1], "id": db_id[0], "isClosed": bool(db_id[3]), "isDeleted": bool(db_id[8]), "likes": db_id[9], "message": db_id[6], "points": db_id[12], "posts": db_id[11], "slug": db_id[7], "title": db_id[2], "user": db_id[4] } array.append(maps) print array for iter in array: if 'user' in related: user = detail(iter['user']) iter.update({'user': user}) if 'forum' in related: forum = detail_forum(None, iter['forum']) iter.update({'forum': forum}) results = { "code": 0, "response": array } return results except MySQLdb.Error: return response_dict[4]
def list_followers(email, order, limit, since_id): db = connect() cursor = db.cursor(MySQLdb.cursors.DictCursor) try: cursor.execute(""" SELECT * FROM users WHERE email = %s""", (email,)) if email is None: return response_dict[1] if limit is None: limit = " " else: limit = ' LIMIT ' + limit try: cursor.execute( """SELECT about, email, id, isAnonymous, name, username FROM followers AS f JOIN users ON users.email = f.followeee WHERE f.follower = %s AND users.id >= %s ORDER BY name """ + order + limit + " ;", ( email, int(since_id) ) ) except MySQLdb.Error as e: print e return response_dict[3] users = [i for i in cursor.fetchall()] for user in users: following = func_following(user['email']) followers = func_followers(user['email']) cursor.execute( """SELECT `thread` FROM `subscriptions` WHERE `user` = %s;""", ( user['email'], ) ) threads = [i['thread'] for i in cursor.fetchall()] user.update({'following': following, 'followers': followers, 'subscriptions': threads}) if users: results = {"code": 0, "response": users} return results else: return response_dict[1] except MySQLdb.IntegrityError as e: if e[0] == 1062: return response_dict[5] elif e[0] == 1452: return response_dict[1] else: return response_dict[4]
def saveSampleResultToDB(idKey, uuId, dict_id, result_dict): if result_dict is None: result_dict = {} result_dict['N'] = -1, result_dict['mean'] = -1, result_dict['stddev'] = -1, result_dict['stddev_error'] = -1, result_dict['statistic'] = -1, result_dict["s_free_degree"] = -1, #s_free_degree result_dict['pvalue'] = -1, result_dict['mean_dev'] = -1, result_dict['confidence_low'] = -1, result_dict['confidence_up'] = -1, result_dict['confidence'] = -1, result_dict['popmean'] = -1, try: conn = mysql_connect.connect() sql = mysql_connect.get_sample_test_result_sql_replace() conn.autocommit = True cursor = conn.cursor() cursor.execute( sql, ( idKey, uuId, dict_id, result_dict['N'], result_dict['mean'], result_dict['stddev'], result_dict['stddev_error'], result_dict['statistic'], result_dict["s_free_degree"], #s_free_degree result_dict['pvalue'], result_dict['mean_dev'], result_dict['confidence_low'], result_dict['confidence_up'], result_dict['confidence'], result_dict['popmean'], time.strftime('%Y-%m-%d %H:%M:%S', time.localtime( time.time())))) conn.commit() except: import traceback traceback.print_exc() conn.rollback() finally: cursor.close() conn.close() return
def func_followers(email): db = connect() cursor = db.cursor(MySQLdb.cursors.DictCursor) cursor.execute(""" SELECT Followers FROM User_followers WHERE User=%s """, (email, )) followers = [i['Followers'] for i in cursor.fetchall()] cursor.close() db.commit() db.close() print followers return followers
def func_subscribe(email): db = connect() cursor = db.cursor(MySQLdb.cursors.DictCursor) cursor.execute( """ SELECT thread_id FROM Thread_followers WHERE follower_email=%s""", (email, )) subscribe = [i['thread_id'] for i in cursor.fetchall()] cursor.close() db.commit() db.close() print subscribe return subscribe
def list_post(since, order, limit, forum, thread): db = connect() cursor = db.cursor(MySQLdb.cursors.DictCursor) try: if thread is None and forum is None: return response_dict[3] if forum is not None: query = """SELECT * FROM posts WHERE forum = %s """ query_params = (forum,) else: query = """SELECT * FROM posts WHERE thread = %s """ query_params = (thread,) if since is not None: query += "AND date >= %s " query_params += (since,) query += "ORDER BY date " + order + " " if limit is not None: query += "LIMIT %s;" query_params += (int(limit),) cursor.execute(query, query_params) array = [] for db_id in cursor.fetchall(): maps = { "date": str(db_id['date']), "dislikes": db_id["dislikes"], "forum": db_id['forum'], "id": db_id['id'], "isApproved": bool(db_id["isApproved"]), "isDeleted": bool(db_id["isDeleted"]), "isEdited": bool(db_id["isEdited"]), "isHighlighted": bool(db_id["isHighlighted"]), "isSpam": bool(db_id["isSpam"]), "likes": db_id["likes"], "message": db_id["message"], "parent": db_id["parent"], "points": int(db_id["points"]), "thread": db_id['thread'], "user": db_id['user'] } array.append(maps) print array result = { "code": 0, "response": array } return result except MySQLdb.Error: return response_dict[4]
def list_post(since, order, limit, forum, thread): db = connect() cursor = db.cursor() try: if thread is None and forum is None: return response_dict[3] if forum is not None: query = """SELECT * FROM Post WHERE forum = %s """ query_params = (forum,) else: query = """SELECT * FROM Post WHERE thread = %s """ query_params = (thread,) if since is not None: query += "AND date >= %s " query_params += (since,) query += "ORDER BY date " + order + " " if limit is not None: query += "LIMIT %s;" query_params += (int(limit),) cursor.execute(query, query_params) array = [] for db_id in cursor.fetchall(): maps = { "date": db_id[1].strftime("%Y-%m-%d %H:%M:%S"), "dislikes": db_id[13], "forum": db_id[5], "id": db_id[0], "isApproved": bool(db_id[7]), "isDeleted": bool(db_id[11]), "isEdited": bool(db_id[9]), "isHighlighted": bool(db_id[8]), "isSpam": bool(db_id[10]), "likes": db_id[12], "message": db_id[3], "parent": db_id[6], "points": int(db_id[16]), "thread": db_id[2], "user": db_id[4] } array.append(maps) print array result = { "code": 0, "response": array } return result except MySQLdb.Error: return response_dict[4]
def list_thread(since, order, limit, forum, user): db = connect() cursor = db.cursor() try: if user and forum: query = """SELECT * FROM Thread WHERE forum = %s AND user = %s """ query_params = (forum, user) elif forum: query = """SELECT * FROM Thread WHERE forum = %s """ query_params = (forum,) else: query = """SELECT * FROM Thread WHERE user = %s """ query_params = (user,) if since is not None: query += "AND date >= %s " query_params += (since,) query += "ORDER BY date " + order + " " if limit is not None: query += "LIMIT %s;" query_params += (int(limit),) cursor.execute(query, query_params) array = [] for db_id in cursor.fetchall(): maps = { "date": db_id[5].strftime("%Y-%m-%d %H:%M:%S"), "dislikes": db_id[10], "forum": db_id[1], "id": db_id[0], "isClosed": bool(db_id[3]), "isDeleted": bool(db_id[8]), "likes": db_id[9], "message": db_id[6], "points": db_id[12], "posts": db_id[11], "slug": db_id[7], "title": db_id[2], "user": db_id[4] } array.append(maps) print array result = { "code": 0, "response": array } return result except MySQLdb.Error: return response_dict[4]
def follow(follower, followee): db = connect() cursor = db.cursor() try: cursor.execute(""" SELECT * FROM User WHERE email=%s""", (followee,)) str = cursor.fetchone() cursor.execute(""" SELECT * FROM User WHERE email=%s""", (follower,)) str2 = cursor.fetchone() if str2: cursor.execute("""INSERT INTO User_followers (User,Followers) VALUES (%s,%s) """, (follower, followee)) cursor.execute(""" SELECT Followers FROM User_followers WHERE User=%s""", (follower,)) followers = cursor.fetchall() cursor.execute(""" SELECT User FROM User_followers WHERE Followers=%s""", (follower,)) following = cursor.fetchall() cursor.execute(""" SELECT count(*) FROM Thread_followers WHERE follower_email=%s""", (followee,)) count_subscribe = cursor.fetchone() print str results = { "code": 0, "response": { "about": str[2], "email": str[4], "followers": func_followers(follower), "following": func_following(follower), "id": str[0], "isAnonymous": bool(str[5]), "name": str[3], "subscriptions": count_subscribe[0], "username": str[1] } } cursor.close() db.commit() db.close() return results else: return response_dict[1] except MySQLdb.IntegrityError as e: if e[0] == 1062: return response_dict[5] elif e[0] == 1452: return response_dict[1] else: return response_dict[4] except TypeError as e: print e results = response_dict[1] return results
def follow(follower, followee): db = connect() cursor = db.cursor(MySQLdb.cursors.DictCursor) try: cursor.execute(""" SELECT * FROM users WHERE email=%s""", (followee,)) str = cursor.fetchone() cursor.execute(""" SELECT * FROM users WHERE email=%s""", (follower,)) str2 = cursor.fetchone() if str2: cursor.execute("""INSERT INTO followers (follower ,followee ) VALUES (%s,%s) """, (follower, followee)) cursor.execute(""" SELECT followee FROM followers WHERE follower = %s""", (follower,)) followers = cursor.fetchall() cursor.execute(""" SELECT follower FROM followers WHERE followee = %s""", (follower,)) following = cursor.fetchall() cursor.execute(""" SELECT count(*) FROM subscriptions WHERE user = %s""", (followee,)) count_subscribe = cursor.fetchone() print str results = { "code": 0, "response": { "about": str['about'], "email": str['email'], "followers": func_followers(follower), "following": func_following(follower), "id": str['id'], "isAnonymous": bool(str['isAnonymous']), "name": str['name'], "subscriptions": count_subscribe, "username": str['username'] } } cursor.close() db.commit() db.close() return results else: return response_dict[1] except MySQLdb.IntegrityError as e: if e[0] == 1062: return response_dict[5] elif e[0] == 1452: return response_dict[1] else: return response_dict[4] except TypeError as e: print e results = response_dict[1] return results
def detail_forum(related, forum): db = connect() cursor = db.cursor() try: cursor.execute("""SELECT * FROM Forum WHERE short_name=%s """, (forum,)) db_id = cursor.fetchone() cursor.execute("""SELECT * FROM User WHERE email=%s""", (db_id[3],)) user_id = cursor.fetchone() if related: results = { "id": db_id[0], "name": db_id[1], "short_name": db_id[2], "user": { "about": user_id[2], "email": db_id[3], "followers": func_followers(db_id[3]), "following": func_following(db_id[3]), "id": user_id[0], "isAnonymous": user_id[5], "name": user_id[3], "subscriptions": func_subscribe(db_id[3]), "username": user_id[1] } } else: results = { "id": db_id[0], "name": db_id[1], "short_name": db_id[2], "user": db_id[3] } cursor.close() db.commit() db.close() return results except MySQLdb.Error: return response_dict[1] except TypeError: return response_dict[1] except MySQLdb.IntegrityError as e: if e[0] == 1062: return response_dict[5] elif e[0] == 1452: return response_dict[1] else: return response_dict[4]
def post_vote(post_id, vote): db = connect() cursor = db.cursor(MySQLdb.cursors.DictCursor) try: cursor.execute("""SELECT * FROM posts WHERE id=%s """, (post_id,)) is_id = cursor.fetchone() if is_id: print vote if vote == 1: cursor.execute("""UPDATE posts SET likes=likes+1, points=points+1 WHERE id=%s """, (post_id,)) elif vote == -1: cursor.execute("""UPDATE posts SET dislikes=dislikes+1, points=points-1 WHERE id=%s """, (post_id,)) else: return response_dict[3] cursor.execute("""SELECT * FROM posts WHERE id=%s """, (post_id,)) db_id = cursor.fetchone() results = { "code": 0, "response": { "date": str(db_id['date']), "dislikes": db_id["dislikes"], "forum": db_id['forum'], "id": db_id['id'], "isApproved": bool(db_id["isApproved"]), "isDeleted": bool(db_id["isDeleted"]), "isEdited": bool(db_id["isEdited"]), "isHighlighted": bool(db_id["isHighlighted"]), "isSpam": bool(db_id["isSpam"]), "likes": db_id["likes"], "message": db_id["message"], "parent": db_id["parent"], "points": int(db_id["points"]), "thread": db_id['thread'], "user": db_id['user'] } } cursor.close() db.commit() db.close() return results else: return response_dict[1] except MySQLdb.IntegrityError: return response_dict[4]
def post_vote(post_id, vote): db = connect() cursor = db.cursor() try: cursor.execute("""SELECT * FROM Post WHERE id=%s """, (post_id,)) is_id = cursor.fetchone() if is_id: print vote if vote == 1: cursor.execute("""UPDATE Post SET likes=likes+1, points=points+1 WHERE id=%s """, (post_id,)) elif vote == -1: cursor.execute("""UPDATE Post SET dislikes=dislikes+1, points=points-1 WHERE id=%s """, (post_id,)) else: return response_dict[3] cursor.execute("""SELECT * FROM Post WHERE id=%s """, (post_id,)) db_id = cursor.fetchone() results = { "code": 0, "response": { "date": db_id[1].strftime("%Y-%m-%d %H:%M:%S"), "dislikes": db_id[13], "forum": db_id[5], "id": db_id[0], "isApproved": bool(db_id[7]), "isDeleted": bool(db_id[11]), "isEdited": bool(db_id[9]), "isHighlighted": bool(db_id[8]), "isSpam": bool(db_id[10]), "likes": db_id[12], "message": db_id[3], "parent": db_id[6], "points": db_id[14], "thread": db_id[5], "user": db_id[4] } } cursor.close() db.commit() db.close() return results else: return response_dict[1] except MySQLdb.IntegrityError: return response_dict[4]
def unfollow(follower, followee): db = connect() cursor = db.cursor() try: cursor.execute(""" SELECT * FROM User WHERE email=%s""", (followee,)) str = cursor.fetchone() cursor.execute(""" SELECT * FROM User WHERE email=%s""", (follower,)) str2 = cursor.fetchone() if str2: cursor.execute("""DELETE FROM User_followers WHERE User=%s AND Followers=%s """, (follower, followee)) print str results = { "code": 0, "response": { "about": str[2], "email": str[4], "followers": func_followers(follower), "following": func_following(follower), "id": str[0], "isAnonymous": bool(str[5]), "name": str[3], "subscriptions": func_subscribe(follower), "username": str[1] } } cursor.close() db.commit() db.close() return results else: return response_dict[1] except MySQLdb.IntegrityError as e: if e[0] == 1062: print e return response_dict[5] elif e[0] == 1452: return response_dict[1] else: return response_dict[4] except TypeError: results = response_dict[1] return results
def thread_vote(thread, vote): db = connect() cursor = db.cursor() try: cursor.execute("""SELECT * FROM Thread WHERE id=%s """, (thread,)) is_id = cursor.fetchone() if is_id: print vote if vote == 1: cursor.execute("""UPDATE Thread SET likes=likes+1, points=points+1 WHERE id=%s """, (thread,)) elif vote == -1: cursor.execute("""UPDATE Thread SET dislikes=dislikes+1, points=points-1 WHERE id=%s """, (thread,)) else: return response_dict[3] cursor.execute("""SELECT * FROM Thread WHERE id=%s """, (thread,)) db_id = cursor.fetchone() results = { "code": 0, "response": { "date": db_id[5].strftime("%Y-%m-%d %H:%M:%S"), "dislikes": db_id[10], "forum": db_id[1], "id": db_id[0], "isClosed": db_id[3], "isDeleted": db_id[8], "likes": db_id[9], "message": db_id[6], "points": db_id[12], "posts": db_id[11], "slug": db_id[7], "title": db_id[2], "user": db_id[4] } } cursor.close() db.commit() db.close() return results else: return response_dict[1] except MySQLdb.IntegrityError: return response_dict[4]
def clear(): db = connect() cursor = db.cursor() try: cursor.execute("""SET foreign_key_checks = 0""") cursor.execute("""TRUNCATE forums""") cursor.execute("""TRUNCATE users""") cursor.execute("""TRUNCATE treads""") cursor.execute("""TRUNCATE posts""") cursor.execute("""TRUNCATE subscriptions""") cursor.execute("""TRUNCATE followers""") result = { "code": 0, "response": "OK" } cursor.close() db.commit() db.close() return result except MySQLdb.Error: return response_dict[4]
def status(): try: db = connect() cursor = db.cursor() tables = ['users', 'threads', 'forums', 'posts'] response = {} for table in tables: cursor.execute('SELECT COUNT(1) FROM %s' % table) db.commit() response[table] = cursor.fetchone()[0] db.close() result = { "code": 0, "response": response } cursor.close() db.commit() db.close() return result except MySQLdb.Error: return response_dict[4]
def clear(): db = connect() cursor = db.cursor() try: cursor.execute("""SET foreign_key_checks = 0""") cursor.execute("""TRUNCATE Forum""") cursor.execute("""TRUNCATE User""") cursor.execute("""TRUNCATE Thread""") cursor.execute("""TRUNCATE Post""") cursor.execute("""TRUNCATE Thread_followers""") cursor.execute("""TRUNCATE User_followers""") result = { "code": 0, "response": "OK" } cursor.close() db.commit() db.close() return result except MySQLdb.Error: return response_dict[4]
def post_restore(post_id): db = connect() cursor = db.cursor() try: cursor.execute("""SELECT * FROM Post WHERE id=%s """, (post_id,)) del_sel = cursor.fetchone() if del_sel: cursor.execute("""UPDATE Post SET isDeleted=0 WHERE id=%s """, (post_id,)) results = { "code": 0, "response": { "post": post_id, } } cursor.close() db.commit() db.close() return results else: return response_dict[1] except MySQLdb.IntegrityError: return response_dict[4]