Browse Source

first commit

Inyoung 8 years ago
parent
commit
372957c390
5 changed files with 182 additions and 233 deletions
  1. BIN
      __pycache__/app.cpython-35.pyc
  2. 123 176
      app.py
  3. 0 0
      itemlist.txt
  4. 35 43
      static/js/scripts.js
  5. 24 14
      templates/index.html

BIN
__pycache__/app.cpython-35.pyc


+ 123 - 176
app.py

@@ -1,210 +1,157 @@
-from flask import Flask, abort, jsonify, url_for, render_template, g, request
-from flask.json import JSONEncoder
+# File Name: app.py
+# Author Name: In-young Choung
+# Date: March 1, 2017
+# Description: This python file contains database configuration and creates database tables and fields using flask_sqlalchemy.
+#              Users' values passed from Javascript are inserted into the database table.
+#              It also has mapping request to interact with specific html files and
+#              it reads a file of itemlist.text and prints out to the console.
+
 from flask_sqlalchemy import SQLAlchemy
-from flask_httpauth import HTTPBasicAuth
-import decimal, re, json
-from passlib.apps import custom_app_context as pwd_context
-from itsdangerous import (TimedJSONWebSignatureSerializer as Serializer, BadSignature, SignatureExpired)
+from flask import Flask, render_template, request
+
 
+# passing the whole app code to Flask
 app = Flask(__name__)
-#Configuration for Database ORM
+
+# Configuration for Database ORM - database name: grocery app, user: groceryadmin, password: VKov2q3XTtqj6w9o
 app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://groceryadmin:VKov2q3XTtqj6w9o@localhost/groceryapp'
 app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True
+
+# Database instantiation
 db = SQLAlchemy(app)
 
-app.config['SECRET_KEY'] = 'geunyeorang cheoeum daehoa sijag hajamaja'
-auth = HTTPBasicAuth()
+# database ORM calc table - 3 columns
+class Calc(db.Model):
+    __tablename__="calc"
 
+    # database fields
+    id = db.Column(db.Integer, primary_key=True)
+    result = db.Column(db.String(64))
+    timestampe = db.Column(db.TIMESTAMP)
+
+    # adding constraints to delete all data in Item when calc is deleted.
+    item = db.relationship('Item', backref='calc', cascade='all, delete-orphan', lazy='dynamic')
 
-#This helper class will be used to facilitate the printing of database objects as strings
-# class MJSONEncoder(JSONEncoder):
-#     def default(self, obj):
-#         if isinstance(obj, decimal.Decimal):
-#             # Convert decimal instances to strings.
-#             return str(obj)
-#         return super(MJSONEncoder, self).default(obj)
-#
-#
-# app.json_encoder = MJSONEncoder
 
+# database ORM item table - 9 columns
+class Item(db.Model):
+    __tablename__ = "items"
 
-class User(db.Model):
-    __tablename__ = "users"
+    # database fields
     id = db.Column(db.Integer, primary_key=True)
-    email = db.Column(db.String(120), unique=True)
-    password_hash = db.Column(db.String(128))
-
-    def hash_password(self, password):
-        self.password_hash = pwd_context.encrypt(password)
-        print(self.password_hash)
-
-    def verify_password(self, password):
-        return pwd_context.verify(password, self.password_hash)
-
-    def generate_auth_token(self, expiration=600):
-        s = Serializer(app.config['SECRET_KEY'], expires_in=expiration)
-        return s.dumps({'id': self.id})
-
-    @staticmethod
-    def verify_auth_token(token):
-        print ('48 - ' + token)
-        s = Serializer(app.config['SECRET_KEY'])
-        try:
-            data = s.loads(token)
-        except SignatureExpired:
-            return None  # valid token, but expired
-        except BadSignature:
-            return None  # invalid token
-        user = User.query.get(data['id'])
-        if user is None:
-            return
-        return user
-
-
-
-@auth.verify_password
-def verify_password(email_or_token, password):
-    # first try to authenticate by token
-    user = User.verify_auth_token(email_or_token)
-    if not user:
-        # try to authenticate with username/password
-        user = User.query.filter_by(email=email_or_token).first()
-        print ('86')
-        print (user)
-        if not user or not user.verify_password(password):
-            return False
-    g.user = user
-    return True
+    item_type = db.Column(db.String(64))
+    brand_name = db.Column(db.String(64))
+    price = db.Column(db.Integer)
+    weight = db.Column(db.Integer)
+    weight_type = db.Column(db.String(5))
+    discount = db.Column(db.Integer)
+    discount_type = db.Column(db.String(20))
+    calc_id = db.Column(db.Integer, db.ForeignKey(Calc.id))
+
+
+# create all the tables defined as classes
+db.create_all()
 
 
+# mapping request to URLs
 @app.route('/', methods = ['GET', 'POST'])
 def index():
-    if request.method == 'POST':
-        if request.form['submit'] == 'calculate_btn':
-            weight1 = request.form['weight1']
-            weight2 = request.form['weight2']
-            print (weight1)
-            print (weight2)
-            # my_total = calculate(weight1, weight2)
-            # print (my_total)
-            my_total = 69
-
-            return my_total
     if request.method == 'GET':
+        # renders to html file
         return render_template('index.html')
 
 
-
-
-@app.route('/calculate_total/', methods = ['GET'])
+# end point where python gets user data from javascript
+@app.route('/calculate', methods = ['GET'])
 def calculate():
-    print (request)
-    print (request.view_args)
-    item1 = (request.args.get('item1'))
-    item2 = (request.args.get('item2'))
-    price1 = (request.args.get('price1'))
-    price2 = (request.args.get('price2'))
-    weight1 = (request.args.get('weight1'))
-    weight2 = (request.args.get('weight2'))
-
+    # get value from html
+    itemtype = (request.args.get('param1'))
+    brandN1 = (request.args.get('param2'))
+    brandN2 = (request.args.get('param3'))
+    price1 = (request.args.get('param4'))
+    price2 = (request.args.get('param5'))
+    weight1 = (request.args.get('param6'))
+    weightT1 = (request.args.get('param7'))
+    weight2 = (request.args.get('param8'))
+    weightT2 = (request.args.get('param9'))
+    discount1 = (request.args.get('param10'))
+    discountT1 = (request.args.get('param11'))
+    discount2 = (request.args.get('param12'))
+    discountT2 = (request.args.get('param13'))
+
+
+    #TODO: calculate function
     # total2 = float(total)
     # new_total = 1.0 + total2
     # print(new_total)
-
-    item1_byWeight = float(price1) / float(weight1);
-    item2_byWeight = float(price2) / float(weight2);
-
-    if (item1_byWeight < item2_byWeight) :
-        difference = float(item2_byWeight) - float(item1_byWeight)
-        result = (item1 + "is cheapter by " + difference)
-    else :
-        difference = float(item1_byWeight) - float(item2_byWeight)
-        result = (item2 + "is cheapter by " + difference)
-    print(result)
-
-    return result
-
-
-def calculate(weight1, weight2):
-    total = weight1 + weight2
-    return total
-
-
-@app.route('/login', methods=['POST'])
-def login():
-    if request.headers['content-Type'] == 'application/x-www-form-urlencoded':
-        email = request.form['email']
-        password = request.form['password']
-        if email is None or password is None:
-            abort(400)
-        if User.query.filter_by(email=email).first() is not None:
-            verify = verify_password(email, password)
-            user = User(email=email)
-            print('108 - ' + verify)
-            if verify:
-                print('You already in there\n')
-                return render_template('success.html')
-            else:
-                print ('Login failed')
-                return 'Login failed'
-
-        user = User(email=email)
-        User.hash_password(user, password)
-        db.session.add(user)
+    #
+    # weight_types = ['lb', 'kg', 'g']
+    #
+    # item1_byWeight = float(price1) / float(weight1);
+    # item2_byWeight = float(price2) / float(weight2);
+    #
+    # if (item1_byWeight < item2_byWeight) :
+    #     difference = float(item2_byWeight) - float(item1_byWeight)
+    #     result = (item1 + "is cheapter by " + difference)
+    # else :
+    #     difference = float(item1_byWeight) - float(item2_byWeight)
+    #     result = (item2 + "is cheapter by " + difference)
+    #
+    # print(param1 + param2)
+    # result = param1 + param2
+
+    # returns a row from db
+    # item_from_db = Item.query.filter_by(item_type=itemtype).first();
+
+    # if item_from_db is not None:
+    #     print("already exists in the database.")
+    # else:
+
+    try:
+        # define array variables to be ready to match with db columns
+        brand_names = [brandN1, brandN2]
+        prices = [price1, price2]
+        weights = [weight1, weight2]
+        weight_types = [weightT1, weightT2]
+        discounts = [discount1, discount2]
+        discount_types = [discountT1, discountT2]
+
+        # iteration variable for loop
+        i = 0
+
+        # loop twice to save two compared items into database
+        for i in range(0, 2):
+            item = Item(item_type = itemtype, brand_name = brand_names[i], price =prices[i],
+                           weight=weights[i] , weight_type = weight_types[i], discount = discounts[i] ,
+                           discount_type = discount_types[i])
+
+            # insert a new row into the database
+            db.session.add(item)
+
+        # write it to db disk once the loop is done
         db.session.commit()
-        return render_template('success.html')
-    elif request.headers['Content-Type'] == 'application/json':
-        print ('122')
-        print(request.json)
-        email = request.json.get('email')
-        password = request.json.get('password')
-        if email is None or password is None:
-            abort(400)
-        if User.query.filter_by(email=email).first() is not None:
-            verify = verify_password(email, password)
-            user = User(email=email)
-            print ('130')
-            print (verify)
-            if verify:
-                print (g.user.id)
-                token = g.user.generate_auth_token(600)
-                return jsonify({'email': user.email, 'authToken': token.decode('ascii')}), 201, {
-                    'Location': url_for('get_user', id=g.user.id, _external=True)}
-            else:
-                print ('Error: Login Unsuccessful')
-                return 'Error: Login Unsuccessful'
-
-        user = User(email=email)
-        User.hash_password(user, password)
-        db.session.add(user)
-        db.session.commit()
-        verify_password(email, password)
-        token = g.user.generate_auth_token(600)
-        return jsonify({'email': user.email, 'authToken': token.decode('ascii')}), 201, {'Location': url_for('get_user', id=user.id, _external=True)}
-
-
-@app.route('/users/<int:id>')
-@auth.login_required
-def get_user(id):
-    user = User.query.get(id)
-    if not user:
-        abort(400)
-    return jsonify({'email': user.email, 'password': user.password_hash})
 
+    # catch the exception and print it
+    except ValueError:
+        print(ValueError)
+        print("failed to create new row")
 
-@app.route('/token')
-@auth.login_required
-def get_auth_token():
-    token = g.user.generate_auth_token(600)
-    return jsonify({'token': token.decode('ascii'), 'duration': 600})
 
+# File I/O - prints a list of grocery items
+path = "C:\In-young Choung\Computer Programming\Self Programming Files\grocerycalc\itemlist.txt"
+# open a file for writing and create it if it doesn't exist.
+f = open(path,"w+")
 
-@app.route('/resource')
-@auth.login_required
-def get_resource():
-    return jsonify({'data': 'Hello, %s!' % g.user.email})
+# open the file in the defined path and "r" read it
+f = open(path, "r")
+if f.mode == 'r':
+    # use read function to read the entire file.
+    contents = f.read()
+    #print the file content in the console
+    print(contents)
 
 
+# main method
 if __name__ == '__main__':
     app.debug = True
     # app.debug = False

+ 0 - 0
itemlist.txt


+ 35 - 43
static/js/scripts.js

@@ -1,48 +1,40 @@
-function calc_handle(item1, item2, price1, price2, weight1, weight2) {
-    console.dir(item1);
-    console.dir(item2);
-    console.dir(price1);
-    console.dir(price2);
-    console.dir(weight1);
-    console.dir(weight2);
+// File Name: scrips.js
+// Author Name: In-young Choung
+// Date: March 1, 2017
+// Description: This Javascript file redirects users' input values asynchronously
+//              to the end points in python file.
 
-    if (!isNaN(price1) || !isNaN(price2) || !isNaN(weight1) || !isNaN(weight2)) {
-        // var item1_byWeight = Number(price1) / Number(weight1);
-        // var item2_byWeight = Number(price2) / Number(weight2);
-        //
-        // if (item1_byWeight < item2_byWeight) {
-        //     var difference = Number(item2_byWeight) - Number(item1_byWeight)
-        //     console.log(item1 + "is cheapter by " + difference);
-        // } else {
-        //     var difference = Number(item1_byWeight) - Number(item2_byWeight)
-        //     console.log(item2 + "is cheapter by " + difference);
-        // }
 
-        // send_total(item1, item2, price1, price2, weight1, weight2);
-    } else {
-        alert("You entered wrong format.");
-    }
-}
+/**
+ * handling form data passed from html and relaying it to python
+ *
+ * @param itemtype
+ * @param brandN1
+ * @param brandN2
+ * @param price1
+ * @param price2
+ * @param weight1
+ * @param weightT1
+ * @param weight2
+ * @param weightT2
+ * @param discount1
+ * @param discountT1
+ * @param discount2
+ * @param discountT2
+ */
+function calc_handle(itemtype, brandN1, brandN2, price1, price2,
+                     weight1, weightT1, weight2, weightT2,
+                     discount1, discountT1, discount2, discountT2) {
 
-function send_total(item1, item2, price1, price2, weight1, weight2) {
+    // create an object of XMLHttpRequest
     x = new XMLHttpRequest();
-    x.open("GET", '/calculate_total?param1=value1&param2=value2', true);
+
+    // send an http request to /calculate which is mapped in python
+    x.open("GET", '/calculate?param1=' + itemtype + '&param2=' + brandN1 + '&param3=' + brandN2 +
+                    '&param4=' + price1 + '&param5=' + price2 + '&param6=' + weight1 + '&param7=' + weightT1 +
+                    '&param8=' + weight2 + '&param9=' + weightT2 + '&param10=' + discount1 + '&param11=' + discountT1 +
+                    '&param12=' + discount2 + '&param13=' + discountT2 + true);
+
+    // fire the request
     x.send();
-}
-//
-// var oReq = new XMLHttpRequest();
-// oReq.onload = function (e) {
-//     results.innerHTML = e.target.response.message;
-// };
-// oReq.open('GET', e.target.dataset.url + '?' + new Date().getTime(), true);
-// oReq.responseType = 'json';
-// oReq.send();
-//
-//
-// http.open("GET", url+"?"+params, true);
-// http.onreadystatechange = function()
-// {
-//     if(http.readyState == 4 && http.status == 200) {
-//         alert(http.responseText);
-//     }
-// }
+}

+ 24 - 14
templates/index.html

@@ -1,4 +1,12 @@
 <!DOCTYPE html>
+<!--
+File Name: index.html
+Author Name: In-young Choung
+Date: March 1, 2017
+Description: This html serves content locally to interact with users
+             and sends users' input values to Javascript.
+>
+
 <html lang="en">
 
 <head>
@@ -26,7 +34,7 @@
                 <br>
                 <br>
                 <br>
-                <form class="col-lg-12" action="{{url_for('login')}}" method="POST">
+                <form class="col-lg-12" action="{{url_for('index')}}" method="POST">
                     <div class="input-group" style="width:340px;text-align:center;margin:0 auto;, ">
                         <input class="form-control input-lg" title="Don't worry. We hate spam, and will not share your email with anyone." placeholder="Enter your email address" type="email" name="email">
                         <input class="form-control input-lg" title="Use the password you use for everything. Trust us." placeholder="Enter your password" type="password" name="password">
@@ -36,18 +44,18 @@
                 </form>
             </div>
         </div>
-
-        <form
 {#                action="action_page.php"#}
-        >
 
+
+            <br>
+            <form id = "calcform" style = "margin-left: 20%">
             <table id="comparison-table" style="width: auto;">
                 <tr>
                     <td>
                         Item Type:
                     </td>
                     <td class="colspan-4" colspan="4">
-                        <input type="text" name="itemtype"  placeholder="Bacon">
+                        <input type="text" name="itemtype"  placeholder="Bacon" >
                     </td>
                 </tr>
                 <tr>
@@ -55,10 +63,10 @@
                         Brand Name:
                     </td>
                     <td class="colspan-2" colspan="2">
-                        <input type="text" name="brandname1" placeholder="Maple Leaf">
+                        <input type="text" name="brandname1" placeholder="Maple Leaf" value="">
                     </td>
                     <td class="colspan-2" colspan="2">
-                        <input type="text" name="brandname2" placeholder="Shanaor">
+                        <input type="text" name="brandname2" placeholder="Shanaor" value="">
                     </td>
                 </tr>
                 <tr>
@@ -66,7 +74,7 @@
                         Price:
                     </td>
                     <td class="colspan-2" colspan="2">
-                        <input type="text" name="price1" value="" >
+                        <input type="text" name="price1" value="">
                     </td>
                     <td class="colspan-2" colspan="2">
                         <input type="text" name="price2" value="">
@@ -87,7 +95,7 @@
                         </select>
                     </td>
                     <td>
-                        <input type="text" name="weight2" value="">
+                        <input type="text" name="weight2" value = "">
                     </td>
                     <td>
                         <select>
@@ -119,17 +127,20 @@
                             <option>buy and get free</option>
                         </select>
                     </td>
-                </tr>
+                 </tr>
                 </table>
             <br><br>
             <input type="text" value="{{ my_total }}" class="calculate_result" readonly>
             <button type="button"
-                    onclick="calc_handle(this.form[2].value,this.form[3].value,
+                    onclick="calc_handle(this.form[0].value, this.form[1].value,
+                                         this.form[2].value, this.form[3].value,
                                          this.form[4].value, this.form[5].value,
-                                         this.form[5].value, this.form[6].value)"
+                                         this.form[6].value, this.form[7].value,
+                                         this.form[8].value, this.form[9].value,
+                                         this.form[10].value, this.form[11].value,
+                                         this.form[12].value)"
                     value="calculate_btn">Calculate</button>
             <br><br>
-            <input type="submit" value="Submit">
         </form>
 
 <p>If you click the "Submit" button, the form-data will be sent to a page called "action_page.php".</p>
@@ -200,5 +211,4 @@
     <script src="{{ url_for('static', filename='js/bootstrap.min.js') }}"></script>
     <script src="{{ url_for('static', filename='js/scripts.js') }}"></script>
 </body>
-
 </html>