app.py 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152
  1. # File Name: app.py
  2. # Modified Date: April 15, 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.
  6. # Method Level Comment: Python Convention (inside function)
  7. __author__ = "Inyoung Choung"
  8. from flask_sqlalchemy import SQLAlchemy
  9. from flask import Flask, render_template, request
  10. from implementation import Impl
  11. import datetime
  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(255))
  25. timestamp = 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. @app.route('/', methods = ['GET', 'POST'])
  44. def index():
  45. """
  46. mapping request to URLs
  47. :return: render_template('index.html')
  48. """
  49. if request.method == 'GET':
  50. # renders to html file
  51. return render_template('index.html')
  52. # These variables are declared as global.
  53. global newWeightForSecondItem
  54. global list
  55. @app.route('/calculate', methods=['GET'])
  56. def calculate():
  57. """
  58. end point where python gets user data from javascript.
  59. :return: 'Successful'
  60. """
  61. # get value from javascript.
  62. itemtype = str((request.args.get('param1')))
  63. brandN1 = str((request.args.get('param2')))
  64. brandN2 = str((request.args.get('param3')))
  65. price1 = str((request.args.get('param4')))
  66. price2 = str((request.args.get('param5')))
  67. weight1 = str((request.args.get('param6')))
  68. weightT1 = str((request.args.get('param7')))
  69. weight2 = str((request.args.get('param8')))
  70. weightT2 = str((request.args.get('param9')))
  71. discount1 = str((request.args.get('param10')))
  72. discountT1 = str((request.args.get('param11')))
  73. discount2 = str((request.args.get('param12')))
  74. discountT2 = str((request.args.get('param13')))
  75. # instantiate an object of Impl and pass arguments.
  76. implObj = Impl(itemtype, brandN1, brandN2, price1, price2, weight1, weightT1, weight2,
  77. weightT2, discount1,discountT1, discount2, discountT2)
  78. try:
  79. # save data into calc table of the database.
  80. calc = Calc(result = implObj.get_result(), timestamp = '{:%Y-%b-%d %H:%M:%S}'.format(datetime.datetime.now()))
  81. # insert a new row into the database.
  82. db.session.add(calc)
  83. # define array variables to be ready to match with db columns.
  84. brand_names = [brandN1, brandN2]
  85. prices = [price1, price2]
  86. weights = [weight1, weight2]
  87. weight_types = [weightT1, weightT2]
  88. discounts = [discount1, discount2]
  89. discount_types = [discountT1, discountT2]
  90. # iteration variable for loop.
  91. i = 0
  92. # loop twice to save two compared items into item table of the database.
  93. for i in range(0, 2):
  94. item = Item(item_type=itemtype, brand_name=brand_names[i], price=prices[i],
  95. weight=weights[i], weight_type=weight_types[i], discount=discounts[i],
  96. discount_type=discount_types[i])
  97. # insert a new row into the database.
  98. db.session.add(item)
  99. # write it to db disk once the loop is done.
  100. db.session.commit()
  101. # initialize empty list to collect item objects.
  102. list = []
  103. # loop for the result of the query to display brand_name column rows of Item table.
  104. for row in db.session.query(Item, Item.brand_name).all():
  105. # add brand name into the list
  106. list.append(row.brand_name)
  107. # sorts the item list by the alphabetical order.
  108. implObj.sort(list)
  109. # calls writefile function and pass the sorted list.
  110. implObj.writefile(None, list)
  111. implObj.readfile()
  112. return 'Successful'
  113. # catch the exception and print it.
  114. except ValueError:
  115. print(ValueError)
  116. print("failed to create new row")
  117. return -1
  118. if __name__ == '__main__':
  119. # main method that starts the application.
  120. # debugging purpose.
  121. app.debug = True
  122. app.run()