def update_item(item_id, quantity, produce_id): query = "SELECT produce_quantity FROM produce WHERE produce_id = %s" try: connection = connect() cur = connection.cursor() params = (produce_id,) cur.execute(query, params) produce_quantity = cur.fetchone() if not produce_quantity: print("wrong id") else: if int(quantity) > int(produce_quantity[0]): return "Could not update quantity. Total %s kg available" except mysql.connector.Error as err: print(err) finally: cur.close() connection.close() query = "UPDATE cart_items SET item_quantity = %s WHERE item_id = %s" try: connection = connect() cur = connection.cursor() params = (int(quantity), item_id,) cur.execute(query, params) connection.commit() except mysql.connector.Error as err: print(err) finally: cur.close() connection.close() return "Quantity updated successfully"
def checkout_page(): categories = get_categories() items, subtotal, items_len = cart_items() query = "SELECT DISTINCT buyer_address FROM address WHERE buyer_id = %s" try: connection = connect() cur = connection.cursor() params = (session['id'], ) cur.execute(query, params) buyer_address = cur.fetchall() except mysql.connector.Error as err: print(err) finally: cur.close() connection.close() query = "SELECT user_address FROM user WHERE user_id = %s" try: connection = connect() cur = connection.cursor() params = (session['id'], ) cur.execute(query, params) user_address = cur.fetchone() except mysql.connector.Error as err: print(err) finally: cur.close() connection.close() return render_template('checkout.html', categories=categories, buyer_address=buyer_address, items=items, subtotal=subtotal, items_len=items_len, user_address=user_address)
def find_intersections(): #bounding box is a dictionary with indices max_lat, max_lon, min_lat, min_lon db_connection.connect("130_project") session = db_connection.SESSIONMAKER() intersect_nodes = session.query( db_model.StreetHasNode.node, func.count(db_model.StreetHasNode.node)).group_by( db_model.StreetHasNode.node).having( func.count(db_model.StreetHasNode.node) > 1).all() print(len(intersect_nodes)) # session.query(Child).join(Child, Child.parent_metadata_id == Parent.metadata_id) for i in intersect_nodes: streets = session.query(db_model.StreetHasNode).filter( db_model.StreetHasNode.node == i[0]).order_by( db_model.StreetHasNode.street.asc()).all() location = session.query( db_model.Node.location).filter(db_model.Node.id == i[0]).first()[0] session.add( db_model.Intersection(street_1=streets[0].street, street_2=streets[1].street, location=location)) session.commit() session.close()
def create_specialRules(reader): db_connection = connect() cursor = db_connection.cursor() sql = """ INSERT INTO SpecialRules (Scheme, NumberOfPlayers, HeroInVillainDeck, RequiredHero, NumberOfHeroes, SinisterAmbitions, TyrantVillains) VALUES (%s, %s, %s, %s, %s, %s, %s) """ cursor.execute(TABLES['SpecialRules']) for specialRule in reader: parameters = (specialRule['Scheme'], specialRule['NumberOfPlayers'], specialRule['HeroInVillainDeck'], specialRule['RequiredHero'], specialRule['NumberOfHeroes'], specialRule['SinisterAmbitions'], specialRule['TyrantVillains']) print("Inserting {} into SpecialRules".format(specialRule['Scheme'])) cursor.execute(sql, parameters) db_connection.commit() db_connection.close() cursor.close()
def set_pass(app): form = request.form pwd = form['password'] pwd_repeat = form['confirm'] if (pwd != pwd_repeat): flash("Different passwords.") return redirect(url_for('updatepassword')) query = "UPDATE user SET user_password = %s WHERE user_id = %s" try: connection = connect() bcrypt = Bcrypt(app) pw_hash = bcrypt.generate_password_hash(pwd).decode('utf-8') cur = connection.cursor() params = (pw_hash, session['id'],) cur.execute(query, params) connection.commit() flash("Password updated successfully!!") except mysql.connector.Error as err: print(err) flash("Could not update your details. Try again Later") finally: cur.close() connection.close() return redirect(url_for('updatepassword'))
def set_status(order_id, delivery_status): items, subtotal, items_len = cart_items() if (not order_id): flash("Could not retrieve order") return redirect(url_for('delivery')) if delivery_status == 'Pending': query = "UPDATE orders SET delivery_status = 'Shipping',\ pickup_time = NOW() WHERE order_id = %s " elif delivery_status == 'Shipping': query = "UPDATE orders SET delivery_status = 'Delivered',\ drop_time = NOW() WHERE order_id = %s " try: connection = connect() cur = connection.cursor() params = (order_id, ) cur.execute(query, params) connection.commit() except mysql.connector.Error as err: print(err) flash("Could not update status. Try again later") finally: cur.close() connection.close() return redirect(url_for('delivery'))
def get_status(): query = "SELECT produce_image, produce_name, order_date, delivery_status,\ order_quantity, order_price, delivery_address, order_id \ FROM orders INNER JOIN produce \ ON orders.produce_id = produce.produce_id \ WHERE orders.delivery_agency_id = (SELECT agency_id \ FROM delivery_agent WHERE delivery_agent_id = %s)\ ORDER BY order_date" params = (session['id'], ) try: connection = connect() cur = connection.cursor() cur.execute(query, params) delivery_details = cur.fetchall() except mysql.connector.Error as err: print(err) delivery_details = [] flash("Could not retrieve past delivery details") finally: cur.close() connection.close() addresses = [delivery[6] for delivery in delivery_details] addresses = set(addresses) items, subtotal, items_len = cart_items() return render_template('delivery.html', subtotal=subtotal, items=items, delivery_details=delivery_details, addresses=addresses)
def login(app): form = request.form bcrypt = Bcrypt(app) email = form['email'] password = form['password'] query = "SELECT user_password, user_role, user_id, user_email FROM user\ WHERE user_email = %s" try: connection = connect() cur = connection.cursor() cur.execute(query, (email, )) results = cur.fetchall() if len(results) > 0: results = results[0] if bcrypt.check_password_hash(results[0], password): session['email'] = results[3] session['role'] = results[1] session['id'] = results[2] flash("Login successful") return redirect(url_for('index')) else: flash("Incorrect password") return redirect(url_for('auth')) else: flash("No such user.. Register first!!") return redirect(url_for('auth')) except mysql.connector.Error as err: flash("Something went wrong") print("Something went wrong: {}".format(err)) return "SQL ERROR" finally: cur.close() connection.close()
def main(): # Initialise colorama colorama.init() valid_args = ['-n', '-n2', '-s', '-s2', '-e', '-e2', '-b', '-bf', '-bb', '-bs', '-bl', '-br'] if len(sys.argv) > 1 and sys.argv[1] not in valid_args: print_usage_info(sys.argv) if sys.argv[1] not in ['-h', '--help']: sys.exit(1) sys.exit() db_file = pick_db_file() conn, cursor = db_connection.connect(db_file) card_repository.create_table_if_not_exists(conn, cursor) if len(sys.argv) == 1: table_is_empty = card_repository.check_if_empty(cursor) if table_is_empty: print_error("You don't have any cards yet.") print_instruction( 'Create some cards by launching garrick with one of the following options first:' ) print_instruction('\t-n\tCreate cards starting in one-way mode.') print_instruction('\t-n2\tCreate cards starting in two-way mode.') print_instruction('\t-s\tCreate cards starting in single-line and one-way mode.') print_instruction('\t-s2\tCreate cards starting in single-line and two-way mode.') print_instruction('\t-e\tCreate cards starting in editor mode and in one-way mode.') print_instruction('\t-s2\tCreate cards starting in editor mode and in two-way mode.') else: review.review(conn, cursor) elif sys.argv[1] == '-n': new_cards(conn, cursor, two_way_card=False, single_line_mode=False, editor_mode=False) elif sys.argv[1] == '-n2': new_cards(conn, cursor, two_way_card=True, single_line_mode=False, editor_mode=False) elif sys.argv[1] == '-s': new_cards(conn, cursor, two_way_card=False, single_line_mode=True, editor_mode=False) elif sys.argv[1] == '-s2': new_cards(conn, cursor, two_way_card=True, single_line_mode=True, editor_mode=False) elif sys.argv[1] == '-e': new_cards(conn, cursor, two_way_card=False, single_line_mode=False, editor_mode=True) elif sys.argv[1] == '-e2': new_cards(conn, cursor, two_way_card=True, single_line_mode=False, editor_mode=True) elif sys.argv[1] == '-b': review.browse_by_regex(conn, cursor) elif sys.argv[1] == '-bf': review.browse_by_regex_front(conn, cursor) elif sys.argv[1] == '-bb': review.browse_by_regex_back(conn, cursor) elif sys.argv[1] == '-bs': review.browse_by_score(conn, cursor) elif sys.argv[1] == '-bl': review.browse_by_last_viewed(conn, cursor) elif sys.argv[1] == '-br': review.browse_by_last_viewed_reverse(conn, cursor) print_info('Kbai') db_connection.disconnect(conn, cursor)
def update_slot_to_free(self): connection = db_connection.connect() cursor = connection.cursor() try: cursor.execute("select slot from vehicle_details where vehicle_number='{}'".format(self.vehical_entry.get())) slot = cursor.fetchone() if slot == None or slot[0] != int(self.slot_entry.get()): messagebox.showerror("Error", "Sorry, you have not booked this slot.", parent=self.toplevel_free_slot) return cursor.execute("update slot SET booked_status='Available' where slot_number={}".format(self.slot_entry.get())) connection.commit() self.vehical_entry.delete(0, END) self.slot_entry.delete(0, END) messagebox.showinfo("Successful", "Slot is free now..", parent=self.toplevel_free_slot) except Exception as e: connection.rollback() messagebox.showerror("Error", e, parent=self.toplevel_free_slot) print(e) connection.close()
def set_profile(): form = request.form user_details = get_details() fname = form['first_name'] lname = form['last_name'] user_name = fname + " " + lname user_phone = form['phone'] user_address = form['address'] ALLOWED_EXTENSIONS = set(['png', 'jpg', 'jpeg']) form = request.form image_path = user_details[0] print("name" + request.files['image'].filename) if (request.files['image'].filename == ""): query = "UPDATE user SET user_name = %s, user_phone = %s,\ user_address = %s WHERE user_id = %s" params = ( user_name, user_phone, user_address, session['id'], ) elif (request.files['image'].filename != ""): image_name = request.files['image'].filename image_ext = image_name.split('.', 1)[1].lower() if (image_ext not in ALLOWED_EXTENSIONS): flash("Allowed Extensions are : jpg, jpeg, png ") image_name = (user_name + "-" + str(datetime.now().strftime("%d%m%y %H%M%S")) + "." + image_ext) print(image_name) image_path = "./static/user_profile_image/" + image_name print(image_path) request.files['image'].save(image_path) query = "UPDATE user SET user_image = %s, user_name = %s, user_phone = %s,\ user_address = %s WHERE user_id = %s" params = ( image_path[1:], user_name, user_phone, user_address, session['id'], ) try: connection = connect() cur = connection.cursor() cur.execute(query, params) connection.commit() flash("Profile updated successfully!!") except mysql.connector.Error as err: print(err) flash("Could not update your details. Try again Later") finally: cur.close() connection.close() return redirect(url_for('profile'))
def add_nodes(file_name): tree = ET.parse(file_name) root = tree.getroot() nodes = set() db_connection.connect("130_project") session = db_connection.SESSIONMAKER() for node in root.findall("node"): nodes.add((int(node.attrib['id']), float(node.attrib['lat']), float(node.attrib['lon']))) nodes = list(nodes) print(len(nodes)) for i in nodes: session.add(db_model.Node(id = i[0], location = 'SRID=4326;POINT({} {})'.format(i[2], i[1]))) session.commit() session.close()
def update_item(item_id, quantity, produce_id): try: connection = connect() cur = connection.cursor() params = (produce_id,) params = (produce_ii) cur.execute(query, params) produce_quantity = cur.fetchone() if not produce_quantity:
def __init__(self): self.conn = db_connection.connect() self.mmdbs_data = db_connection.get_all_images(self.conn) self.weight_dic = {} self.weight_dic['global_histogram'] = 1 self.weight_dic['local_histogram'] = 1 self.weight_dic['global_edge_histogram'] = 1 self.weight_dic['global_hue_histogram'] = 1 self.weight_dic['color_moments'] = 1 self.weight_dic['central_circle_color_histogram'] = 1 self.weight_dic['contours'] = 1
def download_images_defined_location(locations, zoom, pixels, center, xy_to_ij, num_images, api_key, img_folder, distance_factor=1, save_image=True): """ Returns num_images ** 2 at locations defined by locations and array generated by lat_long_array() :param locations: dict with keys: 'name', 'lat', 'lon' :param zoom: int :param pixels: int :param center: bool :param xy_to_ij: bool if True then coordinates of array will be indexed as in matrix (left to right, up to down) if False then coordinates of array will be indexed as in cartesian coordinate system, first quadrant (left to right, down to up) :param num_images: int int**2 number of images will be returned :param api_key: str :param img_folder: str :param distance_factor: int if 1 then generates array with images 'touching' each other if > 1 then generates array where images are separated by the factor :param center: bool see lat/long parameters :param save_image: bool :return: """ images = [] mdata = [] db = dbcon.connect("../credentials/mlab_db.txt", "mfp") images_lib_col = db["images_lib"] for location in locations: print("Saving images of " + location["name"] + "...") coord = lat_long_array(location['lat'], location['lon'], zoom, pixels, num_images, distance_factor=distance_factor, center=center, xy_to_ij=xy_to_ij) for i in range(coord.shape[0]): for j in range(coord.shape[1]): lat = coord[i, j, 0] lon = coord[i, j, 1] image = download_and_save_image(location['name'], lat, lon, zoom, pixels, api_key, folder=img_folder, save_image=save_image) images.append(image) if save_image: metadata = generate_metadata_gmaps(location['name'], lat, lon, zoom, pixels, api_key) mdata.append(metadata) images_lib_col.replace_one({"filename": metadata["filename"]}, metadata, upsert=True) return images, mdata
def getWordList(): word = request.args.get('word') type_ = request.args.get('type') # 字符串需要用单引号包裹 sql = "select * from my_words where word like '" + word + "%' and type like '" + type_ + "%'" db = connect() # 游标设置为字典类型 cursor = db.cursor(cursor=pymysql.cursors.DictCursor) cursor.execute(sql) data = cursor.fetchall() db.close() return baseReturn(data)
def getbook(): db = connect() cursor = db.cursor() sql = "select table_name from information_schema.tables where table_schema='words'" cursor.execute(sql) data = cursor.fetchall() db.close() list = [] for x in data: if not str(x[0]) == 'my_words': list.append(str(x[0])) return baseReturn(list)
def add_nodes(file_name): tree = ET.parse(file_name) root = tree.getroot() nodes = set() db_connection.connect("130_project") session = db_connection.SESSIONMAKER() for node in root.findall("node"): nodes.add((int(node.attrib['id']), float(node.attrib['lat']), float(node.attrib['lon']))) nodes = list(nodes) print(len(nodes)) for i in nodes: session.add( db_model.Node(id=i[0], location='SRID=4326;POINT({} {})'.format(i[2], i[1]))) session.commit() session.close()
def delWord(): try: word = json.loads(request.get_data()) db = connect() cursor = db.cursor() # 使用了 %s,就不能用引号包裹 sql = "delete from my_words where word=%s" cursor.execute(sql, (word['word'])) db.commit() db.close() return baseReturn('', '删除成功') except ValueError: return baseReturn(ValueError, '删除失败', False)
def add_ways(file_name): tree = ET.parse(file_name) root = tree.getroot() street_names = set() street_refs = set() db_connection.connect("130_project") session = db_connection.SESSIONMAKER() for way in root.findall("way"): valid_street = False street_name = None for tag in way.findall("tag"): if tag.attrib['k'] == "highway" and tag.attrib['v'] not in [ 'footway', 'pedestrian', 'wall', 'path', 'steps', 'bridleway', 'cycleway' ]: valid_street = True if tag.attrib['k'] == 'name': street_name = tag.attrib['v'] # street_names.add((tag.attrib['v'])) if not valid_street or street_name is None: continue way_id = int(way.attrib['id']) street_names.add((way_id, street_name)) for ref in way.findall('nd'): street_refs.add((way_id, int(ref.attrib['ref']))) print(len(street_names)) for i in street_names: session.add(db_model.Streets(id=i[0], name=i[1])) session.flush() print(len(street_refs)) for i in street_refs: session.add(db_model.StreetHasNode(street=i[0], node=i[1])) session.flush() session.commit() session.close()
def add_item(produce_id, quantity): query = "SELECT produce_quantity FROM produce WHERE produce_id = %s" try: connection = connect() cur = connection.cursor() params = (produce_id,) cur.execute(query, params) produce_quantity = cur.fetchone() if not produce_quantity: print("wrong id") else: if int(quantity) > int(produce_quantity[0]): quantity = int(produce_quantity[0]) flash("Available Quantity is " + str(produce_quantity[0]) + " kg only") except mysql.connector.Error as err: print(err) return finally: cur.close() connection.close() buyer_id = session['id'] query = "INSERT into cart_items \ (item_id, item_quantity, buyer_id, produce_id)\ VALUES (UUID(), %s, %s, %s)" try: connection = connect() cur = connection.cursor() params = (quantity, buyer_id, produce_id) cur.execute(query, params) connection.commit() flash("Item added successfully to your cart") except mysql.connector.Error as err: flash("Could not add item to your cart") print(err) finally: cur.close() connection.close()
def filterWord(): words = json.loads(request.get_data()) db = connect() for word in words: # 获取会话指针 with db.cursor() as cursor: # 创建一条 sql 语句,如果表名或字段名中带 - ,需要使用 ` 包裹 sql = "REPLACE INTO my_words (word, type) VALUES(%s, %s)" # 执行sql语句 cursor.execute(sql, (word, 'normal')) # 提交 db.commit() db.close() return baseReturn('', '加入成功')
def fixWord(): try: word = json.loads(request.get_data()) db = connect() cursor = db.cursor() sql = "replace into my_words (word, phonetic, meaning, type) values(%s, %s, %s, %s)" # word.word 报错,应该使用 word['word'] cursor.execute( sql, (word['word'], word['phonetic'], word['meaning'], word['type'])) db.commit() db.close() return baseReturn('', '更新成功') except ValueError: return baseReturn(ValueError, '更新失败', False)
def insertRatingsDB(Ratings): try: connection = connect() with connection.cursor() as cursor: cursor.executemany( """INSERT INTO `ratings` (FilmID, Rating, NumberOfVotes) VALUES (%s, %s, %s)""", Ratings) connection.commit() except Exception as e: print( "Error inserting ratingsDB data for film: {}, with error:".format( Ratings[0]), str(e)) finally: connection.close()
def delete_item(item_id): query = "DELETE FROM cart_items WHERE item_id = %s" try: connection = connect() cur = connection.cursor() params = (item_id,) cur.execute(query, params) connection.commit() flash("Item deleted successfuly") except mysql.connector.Error as err: flash("Could not delete item..Try again later") print(err) finally: cur.close() connection.close()
def main(): db = db_connection.connect() cursor = db.cursor() try: with open(sys.argv[1]) as f: images = json.load(f) for (filename, feature_vector) in images.items(): store_image(cursor, filename, feature_vector) db.commit() finally: cursor.close() db.close()
def add_ways(file_name): tree = ET.parse(file_name) root = tree.getroot() street_names = set() street_refs = set() db_connection.connect("130_project") session = db_connection.SESSIONMAKER() for way in root.findall("way"): valid_street = False street_name = None for tag in way.findall("tag"): if tag.attrib['k'] == "highway" and tag.attrib['v'] not in ['footway', 'pedestrian', 'wall', 'path', 'steps', 'bridleway', 'cycleway']: valid_street = True if tag.attrib['k'] == 'name': street_name = tag.attrib['v'] # street_names.add((tag.attrib['v'])) if not valid_street or street_name is None: continue way_id = int(way.attrib['id']) street_names.add((way_id, street_name)) for ref in way.findall('nd'): street_refs.add((way_id, int(ref.attrib['ref']))) print(len(street_names)) for i in street_names: session.add(db_model.Streets(id = i[0], name = i[1])) session.flush() print(len(street_refs)) for i in street_refs: session.add(db_model.StreetHasNode(street=i[0], node=i[1])) session.flush() session.commit() session.close()
def get_details(): query = "SELECT user_image, user_name, user_email, user_phone, \ user_address, user_role FROM user WHERE user_id = %s" try: connection = connect() cur = connection.cursor() params = (session['id'],) cur.execute(query, params) user_details = cur.fetchone() except mysql.connector.Error as err: print(err) flash("Could not get your details. Try again Later") return [] finally: cur.close() connection.close() return user_details
def check_availabel_slot(self): connection = db_connection.connect() cursor = connection.cursor() try: cursor.execute("select * from slot where booked_status='Available'") data = cursor.fetchall() if data == None or len(data) <= 0: messagebox.showerror("Error", "No slots available right now. Please try after some time.") return 0 else: return data except Exception as e: connection.rollback() print(e) return 0
def cart_data(): query = "SELECT item_id, produce_price, item_quantity, produce_name,\ produce_image, produce.produce_id, user_name FROM produce\ INNER JOIN cart_items ON produce.produce_id = cart_items.produce_id\ INNER JOIN user ON produce.farmer_id = user.user_id \ WHERE buyer_id = %s" try: connection = connect() cur = connection.cursor() params = (session['id'],) cur.execute(query, params) items = cur.fetchall() except Exception as err: return [], [], [], 0, 0 finally: cur.close() connection.close()
def getList(): bookName = request.args.get('bookName') proFrom = request.args.get('proFrom') proTo = request.args.get('proTo') if proFrom == None: proFrom = 0 if proTo == None: proTo = 10000 db = connect() cursor = db.cursor() # 获取 过滤掉 my_words 表中的单词,且指定出现概率范围下的,倒序排列的数据 sql = 'select * from ' + bookName + ' where (select count(1) as num from my_words where my_words.word =' + bookName + '.word) = 0 and probability >= %s and probability <= %s ORDER BY probability DESC' cursor.execute(sql, (request.args.get('proFrom'), request.args.get('proTo'))) data = cursor.fetchall() db.close() return baseReturn(data)
def update_heroes(reader): db_connection = connect() cursor = db_connection.cursor() sql = """ UPDATE Heroes SET Name=%s, Team=%s, CardSet=%s WHERE Name=%s AND CardSet=%s """ for hero in reader: parameters = (hero['Name'], hero['Team'], hero['CardSet'], hero['Name'], hero['CardSet']) print("Updating {} in Heroes".format(hero['Name'])) cursor.execute(sql, parameters) db_connection.commit() db_connection.close() cursor.close()
def __init__(self, athlete_info: dict): self.athlete_info = athlete_info assert self.athlete_info is not None, f"Please provide athlete info. " \ f"Client_id, client_secret and refresh_token required." self.athlete_id = self.athlete_info['athlete_id'] self.base_url = 'https://www.strava.com/api/v3' self.refresh_data = self.refresh_api_connection() self.access_token = self.refresh_data['access_token'] self.headers = {'Authorization': f"Bearer {self.access_token}"} self.token_expires = self.refresh_data['expires_at'] self.conn = connect() self.latest_activity = self.get_latest_activity() self.earliest_activity = self.get_earliest_activity() self.existing_locations = self.get_existing_locations() self.existing_gear = self.get_existing_gear() self.df = pd.DataFrame() self.df_details = pd.DataFrame() self.df_km = pd.DataFrame() self.df_miles = pd.DataFrame()
import db_connection as dbc import concept as cpt # Strip punctuations from string (tokenize) def strip_punctuation(s): punc = string.punctuation s = list(s) return "".join([o if not o in string.punctuation else " " for o in s]).split() def find_col_attr(all_col_names): for col_name in all_col_names: print "column ", col_name print cpt.common_relations(col_name) if __name__ == "__main__": dbname = "world" usr = "******" pw = "postgres" con = dbc.connect(dbname, usr, pw) tables = dbc.list_tables(con) all_col_names = [dbc.list_column_names(con, table) for table in tables] # print all_col_names find_col_attr(all_col_names) dbc.disconnect(con)