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 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 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 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 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 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 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')
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 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 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 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()
def get_db(): if 'db' not in g: g.db = DBManager(DATABASE) return g.db
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))