def showDogs(): mycursor = DBManager().getCursor() un = session["USERNAME"] queryShowDogs = "select dog_id,name from dogs where username='******'" mycursor.execute(queryShowDogs) result = mycursor.fetchall() return result
def homepage(): un = get_user_logged_in() ge='' ar='' if un: req = request.form filter = "" if request.method == 'POST': if req.get("filter") == 'submit': ge = req.get("gender") ar = req.get("area") if ge != "all" and ar == "all": filter = "gender='" + ge + "'" elif ge == "all" and ar != "all": filter = "area='" + ar + "'" elif ge != "all" and ar != "all": filter = "gender='" + ge + "' and area ='" + ar + "'" queryhomepage = "SELECT * FROM dogs" # add query for excluding from likes table queryhomepage += " WHERE dog_id NOT IN (SELECT dog_id FROM likes WHERE username='******') " +\ "AND username <> '" + un + "'" # add query for the filter in homepage if filter != "": queryhomepage += " AND " + filter mycursor = DBManager().getCursor() mycursor.execute(queryhomepage) result = mycursor.fetchall() return render_template('homepage.html', dogs=result,gender=ge,area=ar) return redirect('login')
def adopted(dog_id): mycursor = DBManager().getCursor() mycursor.execute( "INSERT INTO adopted SELECT d.* FROM dogs AS d WHERE dog_id = " + dog_id) DBManager().connection.commit() deleteDog(dog_id) return True
def dogProfile(dog_id): mycursor = DBManager().getCursor() uname = get_user_logged_in() if uname: queryDogProfile = "select * from dogs where dog_id=" + dog_id mycursor.execute(queryDogProfile) result = mycursor.fetchall() return render_template('dogProfile.html', dog=result) return redirect('login')
def add_meeting(): ''' send a proposal for a meeting to dog owner :return: homepage template ''' mycursor = DBManager().getCursor() details = request.form username = get_user_logged_in() mycursor.execute("select username from dogs where dog_id=" + details['dog']) owner_username = mycursor.fetchone() mycursor.execute("select name from dogs where dog_id=" + details['dog']) dog_name = mycursor.fetchone() DBManager().connection.commit() sending_date = datetime.now() sending_date_formated = sending_date.strftime('%Y-%m-%d %H:%M:%S') date_time = details['time'].split('T') # the template massage: 'Can I meet {} in {} in {} at {}?\nYes/No' add_message_to_db( Message( username, owner_username[0], 'Can I meet ' + dog_name[0] + ' in ' + date_time[0] + ' in ' + date_time[1] + ' at ' + details['place'] + '?\nYes/No', sending_date_formated, 'True')) return redirect('/homepage')
def authenticate_user(username, password): maulers = DBManager().getCursor() Fender = "SELECT username, password FROM users WHERE username = %s" maulers.execute(Fender, username) result = maulers.fetchall() print(result) for user in result: if sha256_crypt.verify(password, user[1]): session["USERNAME"] = user[0] return True else: raise Exception("Password doesn't match") raise Exception("Username not found")
def get_all_messages(sender, receiver): view = [] try: mycursor = DBManager.getCursor() mycursor.execute("SELECT * FROM messages WHERE (sender_username = %(sender)s AND receiver_username = %(receiver)s) " + "OR (receiver_username = %(sender)s AND sender_username = %(receiver)s)" + "ORDER BY sending_date ASC", { 'sender': sender, 'receiver': receiver}) view = mycursor.fetchall() DBManager.closeConnection() except Exception as error: print(f'error in get_all_messages: {str(error)}') return view
def yes_button(): username = get_user_logged_in() if username and 'dog_id' in request.form: details = request.form dog_id = details['dog_id'] answer = details['answer'] if answer == 'yes' or answer == 'no': mycursor = DBManager().getCursor() mycursor.execute("INSERT INTO likes VALUES (%s, %s,%s)", (username, dog_id, answer)) DBManager().connection.commit() return 'success' return 'fail'
def create_dog_profile(): username = get_user_logged_in() if username: if request.method == "POST": try: details = request.form name = details['dog_name'] # check if chip already exists chip = details['chip_number'] mycursor = DBManager().getCursor() mycursor.execute("SELECT dog_id FROM dogs WHERE dog_id = '" + chip + "'") chip_from_db = mycursor.fetchall() if (chip_from_db): raise Exception('Chip already Exists!') birth_date = details['birth_date'] gender = details['gender'] area = details['area'] city = details['city'] type = details['type'] description = details['description'] img1 = request.files['files'] path1 = os.path.join('images/', img1.filename) img1.save(os.path.join(UPLOAD_FOLDER, img1.filename)) photo1 = convertToBinaryData( os.path.join(UPLOAD_FOLDER, img1.filename)) img2 = request.files['img2'] if img2.filename != '': img2.save(os.path.join(UPLOAD_FOLDER, img2.filename)) path2 = os.path.join('images/', img2.filename) photo2 = convertToBinaryData( os.path.join(UPLOAD_FOLDER, img2.filename)) else: photo2 = '' path2 = '' img3 = request.files['img3'] if img3.filename != '': path3 = os.path.join('images/', img3.filename) img3.save(os.path.join(UPLOAD_FOLDER, img3.filename)) photo3 = convertToBinaryData( os.path.join(UPLOAD_FOLDER, img3.filename)) else: photo3 = '' path3 = '' mycursor.execute( "INSERT INTO dogs(dog_id,name,bday,gender,area,city, type,details,pic1,path1,pic2,path2,pic3,path3,username) VALUES (%s, %s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)", (chip, name, birth_date, gender, area, city, type, description, photo1, path1, photo2, path2, photo3, path3, username)) DBManager().connection.commit() message = "Dog added successfully" except Exception as error: message = str(error) else: message = " " return render_template('create_dog_profile.html', message=message) return redirect('/login')
def add_message_to_db(msg: Message) -> bool: message_id = None if msg.receiver and msg.content.strip() != '': mycursor = DBManager.getCursor() sql = "INSERT INTO messages (sender_username, receiver_username, content, sending_date, meeting_proposal) VALUES (%s, %s, %s, %s, %s)" val = (msg.sender, msg.receiver, msg.content, msg.date.strftime('%Y-%m-%d %H:%M:%S'), msg.meeting_proposal) mycursor.execute('select * from messages where sender_username="******" and receiver_username="******" order by sending_date desc Limit 1') last_massage= mycursor.fetchone() print(last_massage) # check if the last message was a meeting proposal and the owner replied yes if last_massage is not None and msg.content.lower() == 'yes' and last_massage[5] == 'True': mycursor.execute("select email from users where username='******'") owner_email = mycursor.fetchone() mycursor.execute("select email from users where username='******'") username_email = mycursor.fetchone() # extract name place and time from the meeting proposal message matches = re.findall(r'Can I meet (\S+) in (\S+) in (\S+) at (.*?)\?\nYes/No', last_massage[3])[0] #meeting_output = os.popen('python meeting//create_meeting.py "' + matches[0] +'" "' + matches[3] + '" ' + matches[1] + 'T' + matches[2] + ' ' + owner_email[0] + ' ' + username_email[0]).read() #print(f'end creating meeting: {meeting_output}') meeting.create_meeting(dog_name=matches[0], place=matches[3], time=f'{matches[1]}T{matches[2]}', owner_email=owner_email[0], client_email=username_email[0]) try: mycursor.execute(sql, val) DBManager.connection.commit() message_id = mycursor.lastrowid print(f'inserted message with id {message_id}') except Exception as error: print(f'error in add_message_to_db: {str(error)}') return message_id
def deleteDog(dog_id): mycursor = DBManager().getCursor() queryDeleteDog = "DELETE FROM dogs WHERE dog_id =" + dog_id mycursor.execute(queryDeleteDog) DBManager().connection.commit() queryDeleteDog = "DELETE FROM likes WHERE dog_id =" + dog_id mycursor.execute(queryDeleteDog) DBManager().connection.commit() return True
def get_all_chats(sender_username): view = [] try: mycursor = DBManager.getCursor() mycursor.execute("SELECT d.username FROM dogs d " + "INNER JOIN likes l ON l.dog_id = d.dog_id " + "WHERE l.username=%(sender)s " + "AND d.dog_id NOT IN (SELECT dog_id FROM adopted) " + "AND d.username <> %(sender)s " + "AND l.answer='yes'" + "UNION " + "SELECT l.username FROM dogs d " + "INNER JOIN likes l ON l.dog_id = d.dog_id " + "WHERE d.username=%(sender)s " + "AND l.username <> %(sender)s " + "AND l.answer='yes'" + "AND d.dog_id NOT IN (SELECT dog_id FROM adopted) " + "ORDER BY 1 ASC", { 'sender': sender_username, }) view = mycursor.fetchall() DBManager.closeConnection() except Exception as error: print(f'error in get_all_chats: {str(error)}') return view
def register(): mycursor = DBManager().getCursor() message = "" if request.method == 'POST': try: userDetails = request.form username = userDetails['username'] unQuery = "SELECT username FROM users WHERE username = '******'" mycursor.execute(unQuery, username) username_from_db = mycursor.fetchall() if username_from_db: raise Exception('User name already Exists!') password = userDetails["password1"] password_confirm = userDetails["password2"] if password != password_confirm: raise Exception('Passwords does not match!') password = sha256_crypt.encrypt(userDetails["password1"]) firstName = userDetails['firstName'] lastName = userDetails['lastName'] phone = userDetails['phone'] email = userDetails['email'] result1 = email.find('@GMAIL.COM') result2 = email.find('@gmail.com') result3 = email.find('@gmail.COM') result4 = email.find('@GMAIL.com') result5 = email.find('@Gmail.com') if result1 == -1 and result2 == -1 and result3 == -1 and result4 == -1 and result5 == -1: error = 'you have to put gmail account in order to use our app' raise Exception(error) mycursor = DBManager().getCursor() sql = "INSERT INTO users (username, password, firstName, lastName, phone, email) VALUES (%s, %s, %s, %s, %s, %s)" val = (username, password, firstName, lastName, phone, email) mycursor.execute(sql, val) DBManager.connection.commit() session['USERNAME'] = username return redirect(url_for('homepage')) except Exception as error: message = str(error) return render_template('/register.html', message=message)
def favorites(): username = get_user_logged_in() if username: if request.method == 'POST': details = request.form clear_but = details['clear'] if clear_but == 'yes': clearChoices(username) return redirect('/homepage') query_favorites = "select * from dogs left join likes on likes.dog_id = dogs.dog_id where likes.username='******' AND answer='yes' AND dogs.username <> '" + username + "'" mycursor = DBManager().getCursor() mycursor.execute(query_favorites) dogs = mycursor.fetchall() DBManager().connection.commit() DBManager().closeConnection() return render_template('favorites.html', dogs=dogs) return redirect('/login')
sleep(1) resp = requests.post(url, data=_data, headers=HEADERS) results = resp.json().get('content').get('positionResult').get('result') for result in results: print(result) db.insert_one({ 'companyFullName': result.get('companyFullName'), 'positionName': result.get('positionName'), 'salary': result.get('salary'), 'workYear': result.get('workYear') }) if __name__ == '__main__': start = time.time() city = sys.argv[2] kd = sys.argv[1] db = DBManager(kd) url = BASE_URL.format(city=city) pages = sys.argv[3] tasks = [] for index in range(1, int(pages) + 1): if index == 1: _data = {'firsrt': True, 'pn': index, 'kd': kd} else: _data = {'first': False, 'pn': index, 'kd': kd} tasks.append(gevent.spawn(crawl, url, _data, db)) gevent.joinall(tasks) print('Exec {}'.format(time.time() - start))
def get_db(): if 'db' not in g: g.db = DBManager(DATABASE) return g.db
def updateUser(): message=None mycursor = DBManager().getCursor() uname = get_user_logged_in() if uname: mycursor.execute( "SELECT * FROM users WHERE username = '******'") user = mycursor.fetchall() if request.method == 'POST': try: formDetails = request.form name = formDetails['name'] if name != "": sql = "UPDATE users SET firstName = '" + \ name + "' WHERE username = '******'" mycursor.execute(sql) DBManager().connection.commit() lastname = formDetails['lastname'] if lastname != "": sql = "UPDATE users SET lastName = '" + \ lastname + "' WHERE username = '******'" mycursor.execute(sql) DBManager().connection.commit() phone = formDetails["tel"] if phone != "": sql = "UPDATE users SET phone = '" + phone + \ "' WHERE username = '******'" mycursor.execute(sql) DBManager().connection.commit() mail = formDetails['mail'] if mail != "": result1 = mail.find('@GMAIL.COM') result2 = mail.find('@gmail.com') result3 = mail.find('@gmail.COM') result4 = mail.find('@GMAIL.com') result5 = mail.find('@Gmail.com') if result1 == -1 and result2 == -1 and result3 == -1 and result4 == -1 and result5 == -1 : error = 'you have to put gmail account in order to use our app' raise Exception(error) else: sql = "UPDATE users SET email = '" + mail + "' where username = '******'" mycursor.execute(sql) DBManager().connection.commit() message = "your details were updates successfully" newpass = formDetails["newpass"] renewpass = formDetails["confirm"] if (newpass != "") & (renewpass != ""): if newpass == renewpass: newpass = sha256_crypt.encrypt(newpass) sql = "UPDATE users SET password='******' where username='******'" mycursor.execute(sql) DBManager().connection.commit() message = "your details were updates successfully" else: message = "new password does NOT match to confirm password" mycursor.execute( "SELECT * FROM users WHERE username = '******'") user = mycursor.fetchall() except Exception as error: message = str(error) else: message = "" return render_template("updateUser.html", dogs=showDogs(), user=user, m=message) return redirect('login')
def clearChoices(username): queryClear = "DELETE FROM likes WHERE username='******'" mycursor = DBManager().getCursor() mycursor.execute(queryClear) DBManager().connection.commit()
import tornado.ioloop import tornado.web from model import Authenticator, DBManager from handler import AliasHandler from handler import AddAliasHandler, AdminHandler, DeleteAliasHandler from handler import RedirectToConsoleHandler, LoginHandler, LogoutHandler settings = { 'static_path': os.path.join(os.path.dirname(__file__), 'static'), 'cookie_secret': 'SVZoZVFzU05QTGh1dFZMYzBMRExUNmRDWDY0emhKTzdaWQ0K', 'login_url': '/login', 'xsrf_cookies': True, } with DBManager('alias.kch') as dbm: application = tornado.web.Application([ (r"/", RedirectToConsoleHandler), (r"/a/([a-zA-Z0-9_]+)", AliasHandler, dict(dbm=dbm)), (r"/login", LoginHandler, dict(auth=Authenticator())), (r"/logout", LogoutHandler), (r"/admin[/]?", AdminHandler, dict(dbm=dbm)), (r"/admin/add", AddAliasHandler, dict(dbm=dbm)), (r"/admin/delete/([a-zA-Z0-9_]+)", DeleteAliasHandler, dict(dbm=dbm)), ], **settings) if __name__ == "__main__": port = int(sys.argv[1]) http_server = tornado.httpserver.HTTPServer(application) http_server.listen(port) tornado.ioloop.IOLoop.instance().start()