How to use execute_query method in SeleniumBase

Best Python code snippet using SeleniumBase

app.py

Source:app.py Github

copy

Full Screen

...12def books():13 db_connection = db.connect_to_database()14 if request.method == 'GET':15 query = "SELECT * FROM Books ORDER BY bookId DESC LIMIT 10;"16 cursor = db.execute_query(db_connection=db_connection, query=query)17 books = cursor.fetchall()18 returnCode = '001'19 20 if request.method == 'POST':21 # Search a book by name.22 if request.form['action'] == "search_book":23 searchBy, searchInput = request.form['search_book_by'], request.form['search_book_input'].capitalize()24 if searchBy == 'isbn':25 query = "SELECT * FROM Books WHERE ISBN = %s;"26 cursor = db.execute_query(db_connection=db_connection, query=query, query_params=(searchInput,))27 books = cursor.fetchall()28 if searchBy == 'title':29 query = "SELECT * FROM Books WHERE title = %s;"30 cursor = db.execute_query(db_connection=db_connection, query=query, query_params=(searchInput,))31 books = cursor.fetchall()32 if not books:33 books = None34 returnCode = '002'35 # Add an book by name.36 if request.form['action'] == "add_book":37 isbn, title, publisher, publish_year = request.form['isbn'], request.form['title'].capitalize(), request.form['publisher'].capitalize(), request.form['publish_year'].capitalize()38 query = "SELECT * FROM Books WHERE ISBN = %s;"39 cursor = db.execute_query(db_connection=db_connection, query=query, query_params=(isbn,))40 books = cursor.fetchall()41 if not books:42 query = "INSERT INTO Books (ISBN, publisher, title, publicationYear) VALUES (%s, %s, %s, %s);"43 cursor = db.execute_query(db_connection=db_connection, query=query, query_params=(isbn, publisher, title, publish_year))44 returnCode = '003'45 else:46 returnCode = '004'47 books = isbn48 if request.form['action'] == "edit_book":49 book_id = request.form['bookId']50 query = "UPDATE Books set ISBN = %s, publisher = %s, title = %s, publicationYear = %s WHERE bookId = %s;"51 cursor = db.execute_query(db_connection=db_connection, query=query, query_params=(request.form['isbn'], request.form['publisher'], request.form['title'], request.form['publication_year'], request.form['bookId']))52 query = "SELECT * FROM Books WHERE bookId = %s;"53 cursor = db.execute_query(db_connection=db_connection, query=query, query_params=(book_id,))54 books = cursor.fetchall()55 returnCode = '002'56 57 # Delete a book.58 if request.method =='DELETE':59 id = str(request.json['id'])60 query = "SELECT * FROM BooksAuthors WHERE bookId = %s;"61 cursor = db.execute_query(db_connection=db_connection, query=query, query_params = (id,))62 books_1 = cursor.fetchall()63 query = "SELECT * FROM BooksCategories WHERE bookId = %s;"64 cursor = db.execute_query(db_connection=db_connection, query=query, query_params = (id,))65 books_2 = cursor.fetchall()66 if books_1 or books_2: 67 return json.dumps({'result':'fail'})68 query = "DELETE FROM Books WHERE bookId = %s;"69 cursor = db.execute_query(db_connection=db_connection, query=query, query_params = (id,)) 70 return json.dumps({'result':'success'}) 71 return render_template("books.j2", books=books, returnCode=returnCode)72 73@app.route('/authors', methods=['POST', 'GET', 'DELETE', 'PUT'])74def authors():75 db_connection = db.connect_to_database()76 if request.method == 'GET':77 query = "SELECT * FROM Authors ORDER BY authorId DESC LIMIT 10;"78 cursor = db.execute_query(db_connection=db_connection, query=query)79 authors = cursor.fetchall()80 returnCode = '001'81 82 if request.method == 'POST':83 # Search an author by name.84 if request.form['action'] == "search_author":85 fname, lname = request.form['fname'].capitalize(), request.form['lname'].capitalize()86 query = "SELECT * FROM Authors WHERE firstName = %s AND lastName = %s;"87 cursor = db.execute_query(db_connection=db_connection, query=query, query_params=(fname, lname))88 authors = cursor.fetchall()89 returnCode = '002'90 if not authors:91 authors = None92 # Add an author by name.93 if request.form['action'] == "add_author":94 fname, lname = request.form['add_first'].capitalize(), request.form['add_last'].capitalize()95 query = "SELECT * FROM Authors WHERE firstName = %s AND lastName = %s;"96 cursor = db.execute_query(db_connection=db_connection, query=query, query_params=(fname, lname))97 authors = cursor.fetchall()98 if not authors:99 query = "INSERT INTO Authors (firstName, lastName) VALUES (%s, %s);"100 cursor = db.execute_query(db_connection=db_connection, query=query, query_params=(fname, lname))101 returnCode = '003'102 else:103 returnCode = '004'104 authors = (fname, lname)105 # Update an author106 if request.form['action'] == "edit_author":107 author_id = request.form['authorId']108 query = "UPDATE Authors set firstName = %s, lastName = %s WHERE authorId = %s;"109 cursor = db.execute_query(db_connection=db_connection, query=query, query_params = (request.form['firstName'],request.form['lastName'],request.form['authorId']))110 query = "SELECT * FROM Authors WHERE authorId = %s;"111 cursor = db.execute_query(db_connection=db_connection, query=query, query_params=(author_id,))112 authors = cursor.fetchall()113 returnCode = '002'114 # Delete an author.115 if request.method =='DELETE':116 id = str(request.json['id'])117 query = "SELECT * FROM BooksAuthors WHERE authorId = %s;"118 cursor = db.execute_query(db_connection=db_connection, query=query, query_params = (id,))119 authors = cursor.fetchall()120 if not authors: 121 query = "DELETE FROM Authors WHERE authorId = %s;"122 cursor = db.execute_query(db_connection=db_connection, query=query, query_params = (id,)) 123 return json.dumps({'result':'success'})124 return json.dumps({'result':'fail'})125 return render_template("authors.j2", authors = authors, returnCode = returnCode)126 127@app.route('/categories', methods=['POST', 'GET', 'DELETE'])128def categories():129 db_connection = db.connect_to_database()130 if request.method == 'GET':131 query = "SELECT * FROM Categories ORDER BY categoryId DESC LIMIT 10;"132 cursor = db.execute_query(db_connection=db_connection, query=query)133 categories = cursor.fetchall()134 returnCode = '001'135 136 if request.method == 'POST':137 # Search a category by name.138 if request.form['action'] == "search_category":139 category_name = request.form['search_category_name'].capitalize()140 query = "SELECT * FROM Categories WHERE categoryName = %s;"141 cursor = db.execute_query(db_connection=db_connection, query=query, query_params=(category_name,))142 categories = cursor.fetchall()143 returnCode = '002'144 if not categories:145 categories = None146 # Add a category by name.147 if request.form['action'] == "add_category":148 category_name = request.form['add_category_name'].capitalize()149 query = "SELECT * FROM Categories WHERE categoryName = %s;"150 cursor = db.execute_query(db_connection=db_connection, query=query, query_params=(category_name,))151 categories = cursor.fetchall()152 if not categories:153 query = "INSERT INTO Categories (categoryName) VALUES (%s);"154 cursor = db.execute_query(db_connection=db_connection, query=query, query_params=(category_name,))155 returnCode = '003'156 else:157 returnCode = '004'158 categories = (category_name,)159 # Update a category.160 if request.form['action'] == "edit_category":161 category_id = request.form['categoryId']162 query = "UPDATE Categories set categoryName = %s WHERE categoryId = %s;"163 cursor = db.execute_query(db_connection=db_connection, query=query, query_params=(request.form['category'],request.form['categoryId']))164 query = "SELECT * FROM Categories WHERE categoryId = %s;"165 cursor = db.execute_query(db_connection=db_connection, query=query, query_params=(category_id,))166 categories = cursor.fetchall()167 returnCode = '002'168 169 # Delete a category by name.170 if request.method =='DELETE':171 id = str(request.json['id'])172 query = "SELECT * FROM BooksCategories WHERE categoryId = %s;"173 cursor = db.execute_query(db_connection=db_connection, query=query, query_params = (id,))174 categories = cursor.fetchall()175 if not categories: 176 query = "DELETE FROM Categories WHERE categoryId = %s;"177 cursor = db.execute_query(db_connection=db_connection, query=query, query_params = (id,)) 178 return json.dumps({'result':'success'})179 return json.dumps({'result':'fail'})180 return render_template("categories.j2", categories=categories, returnCode = returnCode)181 182@app.route('/booksAuthors', methods=['POST', 'GET', 'DELETE'])183def bookAuthors():184 db_connection = db.connect_to_database()185 query = "SELECT * FROM Books order by title;"186 cursor = db.execute_query(db_connection=db_connection, query=query)187 books = cursor.fetchall()188 query = "SELECT * FROM Authors order by firstName;"189 cursor = db.execute_query(db_connection=db_connection, query=query)190 authors = cursor.fetchall()191 if request.method == 'GET':192 query = "SELECT BooksAuthors.bookId, title, authorId FROM BooksAuthors LEFT JOIN Books ON BooksAuthors.bookId = Books.bookId ORDER BY RAND() LIMIT 10;"193 cursor = db.execute_query(db_connection=db_connection, query=query)194 booksAuthors = cursor.fetchall()195 returnCode = '001'196 197 if request.method == 'POST':198 # Search a relationship by id.199 if request.form['action'] == "search_booksAuthors":200 method_ba, search_input = request.form['search_relation_by'], request.form['search_relation_input']201 if method_ba == "relation_book_id":202 query = "SELECT BooksAuthors.bookId, title, authorId FROM BooksAuthors LEFT JOIN Books ON BooksAuthors.bookId = Books.bookId WHERE BooksAuthors.bookId = %s;"203 cursor = db.execute_query(db_connection=db_connection, query=query, query_params=(search_input,))204 booksAuthors = cursor.fetchall()205 if method_ba == "relation_author_id":206 query = "SELECT BooksAuthors.bookId, title, authorId FROM BooksAuthors LEFT JOIN Books ON BooksAuthors.bookId = Books.bookId WHERE authorId = %s;"207 cursor = db.execute_query(db_connection=db_connection, query=query, query_params=(search_input,))208 booksAuthors = cursor.fetchall()209 returnCode = '002'210 if not booksAuthors:211 booksAuthors = None212 # Add a relationship by id.213 if request.form['action'] == "add_booksAuthors":214 author_id, book_id = request.form['add_author_id'], request.form['add_book_id']215 query = "SELECT * FROM BooksAuthors WHERE bookId = %s AND authorId = %s;"216 cursor = db.execute_query(db_connection=db_connection, query=query, query_params=(book_id, author_id))217 result_1 = cursor.fetchall()218 if not result_1:219 query = "SELECT * FROM Authors WHERE authorId = %s;"220 cursor = db.execute_query(db_connection=db_connection, query=query, query_params=(author_id,))221 result_2 = cursor.fetchall()222 query = "SELECT * FROM Books WHERE bookId = %s;"223 cursor = db.execute_query(db_connection=db_connection, query=query, query_params=(book_id,))224 result_3 = cursor.fetchall()225 if result_2 and result_3:226 query = "INSERT INTO BooksAuthors (bookId, authorId) VALUES (%s, %s);"227 cursor = db.execute_query(db_connection=db_connection, query=query, query_params=(book_id, author_id))228 returnCode = '003'229 else:230 returnCode = '005'231 else:232 returnCode = '004'233 booksAuthors = (book_id, author_id)234 # Update a relationship. 235 if request.form['action'] == "edit_book_author":236 book_id = request.form['bookId_ba']237 author_id = request.form['authorId_ba']238 author_id_old = request.form['authorId_old']239 query = "SELECT * FROM BooksAuthors WHERE bookId = %s AND authorId = %s;"240 cursor = db.execute_query(db_connection=db_connection, query=query, query_params=(book_id, author_id))241 result_1 = cursor.fetchall()242 if result_1:243 returnCode = '004'244 booksAuthors = (book_id, author_id)245 else:246 query = "SELECT * FROM Authors WHERE authorId = %s;"247 cursor = db.execute_query(db_connection=db_connection, query=query, query_params=(author_id,))248 result = cursor.fetchall()249 if not result:250 returnCode = '005'251 booksAuthors = (book_id, author_id)252 else:253 query = "UPDATE BooksAuthors set authorId = %s WHERE bookId = %s AND authorId = %s;"254 cursor = db.execute_query(db_connection=db_connection, query=query, query_params=(author_id, book_id, author_id_old))255 query = "SELECT BooksAuthors.bookId, title, authorId FROM BooksAuthors LEFT JOIN Books ON BooksAuthors.bookId = Books.bookId WHERE BooksAuthors.bookId = %s AND authorId = %s;"256 cursor = db.execute_query(db_connection=db_connection, query=query, query_params=(book_id, author_id))257 booksAuthors = cursor.fetchall()258 returnCode = '002'259 260 # Delete a category by name.261 if request.method =='DELETE':262 id_1, id_2 = str(request.json['id_1']), str(request.json['id_2'])263 query = "DELETE FROM BooksAuthors WHERE bookId = %s AND authorId = %s;"264 cursor = db.execute_query(db_connection=db_connection, query=query, query_params = (id_1, id_2)) 265 return json.dumps({'result':'success'})266 # Update an category 267 return render_template("booksAuthors.j2", booksAuthors=booksAuthors, returnCode=returnCode, books=books, authors=authors)268 269@app.route('/booksCategories', methods=['POST', 'GET', 'DELETE'])270def bookCategories():271 db_connection = db.connect_to_database()272 query = "SELECT * FROM Categories order by categoryName;"273 cursor = db.execute_query(db_connection=db_connection, query=query)274 categories = cursor.fetchall()275 query = "SELECT * FROM Books order by title;"276 cursor = db.execute_query(db_connection=db_connection, query=query)277 books = cursor.fetchall()278 if request.method == 'GET':279 query = "SELECT BooksCategories.bookId, title, categoryId FROM BooksCategories LEFT JOIN Books ON BooksCategories.bookId = Books.bookId ORDER BY RAND() LIMIT 10;"280 cursor = db.execute_query(db_connection=db_connection, query=query)281 booksCategories = cursor.fetchall()282 returnCode = '001'283 284 if request.method == 'POST':285 # Search a relationship by id.286 if request.form['action'] == "search_booksCategories":287 method_ba, search_input = request.form['search_relation_by'], request.form['search_relation_input']288 if method_ba == "relation_book_id":289 query = "SELECT BooksCategories.bookId, title, categoryId FROM BooksCategories LEFT JOIN Books ON BooksCategories.bookId = Books.bookId WHERE BooksCategories.bookId = %s;"290 cursor = db.execute_query(db_connection=db_connection, query=query, query_params=(search_input,))291 booksCategobooksAuthorsries = cursor.fetchall()292 if method_ba == "relation_category_id":293 query = "SELECT BooksCategories.bookId, title, categoryId FROM BooksCategories LEFT JOIN Books ON BooksCategories.bookId = Books.bookId WHERE categoryId = %s;"294 cursor = db.execute_query(db_connection=db_connection, query=query, query_params=(search_input,))295 booksCategories = cursor.fetchall()296 returnCode = '002'297 if not booksCategories:298 booksCategories = None299 # Add a relationship by id.300 if request.form['action'] == "add_booksCategories":301 category_id, book_id = request.form['add_category_id'], request.form['add_book_id']302 query = "SELECT * FROM BooksCategories WHERE bookId = %s AND categoryId = %s;"303 cursor = db.execute_query(db_connection=db_connection, query=query, query_params=(book_id, category_id))304 result_1 = cursor.fetchall()305 if not result_1:306 query = "SELECT * FROM Categories WHERE categoryId = %s;"307 cursor = db.execute_query(db_connection=db_connection, query=query, query_params=(category_id,))308 result_2 = cursor.fetchall()309 query = "SELECT * FROM Books WHERE bookId = %s;"310 cursor = db.execute_query(db_connection=db_connection, query=query, query_params=(book_id,))311 result_3 = cursor.fetchall()312 if result_2 and result_3:313 query = "INSERT INTO BooksCategories (bookId, categoryId) VALUES (%s, %s);"314 cursor = db.execute_query(db_connection=db_connection, query=query, query_params=(book_id, category_id))315 returnCode = '003'316 else:317 returnCode = '005'318 else:319 returnCode = '004'320 booksCategories = (book_id, category_id)321 # Update a relationship. 322 if request.form['action'] == "edit_book_category":323 book_id = request.form['bookId_bc']324 category_id = request.form['categoryId_bc']325 category_id_old = request.form['category_id_old']326 query = "SELECT * FROM BooksCategories WHERE bookId = %s AND categoryId = %s;"327 cursor = db.execute_query(db_connection=db_connection, query=query, query_params=(book_id, category_id))328 result_1 = cursor.fetchall()329 if result_1:330 returnCode = '004'331 booksCategories = (book_id, category_id)332 else:333 query = "SELECT * FROM Categories WHERE categoryId = %s;"334 cursor = db.execute_query(db_connection=db_connection, query=query, query_params=(category_id,))335 result = cursor.fetchall()336 if not result:337 returnCode = '005'338 booksCategories = (book_id, category_id)339 else:340 query = "UPDATE BooksCategories set categoryId = %s WHERE bookId = %s and categoryId = %s;"341 cursor = db.execute_query(db_connection=db_connection, query=query, query_params=(category_id, book_id, category_id_old))342 query = "SELECT BooksCategories.bookId, title, categoryId FROM BooksCategories LEFT JOIN Books ON BooksCategories.bookId = Books.bookId WHERE BooksCategories.bookId = %s AND BooksCategories.categoryId = %s;"343 cursor = db.execute_query(db_connection=db_connection, query=query, query_params=(book_id, category_id))344 booksCategories = cursor.fetchall()345 returnCode = '002'346 347 # Delete a category by name.348 if request.method =='DELETE':349 id_1, id_2 = str(request.json['id_1']), str(request.json['id_2'])350 query = "DELETE FROM BooksCategories WHERE bookId = %s AND categoryId = %s;"351 cursor = db.execute_query(db_connection=db_connection, query=query, query_params = (id_1, id_2)) 352 return json.dumps({'result':'success'})353 # Update an category 354 return render_template("booksCategories.j2", booksCategories=booksCategories, returnCode=returnCode, categories=categories,books=books)355@app.route('/copies', methods=['POST', 'GET', 'DELETE'])356def copies():357 db_connection = db.connect_to_database()358 if request.method == 'GET':359 query = "SELECT * FROM Copies ORDER BY copyId DESC LIMIT 10;"360 cursor = db.execute_query(db_connection=db_connection, query=query)361 copies = cursor.fetchall()362 returnCode = '001'363 364 if request.method == 'POST':365 # Search a copy by ID.366 if request.form['action'] == "search_copy":367 book_id = request.form['book_id']368 query = "SELECT * FROM Copies WHERE bookId = %s;"369 cursor = db.execute_query(db_connection=db_connection, query=query, query_params=(book_id,))370 copies = cursor.fetchall()371 returnCode = '002'372 if not copies:373 copies = None374 # Add a copy by name.375 if request.form['action'] == "add_copy":376 book_id, condition = request.form['book_id_add'], request.form['condition']377 query = "SELECT * FROM Books WHERE bookId = %s;"378 cursor = db.execute_query(db_connection=db_connection, query=query, query_params=(book_id,))379 books = cursor.fetchall()380 if not books:381 returnCode = '004'382 else:383 query = "SELECT count(copyId) AS count FROM Copies WHERE bookId = %s;" 384 cursor = db.execute_query(db_connection=db_connection, query=query, query_params=(book_id,))385 copy_count = cursor.fetchall()386 copy_count = copy_count[0]['count']387 if copy_count == 3:388 returnCode ='005'389 else:390 copy_num = copy_count + 1391 query = "INSERT INTO Copies (bookId, copyNum, bookCondition) VALUES (%s, %s, %s);"392 cursor = db.execute_query(db_connection=db_connection, query=query, query_params=(book_id, copy_num, condition))393 returnCode = '003'394 copies = (book_id, condition)395 # Update a copy.396 if request.form['action'] == "edit_copy":397 copy_id = request.form['copyId']398 book_status = request.form['bookStatus']399 book_condition = request.form['bookCondition']400 query = "UPDATE Copies set bookCondition = %s, status = %s WHERE copyId = %s;"401 cursor = db.execute_query(db_connection=db_connection, query=query, query_params = (book_condition, book_status, copy_id))402 query = "SELECT * FROM Copies WHERE copyId = %s;"403 cursor = db.execute_query(db_connection=db_connection, query=query, query_params=(copy_id,))404 copies = cursor.fetchall()405 returnCode = '002'406 407 # Delete a copy.408 if request.method == 'DELETE':409 id = str(request.json['id'])410 query = "SELECT * FROM BorrowRecords WHERE copyId = %s;"411 cursor = db.execute_query(db_connection=db_connection, query=query, query_params = (id,))412 copies = cursor.fetchall()413 if not copies:414 query = "DELETE FROM Copies WHERE copyId = %s;"415 cursor = db.execute_query(db_connection=db_connection, query=query, query_params = (id,))416 return json.dumps({'result':'success'})417 return json.dumps({'result':'fail'})418 return render_template("copies.j2", copies=copies, returnCode=returnCode)419@app.route('/members', methods=['POST', 'GET', 'DELETE'])420def members():421 db_connection = db.connect_to_database()422 if request.method == 'GET':423 query = "SELECT * FROM Members ORDER BY memId DESC LIMIT 10;"424 cursor = db.execute_query(db_connection=db_connection, query=query)425 members = cursor.fetchall()426 returnCode = '001'427 if request.method == 'POST':428 # Search a member by name.429 if request.form['action'] == "search_member":430 fname, lname = request.form['fname'].capitalize(), request.form['lname'].capitalize()431 query = "SELECT * FROM Members WHERE firstName = %s AND lastName = %s;"432 cursor = db.execute_query(db_connection=db_connection, query=query, query_params=(fname, lname))433 members = cursor.fetchall()434 returnCode = '002'435 if not members:436 members = None437 # Add a member by name.438 if request.form['action'] == "add_member":439 fname, lname, address, email, phone = request.form['add_first'].capitalize(), request.form['add_last'].capitalize(), request.form['add_address'].capitalize(), request.form['add_email'], request.form['add_phone']440 query = "SELECT * FROM Members WHERE firstName = %s AND lastName = %s AND memCell = %s;"441 cursor = db.execute_query(db_connection=db_connection, query=query, query_params=(fname, lname, phone))442 members = cursor.fetchall()443 if not members:444 query = "INSERT INTO Members (firstName, lastName, memAddress, memEmail, memCell) VALUES (%s, %s, %s, %s, %s);"445 cursor = db.execute_query(db_connection=db_connection, query=query, query_params=(fname, lname,address,email,phone))446 returnCode = '003'447 else:448 returnCode = '004'449 members = (fname, lname)450 # Update a member.451 if request.form['action'] == "edit_member":452 member_id = request.form['memId']453 first_name = request.form['firstName']454 last_name =request.form['lastName']455 address = request.form['homeAddress']456 email = request.form['email']457 cell = request.form['phone']458 query = "UPDATE Members set firstName = %s, lastName = %s, memAddress = %s, memEmail = %s, memCell = %s WHERE memId = %s;"459 cursor = db.execute_query(db_connection=db_connection, query=query, query_params = (first_name, last_name, address, email, cell, member_id))460 query = "SELECT * FROM Members WHERE memId = %s;"461 cursor = db.execute_query(db_connection=db_connection, query=query, query_params=(member_id,))462 members = cursor.fetchall()463 returnCode = '002'464 465 # Delete a member.466 if request.method == 'DELETE':467 id = str(request.json['id'])468 query = "SELECT * FROM BorrowRecords WHERE memId = %s;"469 cursor = db.execute_query(db_connection=db_connection, query=query, query_params = (id,))470 members = cursor.fetchall()471 if not members:472 query = "DELETE FROM Members WHERE memId = %s;"473 cursor = db.execute_query(db_connection=db_connection, query=query, query_params = (id,))474 return json.dumps({'result':'success'})475 return json.dumps({'result':'fail'})476 return render_template("members.j2", members=members, returnCode=returnCode)477@app.route('/borrowRecords', methods=['GET', 'POST','DELETE'])478def borrowRecords():479 db_connection = db.connect_to_database()480 query = "SELECT * FROM Members order by memId;"481 cursor = db.execute_query(db_connection=db_connection, query=query)482 members = cursor.fetchall()483 query = "SELECT * FROM Copies where status != 'On Loan' order by copyId;"484 cursor = db.execute_query(db_connection=db_connection, query=query)485 copies = cursor.fetchall()486 if request.method == 'GET':487 query = "SELECT * FROM BorrowRecords ORDER BY borrowId DESC LIMIT 10;"488 cursor = db.execute_query(db_connection=db_connection, query=query)489 borrowRecords = cursor.fetchall()490 returnCode = '001'491 492 if request.method == 'POST':493 # Search a borrow record by member id.494 if request.form['action'] == "search_borrowRecords": # input type hidden action and value495 memId_bc = request.form['memId']496 query = "SELECT * FROM BorrowRecords WHERE memId = %s;"497 cursor = db.execute_query(db_connection=db_connection, query=query, query_params=(memId_bc,))498 borrowRecords = cursor.fetchall()499 print(borrowRecords)500 returnCode = '002'501 if not borrowRecords:502 borrowRecords = None503 # Add a borrow record 504 if request.form['action'] == "add_borrow_record":505 member_id = request.form['member_id']506 copy_id = request.form['copy_id']507 borrow_date = request.form['borrow_date']508 due_date = request.form['due_date']509 510 query = "SELECT * FROM BorrowRecords WHERE memId = %s AND copyId = %s;"511 cursor = db.execute_query(db_connection=db_connection, query=query, query_params=(member_id, copy_id))512 borrowed = cursor.fetchall()513 if not borrowed:514 query = "SELECT * FROM Members WHERE memId = %s;"515 cursor = db.execute_query(db_connection=db_connection, query=query, query_params=(member_id,))516 result_2 = cursor.fetchall()517 query = "SELECT * FROM Copies WHERE copyId = %s and status != 'On Loan';"518 cursor = db.execute_query(db_connection=db_connection, query=query, query_params=(copy_id,))519 result_3 = cursor.fetchall()520 if result_2 and result_3:521 query = "INSERT INTO BorrowRecords (memId, copyId, borrowDate, dueDate) VALUES (%s, %s, %s, %s);"522 cursor = db.execute_query(db_connection=db_connection, query=query, query_params=(member_id, copy_id,borrow_date,due_date))523 returnCode = '003'524 else:525 returnCode = '005'526 else:527 returnCode = '004'528 borrowRecords = (member_id, copy_id,borrow_date,due_date)529 530 # Update a borrow Record.531 if request.form['action'] == "edit_borrow_record":532 borrowId = request.form['borrowId']533 memId = request.form['memId']534 copyId =request.form['copyId']535 borrowDate = request.form['borrowDate']536 dueDate = request.form['dueDate']537 passDue = request.form['passDue']538 query = "UPDATE BorrowRecords set memId = %s, copyId = %s, borrowDate = %s, dueDate = %s, passDue = %s WHERE borrowId = %s;"539 cursor = db.execute_query(db_connection=db_connection, query=query, query_params = (memId, copyId, borrowDate, dueDate, passDue,borrowId))540 query = "SELECT * FROM BorrowRecords WHERE borrowId = %s;"541 cursor = db.execute_query(db_connection=db_connection, query=query, query_params=(borrowId,))542 borrowRecords = cursor.fetchall()543 returnCode = '002'544 545 # Delete a member.546 if request.method == 'DELETE':547 id = str(request.json['id'])548 query = "DELETE FROM BorrowRecords WHERE borrowId = %s;"549 cursor = db.execute_query(db_connection=db_connection, query=query, query_params = (id,))550 members = cursor.fetchall()551 return json.dumps({'result':'success'})552 553 return render_template("borrowRecords.j2", borrowRecords=borrowRecords, returnCode=returnCode, members=members, copies=copies)554# Listener555if __name__ == "__main__":556 port = int(os.environ.get('PORT', 3000)) 557 # ^^^^558 # You can replace this number with any valid port559 ...

Full Screen

Full Screen

webapp.py

Source:webapp.py Github

copy

Full Screen

...58 #check if an employee_ID was entered59 if emp_ID == "NULL":60 query = "INSERT INTO customers (first_name, last_name, email, phone_number) VALUES (%s, %s, %s, %s)"61 data = (f_name, l_name, email, phone)62 result = execute_query(db_connection, query, data)63 print("Insert result, null emp - ", result)64 else:65 query = "INSERT INTO customers (first_name, last_name, email, phone_number, employee_ID) VALUES (%s, %s, %s, %s, %s)"66 data = (f_name, l_name, email, phone, emp_ID)67 result = execute_query(db_connection, query, data)68 print("Insert result, NOT null emp - ", result)69 print("Customer added")70 return redirect(url_for('customers'))71@app.route('/update_customer/<int:id>', methods=["GET", "POST"])72def update_customer(id):73 db_connection = connect_to_database()74 print("Update customer start")75 if request.method == "GET":76 print("Getting customer record")77 cust_q = "SELECT customer_ID, first_name, last_name, email, phone_number, employee_ID FROM customers WHERE customer_ID = %s" % (id)78 cust_result = execute_query(db_connection, cust_q).fetchone()79 if cust_result == None:80 return "Could not find customer"81 emp_q = "SELECT employee_ID, first_name, last_name FROM employees"82 emp_result = execute_query(db_connection, emp_q).fetchall()83 print("Employee results for update customer")84 print(emp_result)85 return render_template('customer_update.html', customer = cust_result, emp_list = emp_result)86 elif request.method == "POST":87 print("Updating customer")88 # Get data from the user edit on page89 cust_id = id90 fname = request.form['first_name']91 lname = request.form['last_name']92 email = request.form['email']93 phone = request.form['phone_number']94 emp_ID = request.form['employee_id']95 print("Printing form fields")96 print(request.form)97 if emp_ID == "NULL":98 print("User trying to set NULL employee")99 query = """UPDATE customers SET employee_ID = NULL, first_name = %s, last_name = %s, email = %s, phone_number = %s100 WHERE customer_id = %s"""101 data = (fname, lname, email, phone, cust_id)102 result = execute_query(db_connection, query, data)103 else:104 print("User not setting NULL employee")105 query = "UPDATE customers SET first_name = %s, last_name = %s, email = %s, phone_number = %s, employee_ID = %s WHERE customer_id = %s"106 data = (fname, lname, email, phone, emp_ID, cust_id)107 result = execute_query(db_connection, query, data)108 print("Customer updated")109 return redirect(url_for('customers'))110 #return "Customer updated"111'''112----------------------------------------------------------------------113This section covers the Employees routing/query handling114----------------------------------------------------------------------115'''116@app.route('/employees')117def employees():118 print("Employees page rendering")119 cur = mysql.connection.cursor()120 query = """SELECT employees.employee_ID, employees.first_name, employees.last_name, employees.job_title, 121 warehouse_locations.location_city, warehouse_locations.location_ID FROM employees LEFT JOIN warehouse_locations122 ON employees.location_ID = warehouse_locations.location_ID;"""123 cur.execute(query)124 result = cur.fetchall()125 print(result)126 print("employee query pull success")127 query_loc = "SELECT location_ID, location_city FROM warehouse_locations;"128 db_connection = connect_to_database()129 result_loc = execute_query(db_connection, query_loc)130 print("Location Results for form fill")131 print(result_loc)132 return render_template('employees.html', employees = result, locations = result_loc)133@app.route('/add_emp', methods=["GET", "POST"])134def add_emp():135 print("Adding an employee")136 f_name = request.form["first_name"]137 l_name = request.form["last_name"]138 title = request.form["job_title"]139 loc = request.form["location"]140 print("First name is: ", f_name)141 if loc == "NULL":142 print("Employee does not have a location")143 query = "INSERT INTO employees (first_name, last_name, job_title) VALUES (%s, %s, %s)"144 data = (f_name, l_name, title)145 else:146 query = "INSERT INTO employees (first_name, last_name, job_title, location_ID) VALUES (%s, %s, %s, %s)"147 data = (f_name, l_name, title, loc)148 db_connection = connect_to_database()149 execute_query(db_connection, query, data)150 return redirect(url_for('employees'))151'''152----------------------------------------------------------------------153This section covers the ORDERS routing/query handling154----------------------------------------------------------------------155'''156@app.route('/orders')157def orders():158 print("Orders page rendering")159 cur = mysql.connection.cursor()160 query = "SELECT order_ID, invoice_ID, order_amount, product_serial_number FROM orders;"161 cur.execute(query)162 result = cur.fetchall()163 print(result)164 print("order query pull success")165 print("pulling invoices for add dropdown functionality")166 query_inv = "SELECT invoice_ID FROM invoices;"167 cur.execute(query_inv)168 result_inv = cur.fetchall()169 print(result_inv)170 print("pulling products for add dropdown")171 query_prod = "SELECT product_serial_number, product_brand, product_model FROM product_inventory"172 cur.execute(query_prod)173 result_prod = cur.fetchall()174 print(result_prod)175 return render_template('orders.html', orders = result, invoices = result_inv, products = result_prod)176@app.route('/add_order', methods=["GET", "POST"])177def add_order():178 print("Adding an order")179 inv_ID = request.form["invoice_ID"]180 ord_amt = request.form["order_amount"]181 prod_serNo = request.form["product_serial_number"]182 print("Invoice ID is: ", inv_ID)183 db_connection = connect_to_database()184 if inv_ID == "NULL":185 print("User trying to set null invoice")186 query = """INSERT INTO orders (invoice_ID, order_amount, product_serial_number) VALUES (NULL, %s, %s)"""187 data = (ord_amt, prod_serNo)188 result = execute_query(db_connection, query, data)189 else:190 print("User not trying to set null")191 query = """INSERT INTO orders (invoice_ID, order_amount, product_serial_number) VALUES (%s, %s, %s)"""192 data = (inv_ID, ord_amt, prod_serNo)193 result = execute_query(db_connection, query, data)194 print("New order added!")195 return redirect(url_for('orders'))196@app.route('/update_order/<int:id>', methods=["GET","POST"])197def update_order(id):198 db_connection = connect_to_database()199 print("Update order start")200 if request.method == "GET":201 print("Getting order record")202 ord_q = "SELECT order_ID, invoice_ID, order_amount, product_serial_number FROM orders WHERE order_ID = %s" % (id)203 ord_result = execute_query(db_connection, ord_q).fetchone()204 inv_list_q = "SELECT invoice_ID FROM invoices"205 inv_list_r = execute_query(db_connection, inv_list_q).fetchall()206 prod_serNo_q = "SELECT product_serial_number, product_brand, product_model FROM product_inventory"207 prod_serNo_r = execute_query(db_connection, prod_serNo_q).fetchall()208 print("Invoice results: ")209 print(inv_list_r)210 print("Product results: ")211 print(prod_serNo_r)212 if ord_result == None:213 return "Could not find order"214 return render_template('update_order.html', order = ord_result, inv_list = inv_list_r, prods = prod_serNo_r)215 elif request.method == "POST":216 print("Updating order")217 # Get data from the user edit on page218 ord_id = id219 inv_id = request.form['invoice_id']220 ord_amt = request.form['order_amt']221 prod_serNo = request.form['prod_serNo']222 print("Request form: ")223 print(request.form)224 if inv_id == "NULL":225 print("User trying to set null")226 query = """UPDATE orders SET invoice_ID = NULL, order_amount = %s, product_serial_number = %s227 WHERE order_id = %s"""228 data = (ord_amt, prod_serNo, ord_id)229 result = execute_query(db_connection, query, data)230 else:231 print("User not trying to set null")232 query = """UPDATE orders SET invoice_ID = %s, order_amount = %s, product_serial_number = %s 233 WHERE order_id = %s"""234 data = (inv_id, ord_amt, prod_serNo, ord_id)235 result = execute_query(db_connection, query, data)236 print("Order updated")237 return redirect(url_for('orders'))238'''239----------------------------------------------------------------------240This section covers the WAREHOUSE INVENTORY routing/query handling241----------------------------------------------------------------------242'''243@app.route('/wh_inv')244def wh_inv():245 print("Warehouse Inventory page rendering")246 cur = mysql.connection.cursor()247 # OLD QUERY: query = "SELECT location_ID, product_serial_number FROM warehouse_inventory;"248 # NEW QUERY WITH JOIN249 query = """SELECT warehouse_inventory.location_ID, warehouse_inventory.product_serial_number, warehouse_locations.location_city, 250 product_inventory.product_brand, product_inventory.product_model, warehouse_inventory.inventory_ID, warehouse_inventory.stock_quantity251 FROM `warehouse_inventory` LEFT JOIN warehouse_locations ON warehouse_inventory.location_ID = warehouse_locations.location_ID 252 LEFT JOIN product_inventory ON warehouse_inventory.product_serial_number = product_inventory.product_serial_number;"""253 cur.execute(query)254 result = cur.fetchall()255 print(result)256 print("warehouse Inventory query pull success")257 #query for locations dropdown menu258 query_locs = "SELECT location_ID, location_city FROM warehouse_locations"259 db_connection = connect_to_database()260 result_locs = execute_query(db_connection, query_locs).fetchall()261 print("Location results")262 print(result_locs)263 #query for serial number dropdown menu264 query_serNos = "SELECT product_serial_number, product_brand, product_model FROM product_inventory"265 db_connection = connect_to_database()266 result_serNos = execute_query(db_connection, query_serNos).fetchall()267 print("Product results")268 print(result_serNos)269 return render_template('warehouse_inventory.html', wh_inv = result, locs = result_locs, prods = result_serNos)270@app.route('/add_whInv', methods = ["POST"])271def add_inv():272 print("Adding inventory to a location")273 loc_ID = request.form["location_ID"]274 prod_serNo = request.form["product_serial_number"]275 prod_qty = request.form["stock_quantity"]276 print("TEST: location is ", loc_ID)277 query = "INSERT INTO warehouse_inventory (location_ID, product_serial_number, stock_quantity) VALUES (%s, %s, %s)"278 data = (loc_ID, prod_serNo, prod_qty)279 db_connection = connect_to_database()280 execute_query(db_connection, query, data)281 return redirect(url_for('wh_inv'))282@app.route('/delete_whInv/<int:id>', methods = ["GET", "POST"])283def delete_whInv(id):284 print("Deleting inventory from location")285 query = "DELETE FROM warehouse_inventory WHERE inventory_ID = %s"286 data = (id, )287 db_connection = connect_to_database()288 execute_query(db_connection, query, data)289 return redirect(url_for('wh_inv'))290'''291----------------------------------------------------------------------292This section covers the INVOICES routing/query handling293----------------------------------------------------------------------294'''295@app.route('/Invoices')296def browse_invoices():297 """This function displays the invoices from Invoices.html"""298 print("Fetching and rendering invoices web page")299 db_connection = connect_to_database()300 query = """SELECT customer_id, invoice_id, employee_id, payment_date_year, payment_date_month,301 payment_date_dayOfMonth, payment_amount, payment_method, invoice_amount from invoices;"""302 result = execute_query(db_connection, query).fetchall()303 print(result)304 query_emp = "SELECT employee_ID, first_name, last_name FROM employees;"305 result_emp = execute_query(db_connection, query_emp).fetchall()306 print("Employee names:")307 print(result_emp)308 return render_template('Invoices.html', rows=result, employees=result_emp)309@app.route('/Invoices', methods=['POST'])310def add_new_invoice():311 """This adds the form functionality to insert into the invoices table"""312 db_connection = connect_to_database()313 print("Add new invoice!")314 employee_id = request.form['employee_id']315 payment_date_year = request.form['payment_date_year']316 payment_date_month = request.form['payment_date_month']317 payment_date_dayOfMonth = request.form['payment_date_dayOfMonth']318 payment_amount = request.form['payment_amount']319 payment_method = request.form['payment_method']320 invoice_amount = request.form['invoice_amount']321 query = """INSERT INTO invoices (employee_id, payment_date_year, payment_date_month,322 payment_date_dayOfMonth, payment_amount, payment_method, invoice_amount) 323 VALUES (%s,%s,%s,%s,%s,%s,%s)"""324 data = (employee_id, payment_date_year, payment_date_month,325 payment_date_dayOfMonth, payment_amount, payment_method, invoice_amount)326 execute_query(db_connection, query, data)327 print("Invoice added")328 return redirect(url_for('browse_invoices')) # redirect goes to the defined function, not the app.route name329'''330----------------------------------------------------------------------331This section covers the PRODUCT INVENTORY routing/query handling332----------------------------------------------------------------------333'''334@app.route('/product_inventory', methods=['GET'])335def browse_products():336 """Display all the products and also has functionality for the drop down list."""337 print("Fetching and rendering product inventory web page")338 db_connection = connect_to_database()339 type_filter = request.args.get('type_filter')340 # dropdown menu items pull for filter on page341 type_q = "SELECT product_type FROM product_inventory;"342 result_types = execute_query(db_connection, type_q).fetchall()343 print("Bike types for dropdown: ", result_types)344 if type_filter == "All" or type_filter is None:345 query = """SELECT product_serial_number, product_type, product_brand, product_year, product_model,346 product_invoice_price, product_retail_price, product_size 347 FROM product_inventory;"""348 result = execute_query(db_connection, query).fetchall()349 print(result)350 if type_filter is None:351 type_filter = "All"352 print("Type filter is: ", type_filter)353 return render_template('product_inventory.html', rows=result, types=result_types, filter=type_filter)354 else:355 query = """SELECT product_serial_number, product_type, product_brand, product_year, product_model,356 product_invoice_price, product_retail_price, product_size 357 FROM product_inventory358 WHERE product_type = %s;"""359 data = (type_filter,)360 result = execute_query(db_connection, query, data).fetchall()361 print(result)362 print("Type filter is: ", type_filter)363 return render_template('product_inventory.html', rows=result, types=result_types, filter=type_filter)364@app.route('/product_inventory', methods=['POST'])365def add_product():366 """Function for inserting inventory into the product table."""367 db_connection = connect_to_database()368 print("Add new product!")369 #product_serial_number = request.form['product_serial_number']370 product_type = request.form['product_type']371 product_brand = request.form['product_brand']372 product_year = request.form['product_year']373 product_model = request.form['product_model']374 product_invoice_price = request.form['product_invoice_price']375 product_retail_price = request.form['product_retail_price']376 product_size = request.form['product_size']377 query = """INSERT INTO product_inventory (product_type, product_brand, product_year,378 product_model, product_invoice_price, product_retail_price, product_size)379 VALUES (%s,%s,%s,%s,%s,%s,%s)"""380 data = (product_type, product_brand, product_year,381 product_model, product_invoice_price, product_retail_price, product_size)382 execute_query(db_connection, query, data)383 print("Product added!")384 return redirect(url_for('browse_products'))385 # redirect goes to the defined function, not the app.route name386'''387----------------------------------------------------------------------388This section covers the WAREHOUSE LOCATIONS routing/query handling389----------------------------------------------------------------------390'''391@app.route('/warehouse_locations')392def browse_locations():393 """Display the warehouse locations."""394 print("Fetching and rendering people web page")395 db_connection = connect_to_database()396 query = """SELECT location_ID, location_street_address, location_city, location_state, location_zip397 from warehouse_locations;"""398 result = execute_query(db_connection, query).fetchall()399 print(result)400 return render_template('warehouse_locations.html', rows=result)401@app.route('/warehouse_locations', methods=['POST'])402def add_new_location():403 """Functionality to add locations via the form."""404 db_connection = connect_to_database()405 print("Add new location!")406 #location_ID = request.form['location_ID']407 location_street_address = request.form['location_street_address']408 location_city = request.form['location_city']409 location_state = request.form['location_state']410 location_zip = request.form['location_zip']411 query = """INSERT INTO warehouse_locations (location_street_address, location_city, location_state,412 location_zip) VALUES (%s,%s,%s,%s)"""413 data = (location_street_address, location_city, location_state, location_zip)414 execute_query(db_connection, query, data)415 print("Location added!")416 return redirect(url_for('browse_locations'))417 # redirect goes to the defined function, not the app.route name418'''419----------------------------------------------------------------------420This section covers the errors routing/query handling421----------------------------------------------------------------------422'''423@app.errorhandler(404)424def page_not_found(error):425 return render_template('404.html')426@app.errorhandler(500)427def page_not_found(error):428 return render_template('500.html')

Full Screen

Full Screen

yelp_api.py

Source:yelp_api.py Github

copy

Full Screen

...6 self.user = "user_yelp"7 self.password = "user_yelp"8 self.host = "192.168.2.208"9 self.database = "YELP_DB"10 def execute_query(self, query):11 try:12 # replace user and password with credentials for mysql shell user with YELP_DB full access13 # replace host with VM IP address (VM network setup as bridged adapter from virtualbox)14 cnx = mysql.connector.connect(user=self.user, password=self.password,15 host=self.host, database=self.database)16 cursor = cnx.cursor()17 cursor.execute(query)18 res = [x for x in cursor]19 cnx.commit()20 cursor.close()21 22 return res23 except mysql.connector.Error as err:24 if err.errno == errorcode.ER_ACCESS_DENIED_ERROR:25 print("Something is wrong with your user name or password")26 elif err.errno == errorcode.ER_BAD_DB_ERROR:27 print("Database does not exist")28 else:29 print(err)30 else:31 cnx.close()32 # In all API functions below, we return -n for an error in the nth argument passed33 # to the function, return 0 for success, and an error message is thrown by the 34 # execute_query() helper above if there is a database exception.35 def login_user(self, user_id):36 # validate that current user exists in User table37 q1 = self.execute_query(\38 "select count(*) from User where user_id = '{}'".format(user_id))39 if q1[0][0] == 0:40 # user_id doesn't exist! Please login with a valid user_id...41 return -142 return 043 def post_review(self, user_id, business_id, stars, text):44 # validate business exists45 qV = self.execute_query(\46 "select count(*) from Business where business_id = '{}'".format(business_id))47 if qV[0][0] == 0:48 return -249 today_date = datetime.date.today().isoformat()50 self.execute_query("insert into Review (user_id, business_id, stars, date, text)" +\51 "values ('{}', '{}', '{}', '{}', '{}')".format(\52 user_id, business_id, stars, today_date, text))53 return 054 def follow_user(self, user_id, following_user_id):55 # validate that both user being followed exists56 qV = self.execute_query(\57 "select count(*) from User where user_id = '{}'".format(following_user_id))58 if qV[0][0] == 0:59 return -260 self.execute_query("insert into UserFollowers (user_id, follower_id)" +\61 "values ('{}', '{}')".format(following_user_id, user_id))62 return 063 def follow_business(self, user_id, business_id):64 # validate business exists65 qV = self.execute_query(\66 "select count(*) from Business where business_id = '{}'".format(business_id))67 if qV[0][0] == 0:68 return -269 self.execute_query("insert into BusinessFollowers (business_id, user_id)" +\70 "values ('{}', '{}')".format(business_id, user_id))71 return 072 def follow_category(self, user_id, category):73 # validate category exists74 qV = self.execute_query(\75 "select count(*) from BusinessCategories where category = '{}'".format(category))76 if qV[0][0] == 0:77 return -278 self.execute_query("insert into CategoryFollowers (category, user_id)" +\79 "values ('{}', '{}')".format(category, user_id))80 return 081 # returns review_ids if num_posts_limit is 0, and 82 # otherwise returns the limited number of full reviews83 def get_latest_posts(self, user_id, num_posts_limit = 0):84 # determine when user was last online (when they last read from all topics)85 last_online = self.execute_query(\86 "select last_online from User where user_id = '{}'".format(user_id))87 last_online = last_online[0][0]88 # find all users user follows89 users_followed = self.execute_query(\90 "select user_id from UserFollowers where follower_id = '{}'".format(user_id))91 if not users_followed:92 users_followed = "('')"93 else:94 users_followed = tuple(str(x[0]) for x in users_followed)95 if len(users_followed) == 1:96 # single element tuple has string form of "(e,)"; remove comma97 users_followed = str(users_followed).replace(",", "")98 else:99 users_followed = str(users_followed)100 101 # find all businesses user follows (or within categories user is interested in)102 query1 = "select distinct business_id from BusinessCategories where category in"+\103 " (select category from CategoryFollowers where user_id = '{}')".format(user_id)104 query2 = "select business_id from BusinessFollowers where user_id = '{}'".format(user_id)105 union_query = "select * from ( "+query1+" )bizInLikedCategory union ( "+query2+" )"106 businesses_followed = self.execute_query(union_query)107 if not businesses_followed:108 businesses_followed = "('')"109 else:110 businesses_followed = tuple(str(x[0]) for x in businesses_followed)111 if len(businesses_followed) == 1:112 # single element tuple has string form of "(e,)"; remove comma113 businesses_followed = str(businesses_followed).replace(",", "")114 else:115 businesses_followed = str(businesses_followed)116 # find latests posts from all followed topics/users since last read117 posts_query = "select distinct * from Review where date > '{}' and (user_id in {} or business_id in {}) order by date desc".format(\118 last_online, users_followed, businesses_followed)119 120 if num_posts_limit == 0:121 posts_query = self.execute_query(posts_query)122 # return list of review_ids123 return [p[0] for p in posts_query]124 else:125 posts_query = self.execute_query(posts_query + " limit {}".format(num_posts_limit))126 # return list of review items (dictionaries)127 posts = []128 for p in posts_query:129 posts.append({"review_id": p[0], "user_id": p[1], "business_id": p[2], "stars": p[3], "date": p[4],130 "text": p[5], "useful": p[6], "funny": p[7], "cool": p[8]})131 return posts132 def react_to_review(self, user_id, review_id, reaction):133 q2 = self.execute_query(\134 "select count(*) from Review where review_id = '{}'".format(review_id))135 if q2[0][0] == 0:136 return -2137 q_str = "select react_type from ReviewReacts where user_id='{}' and review_id='{}'".format(user_id, review_id)138 cur_reaction = self.execute_query(q_str)139 print("cur_reaction:",cur_reaction)140 141 if cur_reaction is not None and len(cur_reaction) != 0:142 self.execute_query(\143 "update ReviewReacts set react_type = '{}' where user_id='{}' and review_id='{}'".format(reaction, user_id, review_id))144 if cur_reaction[0][0] != reaction:145 react_count = self.execute_query(\146 "select {} from Review where review_id='{}'".format(cur_reaction[0][0], review_id))147 if react_count[0][0] > 0:148 self.execute_query(\149 "update Review set {} = '{}' where review_id='{}'".format(cur_reaction[0][0], react_count[0][0]-1, review_id))150 react_count = self.execute_query(\151 "select {} from Review where review_id='{}'".format(reaction, review_id))152 self.execute_query(\153 "update Review set {} = '{}' where review_id='{}'".format(reaction, react_count[0][0]+1, review_id))154 else:155 self.execute_query(\156 "insert into ReviewReacts (review_id, user_id, react_type) values ('{}', '{}', '{}')".format(review_id, user_id, reaction))157 react_count = self.execute_query(\158 "select {} from Review where review_id='{}'".format(reaction, review_id))159 self.execute_query(\160 "update Review set {} = '{}' where review_id='{}'".format(reaction, react_count[0][0]+1, review_id))161 return 0162 163 # def get_post(self, user, date):164 # query = ""165 # self.execute_query(query)166 # def get_all_categories(self):167 # query = ""168 # self.execute_query(query)169 # def get_all_users(self):170 # query = ""171 # self.execute_query(query)172if __name__ == '__main__':173 S = YelpServer()174 # testing175 # S.post_review('___DPmKJsBF2X6ZKgAeGqg', '__1uG7MLxWGFIv2fCGPiQQ', '4.0', 'Good physio')176 # print(S.follow_business('1UnZiZiuDLYxDmE2uzvB4A', '4JNXUYY8wbaaDmk3BPzlWw'))177 #print(S.get_latest_posts('1UnZiZiuDLYxDmE2uzvB4A', 10))178 print(S.react_to_review('___DPmKJsBF2X6ZKgAeGqg', '100', 'funny'))...

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run SeleniumBase automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful