def register(): Registerform = RegisterForm() if Registerform.validate_on_submit(): valid = Tlbx.validate_email(Registerform.email.data) print(valid) if(Tlbx.validate_email(Registerform.email.data) is not False): password = Tlbx.hash_password(Registerform.password.data) Tlbx.new_Account(Registerform.email.data, password) return redirect('/') flash('Email address already exists') return redirect('/login') return render_template('Login/login.html', Registerform=Registerform, Loginform=Loginform)
def dbTemp(WithdrawDeposit, Company, Date, Amount): print("dbTemp works!") query = ( "INSERT INTO tTemporary (WithdrawDeposit, Company, Date, Amount) VALUES (%s, %s, %s, %s)" ) data = (WithdrawDeposit, Company, Date, Amount) cur = Tlbx.dbConnect() try: cur.execute(query, data) except: print("PNC Database insert Failed! Sending email...") body = "IMAP failed. Subject was " + WithdrawDeposit + " Company was " + Company + " Date was " + Date + " Amount was " + str( Amount) Tlbx.SendEmail(body)
def dbTrans(Name, Description, WithdrawDeposit, Company, Date, Amount, Comments, Receipt): print("dbTrans works!") cur = Tlbx.dbConnect() query = "INSERT INTO tTransaction (Name, Description, WithdrawDeposit, Company, Date, Amount, Comments, Receipt) VALUES (%s, %s, %s, %s, %s, %s, %s, %s)" print(Date) data = (Name, Description, WithdrawDeposit, Company, Date, Amount, Comments, Receipt) try: cur.execute(query, data) except: body = "IMAP failed. Name was %s, Description was %s, Subject was %s, Company was %s, Date was %s Amount was %s Comments was %s Receipt was %s", ( Name, Description, WithdrawDeposit, Company, Date, Amount, Comments, Receipt) Tlbx.SendEmail(body)
def Delete(TransID): TransID = str(TransID) query = ("DELETE FROM tTransaction WHERE transID=" + TransID + ";") cur = Tlbx.dbConnectDict() cur.execute(query) balance = Tlbx.Balance() cur = Tlbx.dbConnect() query = ("Select COUNT(tempID) FROM tTemporary") cur.execute(query) Transaction = cur.fetchone()[0] if Transaction is None: Transaction = "0" return render_template('HomePage/index.html', balance=balance, Transaction=Transaction)
def login(): if current_user.is_authenticated: return redirect('/dashboard') #instantiates the forms to login and register your account Loginform = LoginForm() Registerform = RegisterForm() #Checks to ensure fields are not null if Loginform.validate_on_submit(): #Checks to ensure username and password are correct. if(Tlbx.check_password(Loginform.email.data, Loginform.password.data) is not False): Tlbx.loginUser(Loginform.email.data) return redirect('/dashboard') flash("Email or Password is incorrect.") return render_template('/Login/login.html', Registerform=Registerform, Loginform=Loginform)
def approve(TransID): cur = Tlbx.dbConnectDict() TransID = str(TransID) query = ( "SELECT TransID, Name, Description, WithdrawDeposit, Company, DATE_FORMAT(Date, '%m-%d-%Y') AS Date, Amount, Comments, Receipt FROM tTransaction WHERE TransID =" + TransID + ";") cur.execute(query) result = cur.fetchone() result = dict(result) Name = result['Name'] Description = result['Description'] WithdrawDeposit = result['WithdrawDeposit'] Company = result['Company'] Date = (result['Date']) Amount = (result['Amount']) Comments = (result['Comments']) Receipt = (result['Receipt']) return render_template('EditTemplate/Edit.html', TransID=TransID, Name=Name, Description=Description, WithdrawDeposit=WithdrawDeposit, Company=Company, Comments=Comments, Date=Date, Amount=Amount, Receipt=Receipt)
def sendMessage(userID): #user userID to get both friendIDs to submit messages #Get both friendIDs associated with friendship cur, db = Tlbx.dbConnectDict() query = ("SELECT friendID from tFriend \ WHERE tFriend.user = %s \ AND tFriend.friend = %s;") data = (current_user.id, userID) cur.execute(query, data) UserFriendID = cur.fetchone() data = (userID, current_user.id) cur.execute(query, data) FriendFriendID = cur.fetchone() session = Database.Session() message = request.form['message'] addMessageFriend = Database.tMessage(friendID = FriendFriendID['friendID'], sender = current_user.id, \ recipient = userID, time_Sent = datetime.datetime.now(), message = message) addMessageUser = Database.tMessage(friendID = UserFriendID['friendID'], sender = current_user.id, \ recipient = userID, time_Sent = datetime.datetime.now(), message = message) session.add(addMessageUser) session.add(addMessageFriend) session.commit() return redirect('/Messages')
def index(): '''Do a normal select for comments and reacts. Then in jinja during the for loop for posts do a for loop for reacts and comments. Do an if post.postID == comment.postID and if post.postiD == react.postID''' session = Database.Session() currentUser = Tlbx.currentUserInfo(current_user.id) #Collect dogs in your family dogResults = session.query(Database.tDog).join(Database.tUser, Database.tDog.familyID == Database.tUser.familyID).filter(Database.tUser.userID == current_user.id) #Get comments of posts commentResults = Comments.getComments() #Get reacts of posts reactResults = Reacts.getReacts() yourReacts = Reacts.yourReacts() #Get Posts postResults = Posts.getPosts() likes={} like =[] for react in postResults: likes[react.postID] = 'Like' for yourReact in yourReacts: if yourReact.postID in likes.keys(): likes[yourReact.postID] = 'Unlike' for react in postResults: like.append(likes[react.postID]) return render_template('HomePage/Dashboard.html', currentUser = currentUser, dogResults = dogResults, \ postResults = zip(postResults, like), commentResults = commentResults, reactResults = reactResults)
def finishpayment(): cur = Tlbx.dbConnectDict() query = ( "SELECT tempID, WithdrawDeposit, Company, DATE_FORMAT(Date, '%m-%d-%Y') AS Date, Date AS Sort, Amount FROM tTemporary ORDER BY Sort DESC;" ) cur.execute(query) return render_template('FinishPayments/finishpaymentSearch.html', items=cur.fetchall())
def routeMessages(): friendID = None userID = int(current_user.id) #Get all friends you have that you've sent messages with. friends, db = Tlbx.dbConnectDict() friendQuery = ( "Select MAX(tMessage.time_sent) as ts, tFriend.friendID, tUser.userID, tUser.firstName, tUser.lastName, tUser.image from tUser \ JOIN tFriend ON tUser.userID = tFriend.friend \ LEFT JOIN tMessage ON tMessage.friendID = tFriend.friendID\ WHERE tFriend.user = %s \ GROUP BY tFriend.friendID \ ORDER BY ts DESC;") data = (current_user.id) friends.execute(friendQuery, data) latestMessageQuery = ( "Select tMessage.time_sent as ts, tFriend.friendID, tUser.userID, tUser.firstName, tUser.lastName, tMessage.message from tUser \ JOIN tFriend ON tUser.userID = tFriend.friend \ LEFT JOIN tMessage ON tMessage.friendID = tFriend.friendID\ JOIN (SELECT tMessage.friendID, MAX(tMessage.time_sent) as ts FROM tMessage \ GROUP by tMessage.friendID) \ AS t2 \ ON tMessage.friendID = t2.friendID AND tMessage.time_sent = t2.ts\ WHERE tFriend.user = %s \ ORDER BY tMessage.time_sent DESC;") latest, db = Tlbx.dbConnectDict() data = (current_user.id) latest.execute(latestMessageQuery, data) messageQuery = ( "Select tMessage.friendID, tMessage.message, tMessage.time_Sent, tMessage.recipient, tUser.firstName, tUser.lastName from tMessage \ JOIN tFriend ON tFriend.friendID = tMessage.friendID \ JOIN tUser ON tFriend.friend = tUser.userID \ WHERE tFriend.user = %s \ ORDER BY tMessage.time_sent") cur, db = Tlbx.dbConnectDict() data = (current_user.id) cur.execute(messageQuery, data) Messages.updateMessageTime(current_user.id) return render_template('/Messages/Messages.html', latest=latest.fetchall(), friendID=friendID, userID=userID, messages=cur.fetchall(), friends=friends.fetchall())
def index(): #Get the current balance balance = Tlbx.Balance() #Connect to the database to post number of incomplete transactions cur = Tlbx.dbConnect() query = ("Select COUNT(tempID) FROM tTemporary") cur.execute(query) Transaction = cur.fetchone()[0] #A catch from testing to prevent a crash if Transaction is None: Transaction = "0" #Render the page return render_template('HomePage/index.html', balance=balance, Transaction=Transaction)
def getPostComments(postID): cur, db = Tlbx.dbConnectDict() query = "SELECT tPosts.postID, tComments.Comment, tUser.userID, tUser.firstName, tUser.lastName, tUser.image \ FROM tComments INNER JOIN tUser ON tComments.userID = tUser.userID INNER JOIN tPosts ON tComments.postID = tPosts.postID \ WHERE tPosts.postID = %s ORDER BY tComments.commentID DESC LIMIT 3;" data = (postID) cur.execute(query, data) commentResults = cur.fetchall() return commentResults
def askAvailability(dogID): msg = ast.literal_eval(json.dumps(dogID)) cur, db = Tlbx.dbConnectDict() query = "SELECT * FROM tAvailability WHERE DogID = %s" data = (msg['dogID']) cur.execute(query, data) Availability = cur.fetchall() for time in Availability: time['Begin_ts'] = str(time['Begin_ts']) time['End_ts'] = str(time['End_ts']) socketio.emit('giveAvailability', {'Availability': Availability}, namespace='/Availability/', room=request.sid)
def userInfo(): UserInfoform = UserInfoForm() if UserInfoform.validate_on_submit(): firstName = UserInfoform.firstName.data lastName = UserInfoform.lastName.data email = session.get('email') password = Tlbx.hash_password(session.get('password', None)) try: address = request.form['desktopstreet_address'] city = request.form['desktopadministrative_area_level_1'] state = request.form['desktoplocality'] except: address = request.form['mobilestreet_address'] city = request.form['mobileadministrative_area_level_1'] state = request.form['mobilelocality'] image = request.files[UserInfoform.profileImage.name] if (image.filename.encode('ascii', 'ignore') is not ""): image = Tlbx.imgToJPG("Profile", image) else: image = None Tlbx.new_Account(firstName, lastName, email, password, address, city, state, image) Tlbx.loginUser(email) return render_template('/Family/FamilySplash.html') flash("Please input data in all fields") return render_template('Register/userInfo.html', UserInfoform=UserInfoform)
def addPlaydate(msg): msg = ast.literal_eval(json.dumps(msg)) eastern = timezone('US/Eastern') cur, db = Tlbx.dbConnectDict() query = "SELECT * FROM tPlayDate WHERE AvailabilityID = %s" data = (msg['AvailabilityID']) cur.execute(query, data) playdate = cur.fetchall() if (playdate != ()): socketio.emit('PlayDateException', {'Error': "This time is in use by another playdate."}, namespace='/Availability/', room=request.sid) else: Availability.commitPlayDate(msg['hostDogID'], msg['guestDogID'], msg['creatorID'] ,msg['AvailabilityID'], parser.parse(msg['Begin_ts']).astimezone(eastern), parser.parse(msg['End_ts']).astimezone(eastern), msg['message'])
def dogProfile(dogID): session = Database.Session() #Get information about the dog dog = session.query(Database.tDog, Database.tBreed).filter(Database.tDog.dogID == dogID) \ .join(Database.tBreed, Database.tBreed.breedID == Database.tDog.dogID) for dog in dog: dog = dog #Get comments of posts commentResults = Comments.getComments() #Get reacts of posts reactResults = Reacts.getReacts() yourReacts = Reacts.yourReacts() #Get Posts postResults = Posts.getPosts() likes = {} like = [] for react in postResults: likes[react.postID] = 'Like' for yourReact in yourReacts: if yourReact.postID in likes.keys(): likes[yourReact.postID] = 'Unlike' for react in postResults: like.append(likes[react.postID]) cur, db = Tlbx.dbConnectDict() query = "select tFamily.familyID from tFamily \ JOIN tUser on tFamily.familyID = tUser.familyID \ JOIN tDog on tUser.familyID = tDog.familyID \ WHERE tUser.userID = %s AND tDog.dogID = %s;" data = (current_user.id, dogID) cur.execute(query, data) family = cur.fetchone() if (family is not None): return render_template('Account/AdminDogProfile.html', postResults=zip(postResults, like), commentResults=commentResults, reactResults=reactResults, yourReacts=yourReacts, dog=dog) else: return render_template('Account/DogProfile.html', postResults=zip(postResults, like), commentResults=commentResults, reactResults=reactResults, yourReacts=yourReacts, dog=dog)
def register(): Registerform = RegisterForm() Loginform = LoginForm() if Registerform.validate_on_submit(): session['email'] = Registerform.email.data session['password'] = Registerform.password.data if(Tlbx.validate_email(Registerform.email.data) is not False): UserInfoform = UserInfoForm() return render_template('Register/userInfo.html', UserInfoform = UserInfoform ) flash('Email address already exists') return redirect('/') return render_template('Login/login.html', Registerform=Registerform, Loginform=Loginform)
def Paging(): Name = request.form['Name'] Description = request.form['Description'] WithdrawDeposit = request.form['WithdrawDeposit'] Company = request.form['Company'] Date = request.form['Date'] Amount = request.form['Amount'] cur = Tlbx.dbConnectDict() query = ( "SELECT TransID, Name, Description, WithdrawDeposit, Company, DATE_FORMAT(Date, '%m-%d-%Y') AS Date, Date AS Sort, Amount FROM tTransaction" ) if (Name != '' or Description != '' or WithdrawDeposit != '' or Company != '' or Date != '' or Amount != ''): query = query + " WHERE " if (Name != ''): query = query + "Name LIKE '" + Name + "'" if (Description != '' or WithdrawDeposit != '' or Company != '' or Date != '' or Amount != ''): query = query + " AND " if (Description != ''): query = query + "Description LIKE '" + Description + "'" if (WithdrawDeposit != '' or Company != '' or Date != '' or Amount != ''): query = query + " AND " if (WithdrawDeposit != ''): query = query + "WithdrawDeposit LIKE '" + WithdrawDeposit + "'" if (Company != '' or Date != '' or Amount != ''): query = query + " AND " if (Company != ''): query = query + "Company LIKE '" + Company + "'" if (Date != '' or Amount != ''): query = query + " AND " if (Date != ''): Date = Date.split("-") Month = Date[0] Day = Date[1] Year = Date[2] Date = Year + "-" + Month + "-" + Day query = query + "Date LIKE '" + Date + "'" if (Amount != ''): query = query + " AND " if (Amount != ''): query = query + "Amount LIKE " + Amount query = query + " ORDER BY Sort DESC;" cur.execute(query) return render_template('Search/Search.html', items=cur.fetchall())
def askPlayDate(dogID): msg = ast.literal_eval(json.dumps(dogID)) cur, db = Tlbx.dbConnectDict() query = "SELECT *, hostDog.name, guestDog.name FROM tPlayDate \ JOIN tDog hostDog ON tPlayDate.hostDogID = hostDog.dogID \ JOIN tDog guestDog ON tPlayDate.guestDogID = guestDog.dogID \ WHERE tPlayDate.hostDogID = %s" data = (msg['dogID']) cur.execute(query, data) Availability = cur.fetchall() for time in Availability: time['Begin_ts'] = str(time['Begin_ts']) time['End_ts'] = str(time['End_ts']) socketio.emit('givePlayDates', {'PlayDates': Availability}, namespace='/Availability/', room=request.sid)
def finish(tempID): #database connection cur = Tlbx.dbConnectDict() tempID = str(tempID) query = ( "SELECT tempID, WithdrawDeposit, Company, DATE_FORMAT(Date, '%m-%d-%Y') AS Date, Amount FROM tTemporary WHERE tempID =" + tempID + ";") cur.execute(query) result = cur.fetchone() result = dict(result) WithdrawDeposit = result['WithdrawDeposit'] Company = result['Company'] Date = (result['Date']) Amount = (result['Amount']) return render_template('FinishPayments/finish.html', tempID=tempID, WithdrawDeposit=WithdrawDeposit, Company=Company, Date=Date, Amount=Amount)
def StartPark(): CreateDogform = CreateDogForm() dbsession = Database.Session() if CreateDogform.validate_on_submit(): session['dogName'] = CreateDogform.dogName.data session['gender'] = CreateDogform.gender.data session['breed'] = CreateDogform.breed.data session['fixed'] = CreateDogform.fixed.data session['age'] = CreateDogform.age.data session['favToy'] = CreateDogform.favToy.data session['size'] = CreateDogform.size.data session['weight'] = CreateDogform.weight.data session['bio'] = CreateDogform.bio.data image = request.files[CreateDogform.profileImage.name] if (image.filename.encode('ascii', 'ignore') is not ""): image = request.files[CreateDogform.profileImage.name] session['image'] = Tlbx.imgToJPG("Profile", image) else: session['image'] = None FavoriteParkform = FavoriteParkForm() followed = dbsession.query(Database.tDog.dogID).join(Database.tUser, Database.tDog.familyID == Database.tUser.familyID) \ .filter(Database.tUser.userID == current_user.id) if followed is not None: return render_template('/Dog/NewPark.html', FavoriteParkform=FavoriteParkform) else: return render_template('Dog/Initial_NewPark.html', FavoriteParkform=FavoriteParkform) return render_template('/Dog/NewPark.html', FavoriteParkform=FavoriteParkform) flash("Please fill out all fields") if followed is not None: return render_template('Dog/NewDog.html', CreateDogform=CreateDogform) else: return render_template('/Dog/Initial_NewDog.html', CreateDogForm=CreateDogForm)
def familyCreation(): sqlalch = Database.Session() HeadOfHouse = Database.tHeadofHouse(userID=current_user.id) sqlalch.add(HeadOfHouse) id = sqlalch.commit() CreateFamilyform = CreateFamilyForm() if CreateFamilyform.validate_on_submit(): CreateDogform = CreateDogForm() familyName = CreateFamilyform.surName.data cur, db = Tlbx.dbConnectDict() cursor = Database.Session() query = ( "INSERT INTO tFamily (familyName, headofHouseID) VALUES(%s, %s);") data = (familyName, id) cur.execute(query, data) session['familyID'] = db.insert_id() x = cursor.query(Database.tUser).get(current_user.id) x.familyID = db.insert_id() cursor.commit() return render_template('Dog/NewDog.html', CreateDogform=CreateDogform) flash("Please add a family name") return render_template('/Family/FamilyCreate.html', CreateFamilyform=CreateFamilyform)
def IMAP(): #Global variable to use inside of the class above global body #Connect to gmails imap service try: mail = imaplib.IMAP4_SSL('imap.gmail.com') mail.login('*****@*****.**', 'Momrocks38') mail.select('inbox') mail.list() except: print("Could not connect to Gmail!") body = "IMAP failed. Could not connect to Gmail." Tlbx.SendEmail(body) #this will search the email and give me all unread emails. response = mail.search(None, '(UNSEEN)') response = response[0].split() #For each email we will parse out the data and commit to the database for e_id in response: #reset variables for each loop body = [] raw_email = '' #Fetch one email and decode as utf-8 _, response = mail.fetch(e_id, 'RFC822') try: raw_email = response[0][1].decode("utf-8") except: print("Email cannot be decoded") continue email_message = email.message_from_string(raw_email) #these pull each heading and place into variables from_ = email_message['From'] subject_ = str(email_message['Subject']) date_ = str(email_message['date']) #set up array for date date = [] try: date = date_.split() Day = (date[0]) Month = (date[1]) Year = (date[2]) Date = Tlbx.dateConvert(Day, Month, Year) except: print("Date Failed!") body = "IMAP Date parsing failed. %s was the date pulled in" % date_ Tlbx.SendEmail(body) #If this data from pncalerts, we run it through this parsing group if (from_ == "PNC Alerts <*****@*****.**>"): #An alert for using the debit card if ("ATM" in subject_): print("There should be no ATM usage!") body = "Someone pulled money out of the ATM using Andrew's card." Tlbx.SendEmail(body) continue #Compares account balance to the current database sum elif ("Your Checking Account Balance" in subject_): parser = MyCheckParser() parser.feed(str(email_message)) PNCBalance = body[0] PNCBalance = PNCBalance.split(":") PNCBalance = PNCBalance[1] PNCBalance = PNCBalance.replace("$", "") PNCBalance = PNCBalance.replace(",", "") PNCBalance = PNCBalance.strip() PNCBalance = float(PNCBalance) db = pymysql.connect(host='192.168.0.20', port=3306, user='******', password='******', db='mydb', autocommit=True) cur = db.cursor() query = ("Select SUM(Amount) FROM tTemporary") cur.execute(query) TempAmount = cur.fetchone()[0] query = ("Select SUM(Amount) FROM tTransaction") cur.execute(query) TransAmount = cur.fetchone()[0] try: balance = TransAmount + TempAmount except: balance = TransAmount if balance is not None: balance = ('%.2f' % balance) balance = float(balance) if (balance != PNCBalance): PNCBalance = str(PNCBalance) balance = str(balance) print("Balances do not match!") body = "PNC and app balances do not match. PNC balance is " + PNCBalance + " and app balance is " + balance + "." Tlbx.SendEmail(body) #If a check is used elif ("Check(s)" in subject_): parser = MyCheckParser() parser.feed(str(email_message)) if ("Deducted" in subject_): WithdrawDeposit = "Withdraw" else: WithdrawDeposit = "Deposit" Company = 'Check' Amount = body[2] Amount = Amount.strip() Amount = Amount.split(":") Amount = Amount[1] Amount = Amount.replace("$", "") Amount = Amount.strip() Day = date[1] Month = date[2] Year = date[3] #Fix date to Y/M/D Date = Tlbx.dateConvert(Day, Month, Year) #Function to connect to database and commit data to tTemporary dbTemp(WithdrawDeposit, Company, Date, Amount) else: #This sets up our html parser which is the class above and feeds it in. parser = MyHTMLParser() parser.feed(str(email_message)) Company = '' Amount = '' #The global variable body we parse down for the company and amount try: Company = body[1] Company = Company.strip('\t') Company = Company.strip('\n') Company = Company.strip() #pull how much the amount was for and strip excess Amount = body[2] Amount = Amount.strip('\t') Amount = Amount.strip('\n') Amount = Amount.strip() Amount = re.findall(r"\d+\.\d+", Amount) #Send e-mail if parsing fails except: print("Company and Amount parsing Failed!") body = "IMAP Company/Amount parsing failed. %s was the Company pulled in, and %s was the the Amount pulled in" % ( Company, Amount) Tlbx.SendEmail(body) continue #try to convert Amount for database commit try: Amount = Amount[0] Amount = float(Amount) except: print("no money I guess") #Date comes in differently, parse again. Could be avoided with external function if ('Payment' in subject_ or 'Withdraw' in subject_): subject_ = 'Withdraw' Day = date[1] Month = date[2] Year = date[3] Date = Tlbx.dateConvert(Day, Month, Year) #Fix to not parse e-mail with no data elif ('Available Balance' in subject_): continue #Fix to not parse e-mail with no data elif ('Online Banking alerts' in subject_): continue else: subject_ = 'Deposit' Day = date[1] Month = date[2] Year = date[3] #Converts the date to Y/M/D Date = Tlbx.dateConvert(Day, Month, Year) # switch the Amount to negative if it is a withdraw if ('Withdraw' in subject_): Amount = -Amount #Strip excess data Company = Company.replace('Payment', '') Company = Company.replace('From:', '') Company = Company.replace('1', '') Company = Company.replace('To:', '') Company = Company.strip() #If we fit this logic, we will correct the naming and automatically commit to tTransaction if ("DUKE ENERGY OH" in Company or "RUMPKE RESIDENTI" in Company or "CLERMONT COUNTY" in Company or "SSI TREAS 30 9" in Company or "US BANK HOME MTG" in Company): Name = '' Description = '' Comments = '' Receipt = '' if ("CLERMONT COUNTY" in Company): Company = "Clermont County Utilities" Description = "Monthly Water Bill Payment" Name = "Clermont County Water" if ("RUMPKE RESIDENTI" in Company): Company = "Rumpke" Description = "Monthly Payment for Waste Disposal" Name = "Trash Removal" if ("DUKE ENERGY OH" in Company): Company = "Duke Energy" Description = "Monthly Electric Bill" Name = "Duke Energy" if ("SSI TREAS 30 9" in Company): Company = "SSI" Description = "Monthly Social Security Deposit" Name = "SSI Check Deposit" if ("US BANK HOME MTG" in Company): Company = "US Bank" Description = "Monthly House Payment" Name = "Housing" #Function to connect to our database and insert into tTransaction dbTrans(Name, Description, subject_, Company, Date, Amount, Comments, Receipt) #commit data to our tTemporary table else: #Function to connect to our database and insert into tTemporary dbTemp(subject_, Company, Date, Amount) #If the email is from [email protected] it will run through here elif (from_ == '*****@*****.**'): #Pull email and decode because it is in base64 ascil = email_message.get_payload(decode=base64).decode("utf-8") #Here we split the array and place them into variables. From there we will strip them down. array = (ascil.split("\n", 1)) startType = 'Your' endType = 'specified' start = 'Amount:' end = 'USD' Start1 = 'Name:' end1 = 'Merchant' s = array[1] WithdrawDeposit = ((s.split(startType))[1].split(endType)[0]) if ("purchase" in WithdrawDeposit): WithdrawDeposit = "Withdraw" if ("deposit" in WithdrawDeposit): WithdrawDeposit = "Deposit" if ("recently used" in WithdrawDeposit): WithdrawDeposit = "Withdraw" #Setup our amount to commit to the database Amount = '' #Attempt to strip down the Amount and convert to a float. try: Amount = ((s.split(start))[1].split(end)[0]) Amount = Amount.strip('\t') Amount = Amount.strip('\n') Amount = Amount.strip() Amount = Amount.replace('\'', '') Amount = Amount.replace("'", '') Amount = float(Amount) #Set amount to negative if this transaction is a withdraw if (WithdrawDeposit == "Withdraw"): Amount = Amount * -1 #A catch in case the amount does not exist in the e-mail except: print("No Amount I Guess") #remove excess data in company to commit into the database Company = ((s.split(Start1))[1].split(end1)[0]) Company = Company.strip('\t') Company = Company.strip('\n') Company = Company.strip() #if the scraped data fits in this logic, commit directly to tTransaction if ("ORDER" in Company or "BALANC" in Company or "TIP" in Company or "Northshore Care Supply" in Company): Name = '' Description = '' Comments = '' Receipt = '' if ("ORDER" in Company): Company = "Shipt" Name = "Groceries" Description = "Monthly Groceries" if ("BALANC" in Company): Company = "Shipt" Name = "Groceries" Description = "Balance differential for adding an item" if ("TIP" in Company): Company = "Shipt" Name = "Groceries" Description = "Added tip for Delivery" if ("Northshore Care Supply" in Company): Company = "Northshore Care Supply" Name = "Diapers" Description = "Tranquility All Night Through Adult Disposable Briefs" #Function call to instantiate database connection and insert scraped data into the tTransaction table. dbTrans(Name, Description, WithdrawDeposit, Company, Date, Amount, Comments, Receipt) #commit to tTemporary table else: #Parse company names to reduce later work when completing the transaction if ("CW BOTANICALS" in Company or "MEIJER" in Company or "FIVE BELOW" in Company or "LOWE'S" in Company or "KROGER" in Company or "MCDONALD'S" in Company or "WALGREENS" in Company or "AMZN MKTP US AMZN.COM/" in Company or "AMAZON" in Company or "AMZN Mktp" in Company or "Amazon" in Company or "amazon" in Company or "THORNTONS" in Company or "KFC" in Company or "TARGET" in Company): if ("CW BOTANICALS" in Company): Company = "CW Botanicals" if ("MEIJER" in Company): Company = "Meijer" if ("FIVE BELOW" in Company): Company = "Five Below" if ("LOWE'S" in Company): Company = "Lowe's" if ("KROGER" in Company): Company = "Kroger" if ("WALGREENS" in Company): Company = "Walgreens" if ("AMAZON" in Company or "AMZN MKTP US AMZN.COM/" in Company or "Amazon" in Company or "amazon" in Company): Company = "Amazon" if ("THORNTONS" in Company): Company = "Thorntons" if ("KFC" in Company): Company = "KFC" if ("TARGET" in Company): Company = "Target" #Function call to instantiate database connection and insert scraped data into the tTemporary table dbTemp(WithdrawDeposit, Company, Date, Amount)
def load_user(userid): return Tlbx.userRefresh(userid)
def finishTemp(tempID): name = '' tempID = str(tempID) #image orienting and saving image = '' if request.files['file'].filename != '': image = Image.open(request.files['file'].stream) if hasattr(image, '_getexif'): orientation = 0x0112 exif = image._getexif() if exif is not None: orientation = exif[orientation] rotations = { 3: Image.ROTATE_180, 6: Image.ROTATE_270, 8: Image.ROTATE_90 } if orientation in rotations: image = image.transpose(rotations[orientation]) name = request.files['file'].filename path = '/var/www/Flask/static/' + name image.save(path, "JPEG", optimize=True, quality=85) #Get data from web page to upload to database Name = request.form['Name'] Description = request.form['Description'] WithdrawDeposit = request.form['WithdrawDeposit'] Company = request.form['Company'] Date = request.form['Date'] split = Date.split("-") month = split[0] day = split[1] year = split[2] Date = year + "/" + month + "/" + day Amount = request.form['Amount'] Amount = float(Amount) Comments = request.form['Comments'] if (WithdrawDeposit == "Withdraw" and Amount > 0): Amount = (Amount * -1) request.get_data('Name') request.get_data('Description') request.get_data('WithdrawDeposit') request.get_data('Company') request.get_data('Amount') request.get_data('Comments') cur = Tlbx.dbConnectDict() query = ( "INSERT INTO tTransaction (Name, Description, WithdrawDeposit, Company, Date, Amount, Comments, Receipt) VALUES (%s, %s, %s, %s, %s, %s, %s,%s)" ) data = (Name, Description, WithdrawDeposit, Company, Date, Amount, Comments, name) cur.execute(query, data) request.get_data('image') Date = month + "-" + day + "-" + year request.get_data('Date') cur = Tlbx.dbConnectDict() query = ("DELETE FROM tTemporary WHERE tempID=" + tempID + ";") cur.execute(query) return render_template("FinishPayments/finishResults.html", Name=Name, Description=Description, WithdrawDeposit=WithdrawDeposit, Company=Company, Date=Date, Amount=Amount, Comments=Comments, image=name)
def DogCreation(): FavoriteParkform = FavoriteParkForm() if FavoriteParkform.validate_on_submit(): #insert Breed cur, db = Tlbx.dbConnectDict() breedQuery = "INSERT INTO tBreed (breed) VALUES (%s);" data = (session.get('breed')) cur.execute(breedQuery, data) db.commit() breedID = cur.lastrowid #Insert Address then insert Favorite Park image = None addressQuery = "INSERT INTO tAddress (address, city, state) VALUES (%s, %s, %s);" try: address = request.form['desktopstreet_address'] city = request.form['desktopadministrative_area_level_1'] state = request.form['desktoplocality'] except: address = request.form['mobilestreet_address'] city = request.form['mobileadministrative_area_level_1'] state = request.form['mobilelocality'] data = (address, city, state) cur.execute(addressQuery, data) favParkQuery = "INSERT INTO tFavoritePark (parkName, AddressID, image) VALUES (%s, LAST_INSERT_ID(), %s);" data = (FavoriteParkform.parkName.data, image) cur.execute(favParkQuery, data) db.commit() favParkID = cur.lastrowid #Insert favorite toy. image = None favToyQuery = "INSERT INTO tFavoriteToy (ToyName, image) VALUES (%s, %s);" data = (session['favToy'], image) cur.execute(favToyQuery, data) db.commit() favToyID = cur.lastrowid cursor = Database.Session() familyID = session.get('familyID') if familyID is None: familyID = cursor.query(Database.tUser.familyID).filter( Database.tUser.userID == current_user.id) for familyID in familyID: familyID = familyID.familyID # commit all the dog data into the database. dogQuery = "Insert into tDog (name, gender, breedID, fixed, age, Size, Weight, bio, image, favToyID, favParkID, familyID) VALUES (%s, %s, %s, %s,%s, %s, %s, %s,%s, %s, %s, %s)" data = (session.get('dogName'), session.get('gender'), breedID, session.get('fixed'), session.get('age'), session.get('size'), session.get('weight'), session.get('bio'), session.get('image'), favToyID, favParkID, familyID) cur.execute(dogQuery, data) db.commit() #Follow the dog sqlalch = Database.Session() Query = Database.tFollowers(dogID=cur.lastrowid, userID=current_user.id) sqlalch.add(Query) sqlalch.commit() return redirect('/dashboard') flash("please input your dogs favorite park") return render_template('/Dog/NewPark.html', FavoriteParkform=FavoriteParkform) #finally commit all the dog data into the database. dogQuery = "Insert into tDog (name, gender, breedID, fixed, age, Size, Weight, bio, image, favToyID, favParkID, familyID) VALUES (%s, %s, %s, %s,%s, %s, %s, %s,%s, %s, %s, %s)" data = (session.get('dogName'), session.get('gender'), breedID, session.get('fixed'), session.get('age'), session.get('size'), session.get('weight'), session.get('bio'), image, favToyID, favParkID, session.get('familyID')) cur.execute(dogQuery, data) db.commit() #Default to follow the dog dogID = cur.lastrowid FollowDogs(dogID) #Redirect to the dashboard return redirect('/dashboard')
def Update(TransID): name = '' Name = request.form['Name'] Description = request.form['Description'] WithdrawDeposit = request.form['WithdrawDeposit'] Company = request.form['Company'] Date = request.form['Date'] split = Date.split("-") month = split[0] day = split[1] year = split[2] Date = year + "-" + month + "-" + day Amount = request.form['Amount'] Amount = float(Amount) Comments = request.form['Comments'] name = request.form['Image'] if (WithdrawDeposit == "Withdraw" and Amount > 0): Amount = (Amount * -1) if (WithdrawDeposit == "Deposit" or WithdrawDeposit == "deposit" and Amount < 0): Amount = abs(Amount) Amount = str(Amount) TransID = str(TransID) request.get_data('Name') request.get_data('Description') request.get_data('WithdrawDeposit') request.get_data('Company') request.get_data('Amount') request.get_data('Comments') if (request.files['file'].filename == '' and request.form['Image'] == ''): name = '' elif (request.form['Image'] != '' and request.files['file'].filename == ''): name = request.form['Image'] elif (request.files['file'].filename != '' and request.form['Image'] == ''): name = '' if request.files['file'].filename != '': image = Image.open(request.files['file'].stream) if hasattr(image, '_getexif'): orientation = 0x0112 exif = image._getexif() if exif is not None: orientation = exif[orientation] rotations = { 3: Image.ROTATE_180, 6: Image.ROTATE_270, 8: Image.ROTATE_90 } if orientation in rotations: image = image.transpose(rotations[orientation]) name = request.files['file'].filename path = '/var/www/Flask/static/' + name image.save(path, "JPEG", optimize=True, quality=85) else: if request.files['file'].filename != '': name = '' if request.files['file'].filename != '': image = Image.open(request.files['file'].stream) if hasattr(image, '_getexif'): orientation = 0x0112 exif = image._getexif() if exif is not None: orientation = exif[orientation] rotations = { 3: Image.ROTATE_180, 6: Image.ROTATE_270, 8: Image.ROTATE_90 } if orientation in rotations: image = image.transpose(rotations[orientation]) name = request.files['file'].filename path = '/var/www/Flask/static/' + name image.save(path, "JPEG", optimize=True, quality=85) cur = Tlbx.dbConnectDict() sql = "UPDATE tTransaction SET Name = (%s),Description= (%s),WithdrawDeposit= (%s), Company= (%s), Date=(%s), Amount= (%s), Comments=(%s), Receipt=(%s) WHERE TransID=(%s)" cur.execute(sql, (Name, Description, WithdrawDeposit, Company, Date, Amount, Comments, name, TransID)) Date = month + "-" + day + "-" + year request.get_data('Date') return render_template("UpdatePayment/Update.html", Name=Name, Description=Description, WithdrawDeposit=WithdrawDeposit, Company=Company, Date=Date, Amount=Amount, Comments=Comments, image=name)
def result(): #Request data from newpayment webpage name = '' Name = request.form['Name'] Description = request.form['Description'] WithdrawDeposit = request.form['WithdrawDeposit'] Company = request.form['Company'] Date = request.form['Date'] #Split data since it is submitted as mm/dd/yyyy and convert to yyyy/mm/dd split = Date.split("-") month = split[0] day = split[1] year = split[2] Date = year + "-" + month + "-" + day #implemented required html tag to prevent crash if no amount Amount = request.form['Amount'] Amount = float(Amount) Comments = request.form['Comments'] # a check to ensure Amount will be positive or negative if (WithdrawDeposit == "Withdraw" or WithdrawDeposit == "withdraw"): Amount = (Amount * -1) if (WithdrawDeposit == "Deposit" or WithdrawDeposit == "deposit"): Amount = abs(Amount) # get data for new webpage, potentially unnecessary. request.get_data('Name') request.get_data('Description') request.get_data('WithdrawDeposit') request.get_data('Company') request.get_data('Amount') request.get_data('Comments') #if image isn't null, rotate the image and PIL automatically sheds off EXIF tag if request.files['file'].filename != '': image = Image.open(request.files['file'].stream) if hasattr(image, '_getexif'): orientation = 0x0112 exif = image._getexif() if exif is not None: orientation = exif[orientation] rotations = { 3: Image.ROTATE_180, 6: Image.ROTATE_270, 8: Image.ROTATE_90 } if orientation in rotations: image = image.transpose(rotations[orientation]) name = request.files['file'].filename path = 'C:/Users/johns/Google Drive/ProgrammingProjects/Python/Flask_Desktop/static/' + name #Does an optimization pass to compress without noticeably reducing quality image.save(path, "JPEG", optimize=True, quality=85) #Connect to database and commit data cur = Tlbx.dbConnectDict() query = ( "INSERT INTO tTransaction (Name, Description, WithdrawDeposit, Company, Date, Amount, Comments, Receipt) VALUES ( %s, %s, %s, %s, %s, %s, %s,%s)" ) data = (Name, Description, WithdrawDeposit, Company, Date, Amount, Comments, name) cur.execute(query, data) request.get_data('image') #Convert date back to display mm-dd-yyyy Date = month + "-" + day + "-" + year request.get_data('Date') return render_template("NewPayment/result.html", Name=Name, Description=Description, WithdrawDeposit=WithdrawDeposit, Company=Company, Date=Date, Amount=Amount, Comments=Comments, image=name)