Browse Source

First update in a while

Inyoung 8 years ago
parent
commit
131f5a42e1

+ 64 - 111
app.py

@@ -7,23 +7,25 @@ from passlib.apps import custom_app_context as pwd_context
 from itsdangerous import (TimedJSONWebSignatureSerializer as Serializer, BadSignature, SignatureExpired)
 
 app = Flask(__name__)
-app.config['SECRET_KEY'] = 'geunyeorang cheoeum daehoa sijag hajamaja'
-app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://ruvadmin:ge9BQ7fT8bVBgm1B@localhost/ruvapp'
+#Configuration for Database ORM
+app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://groceryadmin:VKov2q3XTtqj6w9o@localhost/groceryapp'
 app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True
 db = SQLAlchemy(app)
-auth = HTTPBasicAuth()
-
-
-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.config['SECRET_KEY'] = 'geunyeorang cheoeum daehoa sijag hajamaja'
+auth = HTTPBasicAuth()
 
 
-app.json_encoder = MJSONEncoder
+#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
 
 
 class User(db.Model):
@@ -59,25 +61,6 @@ class User(db.Model):
         return user
 
 
-class Roof(db.Model):
-    __tablename__ = "roofs"
-    id = db.Column(db.Integer, primary_key=True)
-    length = db.Column(db.DECIMAL(10, 3))
-    width = db.Column(db.DECIMAL(10, 3))
-    slope = db.Column(db.Float)
-    price = db.Column(db.DECIMAL(10, 2))
-    address = db.Column(db.VARCHAR(255))
-
-    def serialize(self):
-        return {
-            'id': self.id,
-            'length': re.sub("[^0-9^.]", "", str(self.length)),
-            'width': re.sub("[^0-9^.]", "", str(self.width)),
-            'slope': re.sub("[^0-9^.]", "", str(self.slope)),
-            'price': re.sub("[^0-9^.]", "", str(self.price)),
-            'address': self.address.encode("utf-8"),
-        }
-
 
 @auth.verify_password
 def verify_password(email_or_token, password):
@@ -94,9 +77,57 @@ def verify_password(email_or_token, password):
     return True
 
 
-@app.route('/')
+@app.route('/', methods = ['GET', 'POST'])
 def index():
-    return render_template('index.html')
+    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':
+        return render_template('index.html')
+
+
+
+
+@app.route('/calculate_total/', 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'))
+
+    # 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'])
@@ -152,38 +183,6 @@ def login():
         return jsonify({'email': user.email, 'authToken': token.decode('ascii')}), 201, {'Location': url_for('get_user', id=user.id, _external=True)}
 
 
-@app.route('/roof/add', methods=['POST'])
-@auth.login_required
-def add_roof():
-    print ('Requesting roof addition')
-    if request.headers['Content-Type'] == 'application/json':
-        print ('155')
-        print (request.json)
-        length = request.json.get('length')
-        width = request.json.get('width')
-        slope = request.json.get('slope')
-        address = request.json.get('address')
-        price = request.json.get('price')
-
-        if length is None or width is None or slope is None or address is None or price is None:
-            print ('Something not set')
-            abort(400)
-        if Roof.query.filter_by(address=address).first() is not None:
-            roof = Roof(address=address, price=price)
-            print ('Found a roof')
-            if roof is not None:
-                print ('Roof is not None')
-                print (str(roof.serialize()))
-                return jsonify({'Roof': roof.serialize()}), 201
-        print ('Make new roof')
-        roof = Roof(address=address, length=length, width=width, slope=slope, price=price)
-        db.session.add(roof)
-        db.session.commit()
-        print ('Created roof==> ' + str(roof.serialize()))
-        return jsonify({'Roof': roof.serialize()}), 201, {
-            'Location': url_for('get_roof', address=roof.address, _external=True)}
-
-
 @app.route('/users/<int:id>')
 @auth.login_required
 def get_user(id):
@@ -193,15 +192,6 @@ def get_user(id):
     return jsonify({'email': user.email, 'password': user.password_hash})
 
 
-@app.route('/roofs/<int:id>')
-@auth.login_required
-def get_roof(id):
-    roof = Roof.query.get(id)
-    if not roof:
-        abort(400)
-    return jsonify({'Roof': roof.serialize()})
-
-
 @app.route('/token')
 @auth.login_required
 def get_auth_token():
@@ -215,43 +205,6 @@ def get_resource():
     return jsonify({'data': 'Hello, %s!' % g.user.email})
 
 
-@app.route('/roofs/all', methods=['GET'])
-@auth.login_required
-def get_roofs():
-
-    roofs = Roof.query.all()
-    rStr = ''
-    mJson = ''
-    rlist = [None] * 10
-    i = 0
-    for roof in roofs:
-
-        # rStr += str(jsonify({i: (roof.serialize())}))
-        mJson += '{"roof":' + str(roof.serialize()).replace("'", '"') + '},'
-        rStr += (str([(str(i) + ":" + str((roof.serialize())))]))
-        rObj = (["\""+str(i)+"\"", str(roof.serialize())])
-        rlist.append(["roof", rObj])
-        i += 1
-    # rStr = ("[" + rStr[:-1] + "]")
-    mJson = '{"Roofs":[' + str((mJson[:-1])) + ']}'
-    # rjson = json.dumps(rStr.replace('\\n', '\n').replace('\"', '"'))
-
-    if not roofs:
-        abort(400)
-    # return jsonify({'Roofs': rStr.replace("\\", "")}), 201
-    # return jsonify({'Roofs': str(rStr).replace('\\n', '\n').replace('\"', '"')}), 201
-    return (mJson.replace('\\"', '"')), 201
-
-
-def json_list(list):
-    lst = []
-    for pn in list:
-        d = {}
-        d['roof']=pn
-        lst.append(d)
-    return json.dumps(lst)
-
-
 if __name__ == '__main__':
     app.debug = True
     # app.debug = False

File diff suppressed because it is too large
+ 8 - 0
static/css/bootstrap.min.css


+ 14 - 0
static/css/inyoung.css

@@ -0,0 +1,14 @@
+.container-full {
+    background-image:
+            url(' /static/image/pexels-photo-26799.jpg');
+    background-size:100%
+}
+
+
+#comparison-table td.colspan-4 > input {
+    width: 100%
+}
+
+#comparison-table td.colspan-2 > input {
+    width: 100%
+}

+ 54 - 0
static/css/styles.css

@@ -0,0 +1,54 @@
+html,body {
+  height:100%;
+
+}
+
+h1 {
+  font-family: Arial,sans-serif;
+  font-size:80px;
+  color:#DDCCEE;
+}
+
+.lead {
+	color:#DDCCEE;
+}
+
+
+/* Custom container */
+.container-full {
+  margin: 0 auto;
+  width: 100%;
+  min-height:100%;
+  background-color:#110022;
+  background-image: url("/static/image/pexels-photo-26799.jpg");
+  color:#eee;
+  overflow:hidden;
+}
+
+.container-full a {
+  color:#efefef;
+  text-decoration:none;
+}
+
+.v-center {
+  margin-top:7%;
+}
+
+/* Form */
+.input-group .input-lg {
+  padding: 6px;
+  margin: 4px;
+  background: rgb(214, 233, 198);
+}
+
+.input-group .input-lg:nth-child(2) {
+  border-radius: 6px!important;
+}
+
+.input-group-btn {
+  float: right;
+}
+
+.input-group-btn .btn {
+    background: #594b6d;
+}

BIN
static/image/pexels-photo-128402.jpeg


BIN
static/image/pexels-photo-26799.jpg


BIN
static/image/street-market-fruits-grocery.jpg


File diff suppressed because it is too large
+ 8 - 0
static/js/bootstrap.min.js


+ 48 - 0
static/js/scripts.js

@@ -0,0 +1,48 @@
+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);
+
+    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.");
+    }
+}
+
+function send_total(item1, item2, price1, price2, weight1, weight2) {
+    x = new XMLHttpRequest();
+    x.open("GET", '/calculate_total?param1=value1&param2=value2', true);
+    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);
+//     }
+// }

+ 204 - 0
templates/index.html

@@ -0,0 +1,204 @@
+<!DOCTYPE html>
+<html lang="en">
+
+<head>
+    <meta http-equiv="content-type" content="text/html; charset=UTF-8">
+    <meta charset="utf-8">
+    <title>Calculate Grocery</title>
+    <meta name="generator" content="Bootply" />
+    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
+    <link href="{{ url_for('static', filename='css/bootstrap.min.css') }}" rel="stylesheet">
+{#    <link href="//netdna.bootstrapcdn.com/font-awesome/3.2.1/css/font-awesome.min.css" rel="stylesheet">#}
+    <!--[if lt IE 9]>
+{#      <script src="//html5shim.googlecode.com/svn/trunk/html5.js"></script>#}
+    <![endif]-->
+    <link href="{{ url_for('static', filename='css/styles.css') }}" rel="stylesheet">
+    <link href="{{ url_for('static', filename='css/inyoung.css') }}" rel="stylesheet">
+
+</head>
+
+<body>
+    <div class="container-full">
+        <div class="row">
+            <div class="col-lg-12 text-center v-center">
+                <h1>Grocery Calculation</h1>
+                <p class="lead">Smart-save your grocery expense.</p>
+                <br>
+                <br>
+                <br>
+                <form class="col-lg-12" action="{{url_for('login')}}" 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">
+
+                        <span class="input-group-btn"><button class="btn btn-lg btn-primary" type="submit">GO</button></span>
+                    </div>
+                </form>
+            </div>
+        </div>
+
+        <form
+{#                action="action_page.php"#}
+        >
+
+            <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">
+                    </td>
+                </tr>
+                <tr>
+                    <td>
+                        Brand Name:
+                    </td>
+                    <td class="colspan-2" colspan="2">
+                        <input type="text" name="brandname1" placeholder="Maple Leaf">
+                    </td>
+                    <td class="colspan-2" colspan="2">
+                        <input type="text" name="brandname2" placeholder="Shanaor">
+                    </td>
+                </tr>
+                <tr>
+                    <td>
+                        Price:
+                    </td>
+                    <td class="colspan-2" colspan="2">
+                        <input type="text" name="price1" value="" >
+                    </td>
+                    <td class="colspan-2" colspan="2">
+                        <input type="text" name="price2" value="">
+                    </td>
+                </tr>
+                <tr>
+                    <td>
+                      Weight:
+                    </td>
+                    <td>
+                        <input type="text" name="weight1" value="">
+                    </td>
+                    <td>
+                        <select>
+                            <option>lb</option>
+                            <option>kg</option>
+                            <option>g</option>
+                        </select>
+                    </td>
+                    <td>
+                        <input type="text" name="weight2" value="">
+                    </td>
+                    <td>
+                        <select>
+                            <option>lb</option>
+                            <option>kg</option>
+                            <option>g</option>
+                        </select>
+                    </td>
+                </tr>
+                <tr>
+                    <td>
+                        Discounts:
+                    </td>
+                    <td>
+                       <input type="text" name="discount1" value="">
+                    </td>
+                    <td>
+                        <select>
+                            <option>percentage</option>
+                            <option>buy and get free</option>
+                        </select>
+                    </td>
+                    <td>
+                       <input type="text" name="discount2" value="">
+                    </td>
+                    <td>
+                        <select>
+                            <option>percentage</option>
+                            <option>buy and get free</option>
+                        </select>
+                    </td>
+                </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,
+                                         this.form[4].value, this.form[5].value,
+                                         this.form[5].value, this.form[6].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>
+        <!-- /row -->
+
+        <div class="row">
+            <div class="col-lg-12 text-center v-center" style="font-size:39pt;">
+{#                <a href="#"><i class="icon-google-plus"></i></a>#}
+                <a href="#"><i class="icon-facebook"></i></a>
+                <a href="#"><i class="icon-twitter"></i></a>
+                <a href="#"><i class="icon-github"></i></a>
+{#                <a href="#"><i class="icon-pinterest"></i></a>#}
+            </div>
+        </div>
+        <br>
+        <br>
+        <br>
+        <br>
+        <br>
+    </div>
+    <!-- /container full -->
+
+    <div class="container">
+        <hr>
+        <div class="row">
+            <div class="col-md-4">
+                <div class="panel panel-default">
+                    <div class="panel-heading">
+                        <h3>Hello.</h3>
+                    </div>
+                    <div class="panel-body">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis pharetra varius quam sit amet vulputate. Quisque mauris augue, molestie tincidunt condimentum vitae, gravida a libero. Aenean sit amet felis dolor, in sagittis nisi. Sed ac orci quis tortor imperdiet venenatis. Duis elementum auctor accumsan. Aliquam in felis sit amet augue.
+                    </div>
+                </div>
+            </div>
+            <div class="col-md-4">
+                <div class="panel panel-default">
+                    <div class="panel-heading">
+                        <h3>Hello.</h3>
+                    </div>
+                    <div class="panel-body">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis pharetra varius quam sit amet vulputate. Quisque mauris augue, molestie tincidunt condimentum vitae, gravida a libero. Aenean sit amet felis dolor, in sagittis nisi. Sed ac orci quis tortor imperdiet venenatis. Duis elementum auctor accumsan. Aliquam in felis sit amet augue.
+                    </div>
+                </div>
+            </div>
+            <div class="col-md-4">
+                <div class="panel panel-default">
+                    <div class="panel-heading">
+                        <h3>Hello.</h3>
+                    </div>
+                    <div class="panel-body">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis pharetra varius quam sit amet vulputate. Quisque mauris augue, molestie tincidunt condimentum vitae, gravida a libero. Aenean sit amet felis dolor, in sagittis nisi. Sed ac orci quis tortor imperdiet venenatis. Duis elementum auctor accumsan. Aliquam in felis sit amet augue.
+                    </div>
+                </div>
+            </div>
+        </div>
+
+        <div class="row">
+            <div class="col-lg-12">
+                <br>
+                <br>
+                <p class="pull-right"><a href="http://www.bootply.com">Template from Bootply</a> &nbsp; ©Copyright 2014 ACME<sup>TM</sup> Brand.</p>
+                <br>
+                <br>
+            </div>
+        </div>
+    </div>
+
+    <!-- script references -->
+    <script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
+    <script src="{{ url_for('static', filename='js/bootstrap.min.js') }}"></script>
+    <script src="{{ url_for('static', filename='js/scripts.js') }}"></script>
+</body>
+
+</html>

+ 56 - 0
templates/success.html

@@ -0,0 +1,56 @@
+<!DOCTYPE html>
+<html lang="en">
+
+<head>
+    <meta http-equiv="content-type" content="text/html; charset=UTF-8">
+    <meta charset="utf-8">
+    <title>Landing Page template</title>
+    <meta name="generator" content="Bootply" />
+    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
+    <link href="{{ url_for('static', filename='css/bootstrap.min.css') }}" rel="stylesheet">
+    <link href="//netdna.bootstrapcdn.com/font-awesome/3.2.1/css/font-awesome.min.css" rel="stylesheet">
+    <!--[if lt IE 9]>
+      <script src="//html5shim.googlecode.com/svn/trunk/html5.js"></script>
+    <![endif]-->
+    <link href="{{ url_for('static', filename='css/styles.css') }}" rel="stylesheet">
+</head>
+
+<body>
+    <div class="container-full">
+        <div class="row">
+            <div class="col-lg-12 text-center v-center">
+                <h1>Authenticated. Do your thing.</h1>
+                <p class="lead">Ruviate.</p>
+                <br>
+                <br>
+                <br>
+                <form class="col-lg-12">
+                    <div class="input-group" style="width:340px;text-align:center;margin:0 auto;">
+                        <h3>Thank you!</h3>
+                        <p>Hopefully you know the secrets.</p>
+                    </div>
+                </form>
+            </div>
+
+        </div>
+        <!-- /row -->
+
+        <div class="row">
+            <div class="col-lg-12 text-center v-center" style="font-size:39pt;">
+                <a href="#"><i class="icon-google-plus"></i></a>  <a href="#"><i class="icon-facebook"></i></a>  <a href="#"><i class="icon-twitter"></i></a>  <a href="#"><i class="icon-github"></i></a>  <a href="#"><i class="icon-pinterest"></i></a>
+            </div>
+        </div>
+        <br>
+        <br>
+        <br>
+        <br>
+        <br>
+    </div>
+
+    <!-- script references -->
+    <script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
+    <script src="{{ url_for('static', filename='js/bootstrap.min.js') }}"></script>
+    <script src="{{ url_for('static', filename='js/scripts.js') }}"></script>
+</body>
+
+</html>

Some files were not shown because too many files changed in this diff