app.py 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238
  1. # File Name: app.py
  2. # Modified Date: March 24, 2017
  3. # Description: This python file contains database configuration and creates database tables and fields using flask_sqlalchemy.
  4. # Users' values passed from Javascript are inserted into the database table.
  5. # It also has mapping request to interact with specific html files and
  6. # it reads a file of itemlist.text and prints out to the console.
  7. __author__ = "Inyoung Choung"
  8. import tkinter
  9. from tkinter import messagebox
  10. from flask_sqlalchemy import SQLAlchemy
  11. from flask import Flask, render_template, request
  12. # passing the whole app code to Flask
  13. app = Flask(__name__)
  14. # Configuration for Database ORM - database name: grocery app, user: groceryadmin, password: VKov2q3XTtqj6w9o
  15. app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://groceryadmin:VKov2q3XTtqj6w9o@localhost/groceryapp'
  16. app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True
  17. # Database instantiation
  18. db = SQLAlchemy(app)
  19. # database ORM calc table - 3 columns
  20. class Calc(db.Model):
  21. __tablename__="calc"
  22. # database fields
  23. id = db.Column(db.Integer, primary_key=True)
  24. result = db.Column(db.String(64))
  25. timestampe = db.Column(db.TIMESTAMP)
  26. # adding constraints to delete all data in Item when calc is deleted.
  27. item = db.relationship('Item', backref='calc', cascade='all, delete-orphan', lazy='dynamic')
  28. # database ORM item table - 9 columns
  29. class Item(db.Model):
  30. __tablename__ = "items"
  31. # database fields
  32. id = db.Column(db.Integer, primary_key=True)
  33. item_type = db.Column(db.String(64))
  34. brand_name = db.Column(db.String(64))
  35. price = db.Column(db.DECIMAL)
  36. weight = db.Column(db.DECIMAL)
  37. weight_type = db.Column(db.String(5))
  38. discount = db.Column(db.DECIMAL)
  39. discount_type = db.Column(db.String(20))
  40. calc_id = db.Column(db.Integer, db.ForeignKey(Calc.id))
  41. # create all the tables defined as classes
  42. # db.create_all()
  43. # mapping request to URLs
  44. @app.route('/', methods = ['GET', 'POST'])
  45. def index():
  46. if request.method == 'GET':
  47. # renders to html file
  48. return render_template('index.html')
  49. def convert(weightT1, weightT2, weight2):
  50. if weightT1 == "lb":
  51. if weightT2 == "kg":
  52. weight2 = float(weight2) * 2.20462
  53. elif weightT2 == "g":
  54. weight2 = float(weight2) * 0.002205
  55. elif weightT1 == "kg":
  56. if weightT2 == "lb":
  57. weight2 = float(weight2) * 0.453592
  58. elif weightT2 == "g":
  59. weight2 = float(weight2) * 0.001
  60. elif weightT1 == "g":
  61. if weightT2 == "kg":
  62. weight2 = float(weight2) * 1000
  63. elif weightT2 == "lb":
  64. weight2 = float(weight2) * 453.592
  65. return weight2
  66. def alert_message(message_arg):
  67. if message_arg is None:
  68. message = str("Please fill out all the forms.")
  69. else:
  70. message = message_arg
  71. return message
  72. global newWeightForSecondItem
  73. # end point where python gets user data from javascript
  74. @app.route('/calculate', methods = ['GET'])
  75. def calculate():
  76. # get value from html
  77. itemtype = (request.args.get('param1'))
  78. brandN1 = (request.args.get('param2'))
  79. brandN2 = (request.args.get('param3'))
  80. price1 = (request.args.get('param4'))
  81. price2 = (request.args.get('param5'))
  82. weight1 = (request.args.get('param6'))
  83. weightT1 = (request.args.get('param7'))
  84. weight2 = (request.args.get('param8'))
  85. weightT2 = (request.args.get('param9'))
  86. discount1 = (request.args.get('param10'))
  87. discountT1 = (request.args.get('param11'))
  88. discount2 = (request.args.get('param12'))
  89. discountT2 = (request.args.get('param13'))
  90. if (itemtype is None or itemtype == "" or
  91. brandN1 is None or brandN1 == "" or
  92. brandN2 is None or brandN2 == "" or
  93. price1 is None or price1 == "" or
  94. price2 is None or price2 == "" or
  95. weight1 is None or weight1 == "" or
  96. weightT1 is None or weightT1 == "" or
  97. weight2 is None or weight2 == "" or
  98. weightT2 is None or weightT2 == "" or
  99. discount1 is None or discount1 == "" or
  100. discountT1 is None or discountT1 == "" or
  101. discount2 is None or discount2 == "" or
  102. discountT2 is None or discountT2 == ""):
  103. # hide main window
  104. root = tkinter.Tk()
  105. root.withdraw()
  106. messagebox.showerror( "Alert - Empty fields", alert_message("Please fill out all the forms."))
  107. # after users values are accepted, do calculation.
  108. if weightT1 != weightT2:
  109. newWeightForSecondItem = convert(weightT1, weightT2, weight2)
  110. # both items have the same weight type from this point
  111. else:
  112. newWeightForSecondItem = weight2
  113. if discountT1 == "percentage":
  114. finalPrice1 = float((float(price1) - (float(price1) * (float(discount1) * float(0.01)))) / float(weight1))
  115. elif discountT1 == "dollar":
  116. finalPrice1 = float((float(price1) - float(discount1)) / float(weight1))
  117. if discountT2 == "percentage":
  118. finalPrice2 = float((float(price2) - (float(price2) * (float(discount2) * float(0.01)))) / float(newWeightForSecondItem))
  119. elif discountT2 == "dollar":
  120. finalPrice2 = float((float(price2) - (float(discount2))) / float(newWeightForSecondItem))
  121. if finalPrice1 > finalPrice2:
  122. priceDiff = round(float(finalPrice1 - finalPrice2), 3)
  123. print(brandN1 + str(" is cheaper by "), priceDiff)
  124. result = str(brandN1 + str(" is cheaper by ") + str(priceDiff) + str(" cents per unit weight "))
  125. elif finalPrice1 < finalPrice2:
  126. priceDiff = round(float(finalPrice2 - finalPrice1), 3)
  127. print(brandN2 + str(" is cheaper by "), priceDiff)
  128. result = str(brandN2 + str(" is cheaper by ") + str(priceDiff) + str(" cents per unit weight "))
  129. else:
  130. result = str("The price is equal so get anything!")
  131. # hide main window
  132. root = tkinter.Tk()
  133. root.withdraw()
  134. messagebox.showinfo("Calculation Result", result)
  135. try:
  136. # define array variables to be ready to match with db columns
  137. brand_names = [brandN1, brandN2]
  138. prices = [price1, price2]
  139. weights = [weight1, weight2]
  140. weight_types = [weightT1, weightT2]
  141. discounts = [discount1, discount2]
  142. discount_types = [discountT1, discountT2]
  143. # iteration variable for loop
  144. i = 0
  145. # loop twice to save two compared items into database
  146. for i in range(0, 2):
  147. item = Item(item_type = itemtype, brand_name = brand_names[i], price =prices[i],
  148. weight=weights[i] , weight_type = weight_types[i], discount = discounts[i] ,
  149. discount_type = discount_types[i])
  150. # insert a new row into the database
  151. db.session.add(item)
  152. # write it to db disk once the loop is done
  153. db.session.commit()
  154. return result
  155. # catch the exception and print it
  156. except ValueError:
  157. print(ValueError)
  158. print("failed to create new row")
  159. return -1
  160. # File I/O - prints a list of grocery items
  161. def writefile(path, word):
  162. # open a file for writing and create it if it doesn't exist.
  163. if path is None:
  164. # set a specific path
  165. filepath = "C:\In-young Choung\Computer Programming\Self Programming Files\grocerycalc\itemlist.txt"
  166. # output a file if it doesn't exist
  167. f = open(filepath, "w+")
  168. # write some texts inside the opened file
  169. f.write("chicken, ")
  170. f.write("milk")
  171. readfile(filepath)
  172. else: # when the path is specified
  173. filepath= path
  174. # output a file if it doesn't exist
  175. f = open(filepath, "w+")
  176. # write text that is passed as a paramter in the method
  177. f.write(word)
  178. # read file that is created and pass filepath as a parameter
  179. def readfile(filepath):
  180. # open the file in the defined path and "r" read it
  181. f = open(filepath, "r")
  182. if f.mode == 'r':
  183. # use read function to read the entire file.
  184. contents = f.read()
  185. #print the file content in the console
  186. print(contents)
  187. # main method
  188. if __name__ == '__main__':
  189. app.debug = True
  190. # app.debug = False
  191. writefile(None, None)
  192. app.run()