From ab0801aed9ea45a50488390ec895df85e413c844 Mon Sep 17 00:00:00 2001 From: Karla Lopez Date: Thu, 4 Jun 2015 19:33:18 -0700 Subject: [PATCH 1/9] Update and search --- desserts.db | Bin 0 -> 12288 bytes models.py | 49 +++++++++++++++++++++++++++ templates/details.html | 4 +-- templates/edit.html | 71 +++++++++++++++++++++++++++++++++++++++ templates/index.html | 44 ++++++++++++++++-------- views.py | 74 ++++++++++++++++++++++++++++++++++++++++- 6 files changed, 225 insertions(+), 17 deletions(-) create mode 100644 desserts.db create mode 100644 templates/edit.html diff --git a/desserts.db b/desserts.db new file mode 100644 index 0000000000000000000000000000000000000000..7c05c81ced712738d3c459f43a02236d58da9748 GIT binary patch literal 12288 zcmeI%&r0J!90%~3v_TrsEUrb0h(AxJ;4T$kz_i3a7~9<#1&`BYb~}(7Nh5n)dfV67 zlMf<-FW@V9+ILuI#A*xfVK2fi-wBhM{4&Y!$0w&D$Dc!0O8Sx)Ls8N;d&f9uJ4B4J zhVB*JC(Y86>f}O?d}{uuX@h;Zx99a;YvDI@l|G?C00Izz00bZa0SG_<0uX=z1m0d? zV9hPp>wLUjihd@C^8C{DN+$~ZIH1^XhXI)gc}`8GbkL21y&$4)FQ)EE7;chNI~PMq zr+(Dg_akqs)oPmHr|96wkIv{YI3rJ`O{Y0t;&aO@D}4O@F;yx@BUzMBgEf=zDfqWJ zFA9}N+6{YtY)VK(mKREnCPlwqmf4$E+#BZpa_`(5_vqz#`;UQ)5P$##AOHafKmY;| zfB*y_0D*r+;KwTGd$|&QkqRf(RexLKJQ?Iko{3W0j*cu&N2+GcY^3U5vG?now+r=E zq*4{R=jlZsx28jsN=o!wZS(v>&1S2-Hpy$(Et_p{tDR@LS+{%Hzy4X}n~U6L>pJ}W kUW?tD{lEU{j|Kq 50: + raise Exception("A bit too pricey!") + + # Check for calories + if int(new_calories) > 1000: + raise Exception("No one should eat that") + + #Check duplicates + if Dessert.query.filter_by(name=new_name).first(): + raise Exception("Already in the database") + + # This line maps to line 16 above (the Dessert.__init__ method) dessert = Dessert(new_name, new_price, new_calories) @@ -61,6 +74,42 @@ def create_dessert(new_name, new_price, new_calories): db.session.rollback() +def edit_dessert(dessert, new_name, new_price, new_calories): + # Edit a dessert with the provided input. + + + # Can you think of other ways to write this following check? + if new_name is None or new_price is None or new_calories is None: + raise Exception("Need name, price and calories!") + + # They can also be empty strings if submitted from a form + if new_name == '' or new_price == '' or new_calories == '': + raise Exception("Need name, price and calories!") + + # Check for price + if int(new_price) > 50: + raise Exception("A bit too pricey!") + + # Check for calories + if int(new_calories) > 1000: + raise Exception("No one should eat that") + + # This line maps to line 16 above (the Dessert.__init__ method) + dessert.name = new_name + dessert.price = new_price + dessert.calories = new_calories + + # Save all pending changes to the database + + try: + db.session.commit() + return dessert + except: + # If something went wrong, explicitly roll back the database + db.session.rollback() + + + def delete_dessert(id): dessert = Dessert.query.get(id) diff --git a/templates/details.html b/templates/details.html index 23f0356..2a5d9aa 100644 --- a/templates/details.html +++ b/templates/details.html @@ -15,9 +15,9 @@

{{ dessert.name }}

Calories per dollar: {{ dessert.calories_per_dollar() }}

- Delete {{ dessert.name }} + Edit {{ dessert.name }} Delete {{ dessert.name }} - \ No newline at end of file + diff --git a/templates/edit.html b/templates/edit.html new file mode 100644 index 0000000..1583b43 --- /dev/null +++ b/templates/edit.html @@ -0,0 +1,71 @@ +{% include 'header.html' %} + + + +
+ + +

Edit Dessert

+ + {% if dessert %} + + + + + + {% endif %} + + {% if error %} + + {% endif %} + + + + + +
+ +
+ + + + +
+ +
+ + + + +
+ +
+ + + + +
+ + + + + + + +
+ + +
+ + diff --git a/templates/index.html b/templates/index.html index b6a05e5..4f4eb56 100644 --- a/templates/index.html +++ b/templates/index.html @@ -5,26 +5,42 @@
-

Dessert Menu

+

Dessert Menu

- {% if message %} - + {% endif %} + + +
+ +
+ + +
-
    - {% for dessert in desserts %} -
  • {{ dessert.name }} - ${{ dessert.price }}, {{ dessert.calories }} calories
  • - {% endfor %} -
+ + + +
+ +
    + {% for dessert in desserts %} +
  • {{ dessert.name }} - ${{ dessert.price }}, {{ dessert.calories }} calories
  • + {% endfor %} +
+ + Add Item - Add Item
- \ No newline at end of file + + + diff --git a/views.py b/views.py index 679621a..570d0d3 100644 --- a/views.py +++ b/views.py @@ -1,6 +1,6 @@ from flask import render_template, request -from models import Dessert, create_dessert, delete_dessert +from models import Dessert, create_dessert, delete_dessert, edit_dessert from app import app @@ -42,6 +42,41 @@ def add(): return render_template('add.html', error=e.message) +@app.route('/edit/', methods=['GET', 'POST']) +def edit(id): + + # We could define this inside its own function but it's simple enough + # that we don't really need to. + + dessert = Dessert.query.get(id) + + if request.method == 'GET': + return render_template('edit.html',dessert=dessert) + + # Because we 'returned' for a 'GET', if we get to this next bit, we must + # have received a POST + + # Get the incoming data from the request.form dictionary. + # The values on the right, inside get(), correspond to the 'name' + # values in the HTML form that was submitted. + + dessert_name = request.form.get('name_field') + dessert_price = request.form.get('price_field') + dessert_cals = request.form.get('cals_field') + + # Now we are checking the input in create_dessert, we need to handle + # the Exception that might happen here. + + # Wrap the thing we're trying to do in a 'try' block: + try: + dessert = edit_dessert(dessert, dessert_name, dessert_price, dessert_cals) + return render_template('edit.html', dessert=dessert) + except Exception as e: + # Oh no, something went wrong! + # We can access the error message via e.message: + return render_template('edit.html', dessert=dessert, error=e.message) + + @app.route('/desserts/') def view_dessert(id): @@ -58,3 +93,40 @@ def delete(id): message = delete_dessert(id) return index() # Look at the URL bar when you do this. What happens? + + +@app.route('/search', methods=['GET', 'POST']) +def search(): + + # We could define this inside its own function but it's simple enough + # that we don't really need to. + + if request.method == 'GET': + return render_template('search.html') + + # Because we 'returned' for a 'GET', if we get to this next bit, we must + # have received a POST + + term = request.form.get('term') + dessert = Dessert.query.filter_by(name=term) + + + # Get the incoming data from the request.form dictionary. + # The values on the right, inside get(), correspond to the 'name' + # values in the HTML form that was submitted. + + dessert_name = request.form.get('name_field') + dessert_price = request.form.get('price_field') + dessert_cals = request.form.get('cals_field') + + # Now we are checking the input in create_dessert, we need to handle + # the Exception that might happen here. + + # Wrap the thing we're trying to do in a 'try' block: + try: + dessert = edit_dessert(dessert, dessert_name, dessert_price, dessert_cals) + return render_template('edit.html', dessert=dessert) + except Exception as e: + # Oh no, something went wrong! + # We can access the error message via e.message: + return render_template('edit.html', dessert=dessert, error=e.message) From 5d92250a69f5d21c27086a15f7447fc6d826625e Mon Sep 17 00:00:00 2001 From: Karla Lopez Date: Thu, 4 Jun 2015 20:37:33 -0700 Subject: [PATCH 2/9] Seach --- templates/details.html | 24 +++++++++++++++++++----- views.py | 33 +++++++-------------------------- 2 files changed, 26 insertions(+), 31 deletions(-) diff --git a/templates/details.html b/templates/details.html index 2a5d9aa..9acdee5 100644 --- a/templates/details.html +++ b/templates/details.html @@ -6,16 +6,30 @@

Dessert Details

-

{{ dessert.name }}

+ {% if dessert %} -

Price: ${{ dessert.price }}

+

{{ dessert.name }}

-

Calories: {{ dessert.calories }}

+

Price: ${{ dessert.price }}

-

Calories per dollar: {{ dessert.calories_per_dollar() }}

+

Calories: {{ dessert.calories }}

+

Calories per dollar: {{ dessert.calories_per_dollar() }}

- Edit {{ dessert.name }} Delete {{ dessert.name }} + + Edit {{ dessert.name }} Delete {{ dessert.name }} + + {% endif %} + + {% if error %} + + {% endif %} diff --git a/views.py b/views.py index 570d0d3..2422984 100644 --- a/views.py +++ b/views.py @@ -95,38 +95,19 @@ def delete(id): return index() # Look at the URL bar when you do this. What happens? -@app.route('/search', methods=['GET', 'POST']) +@app.route('/search', methods=['POST']) def search(): - # We could define this inside its own function but it's simple enough - # that we don't really need to. - - if request.method == 'GET': - return render_template('search.html') - # Because we 'returned' for a 'GET', if we get to this next bit, we must # have received a POST term = request.form.get('term') - dessert = Dessert.query.filter_by(name=term) - + dessert = Dessert.query.filter_by(name=term).first() + print - # Get the incoming data from the request.form dictionary. - # The values on the right, inside get(), correspond to the 'name' - # values in the HTML form that was submitted. - - dessert_name = request.form.get('name_field') - dessert_price = request.form.get('price_field') - dessert_cals = request.form.get('cals_field') - - # Now we are checking the input in create_dessert, we need to handle - # the Exception that might happen here. - - # Wrap the thing we're trying to do in a 'try' block: - try: - dessert = edit_dessert(dessert, dessert_name, dessert_price, dessert_cals) - return render_template('edit.html', dessert=dessert) - except Exception as e: + if dessert: + return render_template('details.html', dessert=dessert) + else: # Oh no, something went wrong! # We can access the error message via e.message: - return render_template('edit.html', dessert=dessert, error=e.message) + return render_template('details.html', dessert=dessert, error="Nama does not exist") From 2a289298f094e9c4cbd1fa3065c038787452132a Mon Sep 17 00:00:00 2001 From: Karla Lopez Date: Fri, 5 Jun 2015 16:40:07 -0700 Subject: [PATCH 3/9] Search, Origin, ImageURL --- desserts.db | Bin 12288 -> 12288 bytes models.py | 14 ++++++++++---- templates/add.html | 16 +++++++++++++++- templates/details.html | 5 +++++ templates/edit.html | 18 +++++++++++++++++- views.py | 13 +++++++++---- 6 files changed, 56 insertions(+), 10 deletions(-) diff --git a/desserts.db b/desserts.db index 7c05c81ced712738d3c459f43a02236d58da9748..966293ef33fa5f7d4a3d62b83b2443c62784fca3 100644 GIT binary patch delta 312 zcmYMuPfEi;6vy#NG?)rzA}(A+aEge3&`csy#9dn~g1D*R()2YM&Ve1Lh z96;~};w4=57+yn@ZiKh_Z9d;O=}mesj%K`Wv{wyu_+zXfgmi0$@QF41e7LcSUu#f1 z)0Wm9M|*}s;YT7Qk9kI}o89(#v%Bki-rfOOuJIIN7K~(4bnw=jy=dyVf$%$SeAVrJ z{1odZ+Sc@)=~@dCAQ2;>2*m>WzJiQ&BxE61p|~3kb9G8-EI9Nbf{3LcQ6oZO$@AEj&OjOtO%_(k`kCp`6i#^%jOheWEYo~W^AmV z?8IL^`5nKQ7&HG-2L3nvSNV_f`y$|GK?O7Z`VLt}M)&;8#H7TOM6MK|f#vdyjL8}K z$@w{nC8?}jKoKEi5f+ddR1p^bXf-PnhWnyJeXJm59&&dZVbSq6dypV-aM~IP?K@lhnH<*dx#3BU& E04n4{y#N3J diff --git a/models.py b/models.py index 60f287d..1b33916 100644 --- a/models.py +++ b/models.py @@ -12,11 +12,15 @@ class Dessert(db.Model): name = db.Column(db.String(100)) price = db.Column(db.Float) calories = db.Column(db.Integer) + origin = db.Column(db.String(100)) + image_url = db.Column(db.String(100)) - def __init__(self, name, price, calories): + def __init__(self, name, price, calories, origin,image_url): self.name = name self.price = price self.calories = calories + self.origin = origin + self.image_url = image_url def calories_per_dollar(self): if self.calories: @@ -32,7 +36,7 @@ def __init__(self, name): self.name = name -def create_dessert(new_name, new_price, new_calories): +def create_dessert(new_name, new_price, new_calories, new_origin, new_image_url): # Create a dessert with the provided input. # We need every piece of input to be provided. @@ -59,7 +63,7 @@ def create_dessert(new_name, new_price, new_calories): # This line maps to line 16 above (the Dessert.__init__ method) - dessert = Dessert(new_name, new_price, new_calories) + dessert = Dessert(new_name, new_price, new_calories, new_origin, new_image_url) # Actually add this dessert to the database db.session.add(dessert) @@ -74,7 +78,7 @@ def create_dessert(new_name, new_price, new_calories): db.session.rollback() -def edit_dessert(dessert, new_name, new_price, new_calories): +def edit_dessert(dessert, new_name, new_price, new_calories, new_origin, new_image_url): # Edit a dessert with the provided input. @@ -98,6 +102,8 @@ def edit_dessert(dessert, new_name, new_price, new_calories): dessert.name = new_name dessert.price = new_price dessert.calories = new_calories + dessert.origin = new_origin + dessert.image_url = new_image_url # Save all pending changes to the database diff --git a/templates/add.html b/templates/add.html index d3ad60c..109e6e7 100644 --- a/templates/add.html +++ b/templates/add.html @@ -57,6 +57,20 @@

Add Dessert

+
+ + + + +
+ +
+ + + + +
+ @@ -68,4 +82,4 @@

Add Dessert

- \ No newline at end of file + diff --git a/templates/details.html b/templates/details.html index 9acdee5..c9b0d80 100644 --- a/templates/details.html +++ b/templates/details.html @@ -16,6 +16,10 @@

{{ dessert.name }}

Calories per dollar: {{ dessert.calories_per_dollar() }}

+

Origin: {{ dessert.origin }}

+ +

Image:

+

Edit {{ dessert.name }} Delete {{ dessert.name }} @@ -31,6 +35,7 @@

{{ dessert.name }}

{% endif %} + Back diff --git a/templates/edit.html b/templates/edit.html index 1583b43..734fe61 100644 --- a/templates/edit.html +++ b/templates/edit.html @@ -57,14 +57,30 @@

Edit Dessert

+
+ + + + +
+ +
+ + + + +
+ - + +

+ Back diff --git a/views.py b/views.py index 2422984..bfef446 100644 --- a/views.py +++ b/views.py @@ -28,13 +28,15 @@ def add(): dessert_name = request.form.get('name_field') dessert_price = request.form.get('price_field') dessert_cals = request.form.get('cals_field') + dessert_origin = request.form.get('origin_field') + dessert_image_url = request.form.get('image_url_field') # Now we are checking the input in create_dessert, we need to handle # the Exception that might happen here. # Wrap the thing we're trying to do in a 'try' block: try: - dessert = create_dessert(dessert_name, dessert_price, dessert_cals) + dessert = create_dessert(dessert_name, dessert_price, dessert_cals, dessert_origin, dessert_image_url) return render_template('add.html', dessert=dessert) except Exception as e: # Oh no, something went wrong! @@ -50,8 +52,9 @@ def edit(id): dessert = Dessert.query.get(id) + if request.method == 'GET': - return render_template('edit.html',dessert=dessert) + return render_template('edit.html',dessert=dessert, error="The dessert ID do not exist.") # Because we 'returned' for a 'GET', if we get to this next bit, we must # have received a POST @@ -63,13 +66,15 @@ def edit(id): dessert_name = request.form.get('name_field') dessert_price = request.form.get('price_field') dessert_cals = request.form.get('cals_field') + dessert_origin = request.form.get('origin_field') + dessert_image_url = request.form.get('image_url_field') # Now we are checking the input in create_dessert, we need to handle # the Exception that might happen here. # Wrap the thing we're trying to do in a 'try' block: try: - dessert = edit_dessert(dessert, dessert_name, dessert_price, dessert_cals) + dessert = edit_dessert(dessert, dessert_name, dessert_price, dessert_cals, dessert_origin, dessert_image_url) return render_template('edit.html', dessert=dessert) except Exception as e: # Oh no, something went wrong! @@ -110,4 +115,4 @@ def search(): else: # Oh no, something went wrong! # We can access the error message via e.message: - return render_template('details.html', dessert=dessert, error="Nama does not exist") + return render_template('details.html', dessert=dessert, error="Name does not exist") From aa45c2d1f24244ff14eaa25d3b30734da9676437 Mon Sep 17 00:00:00 2001 From: Karla Lopez Date: Fri, 5 Jun 2015 17:17:35 -0700 Subject: [PATCH 4/9] origin, image url, ordering fields. assignment complete --- templates/edit.html | 57 ++++++++++++++++++++++---------------------- templates/index.html | 21 ++++++++++++---- views.py | 15 +++++++++++- 3 files changed, 59 insertions(+), 34 deletions(-) diff --git a/templates/edit.html b/templates/edit.html index 734fe61..cf27576 100644 --- a/templates/edit.html +++ b/templates/edit.html @@ -30,55 +30,56 @@

Edit Dessert

{% endif %} + {% if error != "The dessert ID do not exist." %} + - + +
- - +
-
+ + - - +
-
- -
+
- - + + -
+
-
+
- - + + -
+
-
+
- - + + -
+
-
+
- - + + -
+
- - + + -
-

+ +

+ {% endif %} Back diff --git a/templates/index.html b/templates/index.html index 4f4eb56..bbbf93f 100644 --- a/templates/index.html +++ b/templates/index.html @@ -29,11 +29,22 @@

Dessert Menu

-
    - {% for dessert in desserts %} -
  • {{ dessert.name }} - ${{ dessert.price }}, {{ dessert.calories }} calories
  • - {% endfor %} -
+ + + + + + + + {% for dessert in desserts %} + + + + + + + {% endfor %} +
Name Price Calories Image
{{dessert.name}}$ {{dessert.price}}{{dessert.calories}}
Add Item diff --git a/views.py b/views.py index bfef446..5929b00 100644 --- a/views.py +++ b/views.py @@ -54,7 +54,10 @@ def edit(id): if request.method == 'GET': - return render_template('edit.html',dessert=dessert, error="The dessert ID do not exist.") + if dessert is None: + return render_template('edit.html',dessert=dessert, error="The dessert ID do not exist.") + else: + return render_template('edit.html',dessert=dessert) # Because we 'returned' for a 'GET', if we get to this next bit, we must # have received a POST @@ -116,3 +119,13 @@ def search(): # Oh no, something went wrong! # We can access the error message via e.message: return render_template('details.html', dessert=dessert, error="Name does not exist") + +@app.route('/order/') +def order(field): + + if field == "name" or field == "price" or field == "calories": + desserts = Dessert.query.order_by(field) + return render_template('index.html', desserts=desserts) + else: + desserts = Dessert.query.all() + return render_template('index.html', desserts=desserts) From 942ec51b8bd5036cdf32bc80d287f103c13eee4d Mon Sep 17 00:00:00 2001 From: Karla Lopez Date: Mon, 8 Jun 2015 16:16:48 -0700 Subject: [PATCH 5/9] Dealing with merge conflicts - relationships branch --- desserts.db | Bin 12288 -> 16384 bytes models.py | 2 -- 2 files changed, 2 deletions(-) diff --git a/desserts.db b/desserts.db index 966293ef33fa5f7d4a3d62b83b2443c62784fca3..8c452392a42dece2612d045712e0ab06bf80ee45 100644 GIT binary patch delta 185 zcmZojXlP)ZAT7woz`(!)#4x}-QO8)AjY0PrD=$!pnU95m--7QPAIrwVNxYhk?#%4s zqN0pVg(ZneIjN<^sYM{n;vD4a7~-lB;^^e#ssIw1oW(EA0%i#Ei)t4n78jT27o{kK zIR-g Date: Mon, 8 Jun 2015 16:42:35 -0700 Subject: [PATCH 6/9] Converting the users from week 4 into SQLAlchemy objects --- app.py | 4 +-- desserts.db | Bin 16384 -> 16384 bytes test_users.py | 80 ++++++++++++++++++++++++++++++++++++++++++++++++++ users.py | 68 ++++++++++++++++++++++++++++++++++++++++++ 4 files changed, 150 insertions(+), 2 deletions(-) create mode 100644 test_users.py create mode 100644 users.py diff --git a/app.py b/app.py index 4347b45..ead058a 100644 --- a/app.py +++ b/app.py @@ -3,8 +3,8 @@ app = Flask(__name__) -# Set up the SQLAlchemy Database to be a local file 'desserts.db' -app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///desserts.db' +# Set up the SQLAlchemy Database to be a local file 'users.db' +app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///users.db' db = SQLAlchemy(app) diff --git a/desserts.db b/desserts.db index 8c452392a42dece2612d045712e0ab06bf80ee45..7c69d21c5091cce263830dfbf864e10f2d756ab9 100644 GIT binary patch delta 309 zcmZo@U~Fh$oRG}V!OOtFz|4Duf!~bp4DXSRjX}JeO{~o9;?mNL&66GZMHpEohw;zw zE-g+iiqA|@@bn9Db$1QYQQ+bX2=erG42o3nc8yff$V|}$iMja)xq7<$fy6YRS~L}c zT-{uQT>YF~gB3txlaKQiiMunhi;IdfHWij6Cgr4pgh7~TvJBs*NdhcvjQmR&_?K)J zRG7sd6UE5RATDVtnVFqfl#{3cC3Euia`FpOs~pmE6Ek!4lJj#RG8rW$1;tkS`njno znTdKinaL@6AW8k)f+8?3&M3;v%g!r^H!(1XH`%1XA^@~(9s~b8pk-6|B@!4p859|r aUv8NO^;S4MVmX=%o$M6i5HYB5l@1WGYYe#ARtvI@V@Bmou(iMy7*rXV)EkAJ5_1w2Qc@L?^ON(L8BPQz<|()pCFUh(7ANOtl#~<{Tj}ek z=VvA+C8i{%q~<0T<)-H3>!oGpq!#Oy=NF|E6anqjOU}>LH!?6Z)CZy@po#Gy 0 + + +@check_test +def test_update_user(): + result = update_user(1, password='newpass') + assert result is not None + assert isinstance(result, User) + assert result.password == 'newpass' + + +for item in dir(): + """ Loop through all the defined items we know about (functions, etc). + If the name starts with test_, assume it's a test function and run it! + """ + if item.startswith('test_'): + globals()[item]() diff --git a/users.py b/users.py new file mode 100644 index 0000000..2b48f9b --- /dev/null +++ b/users.py @@ -0,0 +1,68 @@ +from app import db + + +class User(db.Model): + + id = db.Column(db.Integer, primary_key=True) + + username = db.Column(db.String(100)) + password = db.Column(db.String(100)) + email = db.Column(db.String(250)) + realname = db.Column(db.String(100)) + avatar = db.Column(db.String(250)) + + def __init__(self, username, password, email, realname, avatar): + self.username = username + self.password = password + self.email = email + self.realname = realname + self.avatar = avatar + + +def list_users(): + return User.query.all() + + +def get_user(id): + return User.query.get(id) + + +def get_user_by_username(username): + return User.query.filter_by(username=username).first() + + +def create_user(username, email, password, realname, avatar): + user = User(username, email, password, realname, avatar) + db.session.add(user) + db.session.commit() + return user + + +def update_user(id, username=None, email=None, password=None, realname=None, + avatar=None): + # This one is harder with the object syntax actually! So we changed the + # function definition. + + user = User.query.get(id) + + if username: + user.username = username + + if email: + user.email = email + + if password: + user.password = password + + if realname: + user.realname = realname + + if avatar: + user.avatar = avatar + + db.session.commit() + return user + + +if __name__ == "__main__": + db.create_all() From 5ab799fbac865905ebe1845d115d3810b57d62a6 Mon Sep 17 00:00:00 2001 From: Karla Lopez Date: Tue, 9 Jun 2015 21:27:18 -0700 Subject: [PATCH 7/9] Added session, login and signup --- app.py | 2 + models.py | 28 ++--- templates/index.html | 3 +- templates/login.html | 45 +++++++ templates/signup.html | 69 ++++++++++ users.db | Bin 0 -> 16384 bytes users.py | 9 +- views.py | 283 ++++++++++++++++++++++++++++++------------ 8 files changed, 339 insertions(+), 100 deletions(-) create mode 100644 templates/login.html create mode 100644 templates/signup.html create mode 100644 users.db diff --git a/app.py b/app.py index ead058a..a1190e6 100644 --- a/app.py +++ b/app.py @@ -2,6 +2,8 @@ from flask.ext.sqlalchemy import SQLAlchemy app = Flask(__name__) +app.secret_key = 'thisisasecret' #To "log in" a user, first make sure you have imported the session - you'll also need to set up an app secret key. + # Set up the SQLAlchemy Database to be a local file 'users.db' app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///users.db' diff --git a/models.py b/models.py index 2d3f195..62bc279 100644 --- a/models.py +++ b/models.py @@ -38,20 +38,20 @@ def __init__(self, name): self.name = name -class User(db.Model): - id = db.Column(db.Integer, primary_key=True) - username = db.Column(db.String(100)) - password = db.Column(db.String(100)) - email = db.Column(db.String(250)) - name = db.Column(db.String(100)) - avatar = db.Column(db.String(250)) - - def __init__(self, username, password, email, name, avatar): - self.username = username - self.password = password - self.email = email - self.name = name - self.avatar = avatar +# class User(db.Model): +# id = db.Column(db.Integer, primary_key=True) +# username = db.Column(db.String(100)) +# password = db.Column(db.String(100)) +# email = db.Column(db.String(250)) +# name = db.Column(db.String(100)) +# avatar = db.Column(db.String(250)) +# +# def __init__(self, username, password, email, name, avatar): +# self.username = username +# self.password = password +# self.email = email +# self.name = name +# self.avatar = avatar diff --git a/templates/index.html b/templates/index.html index bbbf93f..28d41e5 100644 --- a/templates/index.html +++ b/templates/index.html @@ -46,7 +46,8 @@

Dessert Menu

{% endfor %} - Add Item +

Add Item

+

Logout

diff --git a/templates/login.html b/templates/login.html new file mode 100644 index 0000000..0df11ca --- /dev/null +++ b/templates/login.html @@ -0,0 +1,45 @@ +{% include 'header.html' %} + + + +
+ +

Login

+ + {% if error %} + + {% endif %} + + + + + + +
+ +
+ + + + +
+ +
+ + +
+
+ +
+ + + +
+ + diff --git a/templates/signup.html b/templates/signup.html new file mode 100644 index 0000000..668f76e --- /dev/null +++ b/templates/signup.html @@ -0,0 +1,69 @@ +{% include 'header.html' %} + + + +
+ +

Sign up

+ + {% if error %} + + {% endif %} + + + + + + +
+ +
+ + + + +
+ +
+ + + + +
+ +
+ + + + +
+ +
+ + + + +
+ +
+ + + + +
+ + + + + + + +
+ + diff --git a/users.db b/users.db new file mode 100644 index 0000000000000000000000000000000000000000..0f6516063a2a37a066fd30023bf3b20165567d4b GIT binary patch literal 16384 zcmeI%&riZI6bJCmVTeSS$=Q%MRy1YKmY;|fB*y_009U<00I#Br@(OD&KB0ztS8x%mu=Nj zajc?V+GWauJ3c4hIdD0pNh;?0pI5mcukMp~?z-!gTj@LJU~xng=ti3G23!M!p+Ba=%8=SsJ8*~03oHP}fQLe=S;W`6=OnZNG- zYgxI{plT&c4eyhsObw>ZeOhW%*^kiX^7q&>jvu>GYf4OoGMG4S?~b0$w{yq`{ac7W zW*Cp1-ibMzTlqJpUkC_500Izz00bZa0SG_<0uX=z1ZGBH(aN&CiP(fW|LZ^f5fFd? y1Rwwb2tWV=5P$##AOHaf%&-8?|1u{8)l00Izz00bZa0SG_<0uX>eD)0^_W2ox@ literal 0 HcmV?d00001 diff --git a/users.py b/users.py index 2b48f9b..015cce7 100644 --- a/users.py +++ b/users.py @@ -8,14 +8,14 @@ class User(db.Model): username = db.Column(db.String(100)) password = db.Column(db.String(100)) email = db.Column(db.String(250)) - realname = db.Column(db.String(100)) + name = db.Column(db.String(100)) avatar = db.Column(db.String(250)) - def __init__(self, username, password, email, realname, avatar): + def __init__(self, username, password, email, name, avatar): self.username = username self.password = password self.email = email - self.realname = realname + self.name = name self.avatar = avatar @@ -30,6 +30,9 @@ def get_user(id): def get_user_by_username(username): return User.query.filter_by(username=username).first() +def get_user_by_email(email): + return User.query.filter_by(email=email).first() + def create_user(username, email, password, realname, avatar): user = User(username, email, password, realname, avatar) diff --git a/views.py b/views.py index 5929b00..96a01bc 100644 --- a/views.py +++ b/views.py @@ -1,131 +1,250 @@ -from flask import render_template, request +from flask import render_template, request, redirect, session from models import Dessert, create_dessert, delete_dessert, edit_dessert +from users import * from app import app @app.route('/') def index(): + if session.get('username'): # this will be executed if 'username' is present in the session + print "Logged-in: Found session" + username = session['username'] + desserts = Dessert.query.all() + return render_template('index.html', desserts=desserts) + else: + print "Logged-in: No session" + return render_template('login.html', error="Please login.") + + +@app.route('/login') +def login(): + return render_template('login.html') + +@app.route('/submit-login', methods=['POST']) +def submit_login(): + #get form info + user_username = request.form.get('username_field') + user_password = request.form.get('password_field') + + print user_username + + # check for username + user_login = get_user_by_username(user_username) + if user_login: + # check for password + print "username is ok" + print user_login.password + print user_password + if user_login.password == user_password: + print "password is ok" + session['username'] = user_username + return redirect('/') + else: + print "password does not match" + return render_template('login.html', error="Login credentials don't not work") + else: + print "password does not match" + return render_template('login.html', error="Login credentials don't not work") - desserts = Dessert.query.all() - return render_template('index.html', desserts=desserts) +@app.route('/signup') +def signup_(): + return render_template('signup.html') +@app.route('/submit-signup', methods=['POST']) +def submit_signup(): + #get form info + user_username = request.form.get('username_field') + user_password = request.form.get('password_field') + user_email = request.form.get('email_field') + user_name = request.form.get('name_field') + user_avatar = request.form.get('avatar_field') -@app.route('/add', methods=['GET', 'POST']) -def add(): + print user_username - if request.method == 'GET': - return render_template('add.html') + # check for duplicated username + if get_user_by_username(user_username): + return render_template('signup.html',error="Username already exists") - # Because we 'returned' for a 'GET', if we get to this next bit, we must - # have received a POST + # check for duplicated email + elif get_user_by_email(user_email): + return render_template('signup.html',error="Email already exists") - # Get the incoming data from the request.form dictionary. - # The values on the right, inside get(), correspond to the 'name' - # values in the HTML form that was submitted. + # if no duplicates, create user + else: + try: + user = create_user(user_username, user_email, user_password, user_name, user_avatar) + session['username'] = user_username + return redirect('/') + except Exception as e: + # Oh no, something went wrong! + # We can access the error message via e.message: + return render_template('signup.html', error=e.message) - dessert_name = request.form.get('name_field') - dessert_price = request.form.get('price_field') - dessert_cals = request.form.get('cals_field') - dessert_origin = request.form.get('origin_field') - dessert_image_url = request.form.get('image_url_field') - # Now we are checking the input in create_dessert, we need to handle - # the Exception that might happen here. +@app.route('/add', methods=['GET', 'POST']) +def add(): + if session.get('username'): # this will be executed if 'username' is present in the session + print "Logged-in: Found session" + username = session['username'] + + if request.method == 'GET': + return render_template('add.html',error="e.message") + + # Because we 'returned' for a 'GET', if we get to this next bit, we must + # have received a POST + + # Get the incoming data from the request.form dictionary. + # The values on the right, inside get(), correspond to the 'name' + # values in the HTML form that was submitted. + + dessert_name = request.form.get('name_field') + dessert_price = request.form.get('price_field') + dessert_cals = request.form.get('cals_field') + dessert_origin = request.form.get('origin_field') + dessert_image_url = request.form.get('image_url_field') + + # Now we are checking the input in create_dessert, we need to handle + # the Exception that might happen here. + + # Wrap the thing we're trying to do in a 'try' block: + try: + dessert = create_dessert(dessert_name, dessert_price, dessert_cals, dessert_origin, dessert_image_url) + return render_template('add.html', dessert=dessert) + except Exception as e: + # Oh no, something went wrong! + # We can access the error message via e.message: + return render_template('add.html', error=e.message) + + else: + print "Logged-in: No session" + return render_template('login.html', error="Please login.") - # Wrap the thing we're trying to do in a 'try' block: - try: - dessert = create_dessert(dessert_name, dessert_price, dessert_cals, dessert_origin, dessert_image_url) - return render_template('add.html', dessert=dessert) - except Exception as e: - # Oh no, something went wrong! - # We can access the error message via e.message: - return render_template('add.html', error=e.message) @app.route('/edit/', methods=['GET', 'POST']) def edit(id): + if session.get('username'): # this will be executed if 'username' is present in the session + print "Logged-in: Found session" + username = session['username'] + + # We could define this inside its own function but it's simple enough + # that we don't really need to. + + dessert = Dessert.query.get(id) + + + if request.method == 'GET': + if dessert is None: + return render_template('edit.html',dessert=dessert, error="The dessert ID do not exist.") + else: + return render_template('edit.html',dessert=dessert) + + # Because we 'returned' for a 'GET', if we get to this next bit, we must + # have received a POST + + # Get the incoming data from the request.form dictionary. + # The values on the right, inside get(), correspond to the 'name' + # values in the HTML form that was submitted. + + dessert_name = request.form.get('name_field') + dessert_price = request.form.get('price_field') + dessert_cals = request.form.get('cals_field') + dessert_origin = request.form.get('origin_field') + dessert_image_url = request.form.get('image_url_field') + + # Now we are checking the input in create_dessert, we need to handle + # the Exception that might happen here. + + # Wrap the thing we're trying to do in a 'try' block: + try: + dessert = edit_dessert(dessert, dessert_name, dessert_price, dessert_cals, dessert_origin, dessert_image_url) + return render_template('edit.html', dessert=dessert) + except Exception as e: + # Oh no, something went wrong! + # We can access the error message via e.message: + return render_template('edit.html', dessert=dessert, error=e.message) + else: + print "Logged-in: No session" + return render_template('login.html', error="Please login.") - # We could define this inside its own function but it's simple enough - # that we don't really need to. - - dessert = Dessert.query.get(id) - - - if request.method == 'GET': - if dessert is None: - return render_template('edit.html',dessert=dessert, error="The dessert ID do not exist.") - else: - return render_template('edit.html',dessert=dessert) - - # Because we 'returned' for a 'GET', if we get to this next bit, we must - # have received a POST - - # Get the incoming data from the request.form dictionary. - # The values on the right, inside get(), correspond to the 'name' - # values in the HTML form that was submitted. - - dessert_name = request.form.get('name_field') - dessert_price = request.form.get('price_field') - dessert_cals = request.form.get('cals_field') - dessert_origin = request.form.get('origin_field') - dessert_image_url = request.form.get('image_url_field') - - # Now we are checking the input in create_dessert, we need to handle - # the Exception that might happen here. - - # Wrap the thing we're trying to do in a 'try' block: - try: - dessert = edit_dessert(dessert, dessert_name, dessert_price, dessert_cals, dessert_origin, dessert_image_url) - return render_template('edit.html', dessert=dessert) - except Exception as e: - # Oh no, something went wrong! - # We can access the error message via e.message: - return render_template('edit.html', dessert=dessert, error=e.message) @app.route('/desserts/') def view_dessert(id): + if session.get('username'): # this will be executed if 'username' is present in the session + print "Logged-in: Found session" + username = session['username'] # We could define this inside its own function but it's simple enough # that we don't really need to. - dessert = Dessert.query.get(id) + dessert = Dessert.query.get(id) - return render_template('details.html', dessert=dessert) + return render_template('details.html', dessert=dessert) + else: + print "Logged-in: No session" + return render_template('login.html', error="Please login.") @app.route('/delete/') def delete(id): + if session.get('username'): # this will be executed if 'username' is present in the session + print "Logged-in: Found session" + username = session['username'] - message = delete_dessert(id) + message = delete_dessert(id) - return index() # Look at the URL bar when you do this. What happens? + return index() # Look at the URL bar when you do this. What happens? + + else: + print "Logged-in: No session" + return render_template('login.html', error="Please login.") @app.route('/search', methods=['POST']) def search(): + if session.get('username'): # this will be executed if 'username' is present in the session + print "Logged-in: Found session" + username = session['username'] - # Because we 'returned' for a 'GET', if we get to this next bit, we must - # have received a POST + # Because we 'returned' for a 'GET', if we get to this next bit, we must + # have received a POST - term = request.form.get('term') - dessert = Dessert.query.filter_by(name=term).first() - print + term = request.form.get('term') + dessert = Dessert.query.filter_by(name=term).first() + print - if dessert: - return render_template('details.html', dessert=dessert) + if dessert: + return render_template('details.html', dessert=dessert) + else: + # Oh no, something went wrong! + # We can access the error message via e.message: + return render_template('details.html', dessert=dessert, error="Name does not exist") else: - # Oh no, something went wrong! - # We can access the error message via e.message: - return render_template('details.html', dessert=dessert, error="Name does not exist") + print "Logged-in: No session" + return render_template('login.html', error="Please login.") @app.route('/order/') def order(field): + if session.get('username'): # this will be executed if 'username' is present in the session + print "Logged-in: Found session" + username = session['username'] - if field == "name" or field == "price" or field == "calories": - desserts = Dessert.query.order_by(field) - return render_template('index.html', desserts=desserts) + if field == "name" or field == "price" or field == "calories": + desserts = Dessert.query.order_by(field) + return render_template('index.html', desserts=desserts) + else: + desserts = Dessert.query.all() + return render_template('index.html', desserts=desserts) else: - desserts = Dessert.query.all() - return render_template('index.html', desserts=desserts) + print "Logged-in: No session" + return render_template('login.html', error="Please login.") + +@app.route('/logout') +def logout_user(): + if session.get('username'): # this will be executed if 'username' is present in the session + username = session['username'] + print "Logout: Deleting settion" + del session['username'] + return redirect("/") From b857108fdb0ba55939f6538e589cc972fff7f1b8 Mon Sep 17 00:00:00 2001 From: Karla Lopez Date: Thu, 11 Jun 2015 14:23:56 -0700 Subject: [PATCH 8/9] Assignment Connecting Models Week 6 --- models.py | 58 ++++++++++++++++++----------- static/starter-template.css | 10 +++++ templates/add.html | 3 +- templates/details.html | 2 +- templates/edit.html | 25 ++++++------- templates/header.html | 51 ++++++++++++++++++++++++- templates/index.html | 20 +--------- templates/login.html | 49 ++++++++++++------------ templates/signup.html | 72 ++++++++++++++++++------------------ users.db | Bin 16384 -> 16384 bytes views.py | 63 +++++++++++++++++++++---------- 11 files changed, 216 insertions(+), 137 deletions(-) create mode 100755 static/starter-template.css diff --git a/models.py b/models.py index 62bc279..cca8f28 100644 --- a/models.py +++ b/models.py @@ -1,4 +1,5 @@ from app import db +from users import get_user_by_username class Dessert(db.Model): @@ -14,16 +15,16 @@ class Dessert(db.Model): calories = db.Column(db.Integer) origin = db.Column(db.String(100)) image_url = db.Column(db.String(100)) - user_id = db.Column(db.Integer, db.ForeignKey('user.id')) user = db.relationship("User", backref="desserts") - def __init__(self, name, price, calories, origin,image_url): + def __init__(self, name, price, calories, origin,image_url,user_id): self.name = name self.price = price self.calories = calories self.origin = origin self.image_url = image_url + self.user_id = user_id def calories_per_dollar(self): if self.calories: @@ -53,9 +54,16 @@ def __init__(self, name): # self.name = name # self.avatar = avatar +def get_desserts(user_id): + desserts = Dessert.query.filter_by(user_id=user_id).all() + return desserts +def get_user_id(username): + user = get_user_by_username(username) + user_id = user.id + return user_id -def create_dessert(new_name, new_price, new_calories, new_origin, new_image_url): +def create_dessert(new_name, new_price, new_calories, new_origin, new_image_url,new_user_id): # Create a dessert with the provided input. # We need every piece of input to be provided. @@ -82,7 +90,8 @@ def create_dessert(new_name, new_price, new_calories, new_origin, new_image_url) # This line maps to line 16 above (the Dessert.__init__ method) - dessert = Dessert(new_name, new_price, new_calories, new_origin, new_image_url) + + dessert = Dessert(new_name, new_price, new_calories, new_origin, new_image_url,new_user_id) # Actually add this dessert to the database db.session.add(dessert) @@ -133,27 +142,32 @@ def edit_dessert(dessert, new_name, new_price, new_calories, new_origin, new_ima # If something went wrong, explicitly roll back the database db.session.rollback() - - -def delete_dessert(id): +def delete_dessert(id,user_id): dessert = Dessert.query.get(id) - - if dessert: - # We store the name before deleting it, because we can't access it - # afterwards. - dessert_name = dessert.name - db.session.delete(dessert) - - try: - db.session.commit() - return "Dessert {} deleted".format(dessert_name) - except: - # If something went wrong, explicitly roll back the database - db.session.rollback() - return "Something went wrong" + print dessert.user_id + print user_id + if dessert.user_id == user_id: + + if dessert: + # We store the name before deleting it, because we can't access it + # afterwards. + dessert_name = dessert.name + db.session.delete(dessert) + + try: + db.session.commit() + return "Dessert {} deleted".format(dessert_name) + except: + # If something went wrong, explicitly roll back the database + db.session.rollback() + return "Something went wrong" + else: + return "Dessert not found" else: - return "Dessert not found" + return "You can't delete this dessert" + + if __name__ == "__main__": diff --git a/static/starter-template.css b/static/starter-template.css new file mode 100755 index 0000000..eab5c58 --- /dev/null +++ b/static/starter-template.css @@ -0,0 +1,10 @@ +body { + padding-top: 50px; +} +.starter-template { + padding: 40px 15px; + text-align: center; +} +.search { + align-items: baseline; +} diff --git a/templates/add.html b/templates/add.html index 109e6e7..e9781d8 100644 --- a/templates/add.html +++ b/templates/add.html @@ -1,6 +1,5 @@ {% include 'header.html' %} -
@@ -76,6 +75,8 @@

Add Dessert

+ Back + diff --git a/templates/details.html b/templates/details.html index c9b0d80..cc4d219 100644 --- a/templates/details.html +++ b/templates/details.html @@ -1,6 +1,6 @@ {% include 'header.html' %} - +
diff --git a/templates/edit.html b/templates/edit.html index cf27576..db6683a 100644 --- a/templates/edit.html +++ b/templates/edit.html @@ -1,36 +1,35 @@ {% include 'header.html' %} -

Edit Dessert

- {% if dessert %} + {% if success %} - + - {% endif %} {% if error %} - {% endif %} - {% if error != "The dessert ID do not exist." %} + {% if dessert %} @@ -79,7 +78,7 @@

Edit Dessert

- {% endif %} + {% endif %} Back diff --git a/templates/header.html b/templates/header.html index afbc019..11287ee 100644 --- a/templates/header.html +++ b/templates/header.html @@ -1,6 +1,6 @@ - Desserts + Desserts for you! @@ -13,6 +13,55 @@ + + + + + + + + + + +
+ + diff --git a/templates/index.html b/templates/index.html index 28d41e5..2ef6076 100644 --- a/templates/index.html +++ b/templates/index.html @@ -1,34 +1,19 @@ {% include 'header.html' %} -

Dessert Menu

- {% if message %} + {% if error %} {% endif %} - -
- -
- - - -
- - - - -
- @@ -47,7 +32,6 @@

Dessert Menu

Name

Add Item

-

Logout

diff --git a/templates/login.html b/templates/login.html index 0df11ca..a28bd4e 100644 --- a/templates/login.html +++ b/templates/login.html @@ -1,45 +1,44 @@ {% include 'header.html' %} -
-

Login

+

Login

- {% if error %} - + {% endif %} - + - + -
+ -
+
- - + + -
+
-
- - -
-
- +
+ + +
+
+ +
+ + + Or Sign up.
- - - - diff --git a/templates/signup.html b/templates/signup.html index 668f76e..61e9ec2 100644 --- a/templates/signup.html +++ b/templates/signup.html @@ -1,69 +1,67 @@ {% include 'header.html' %} -
-

Sign up

+

Sign up

- {% if error %} - + {% endif %} - + - + -
+ -
+
- - + + -
+
-
+
- - + + -
+
-
+
- - + + -
+
-
+
- - + + -
+
-
+
- - + + -
+
+ + - - - - - -
+ + Or Login. +
diff --git a/users.db b/users.db index 0f6516063a2a37a066fd30023bf3b20165567d4b..cbba394e6ed934891fe7ee0c62d081ed1274eeaa 100644 GIT binary patch delta 514 zcmZvYv2GeM7=Z5}6}^a@({^A;s*oY7y4X3OsxDJSq%c)gm8nzvpU)f)zVp>KP*{LB zNTn!GkS$ZhlqX1^hbO2_qz>jOXheR%GN4?phEZWTRxXpNrG zL z5DuThu?6sf0lEKwE@F7>v4_*3My@q jvlN=N4T)!jw(KRI(N-sej;2b*@t&S0ACqYKA#$?6eea{q delta 41 xcmZo@U~Fh$oFL7}GEv5vk!54T5`H#D{!a}2pEe6Byx`ybNnS``GmF9>egFe04Hy6b diff --git a/views.py b/views.py index 96a01bc..c1fddb7 100644 --- a/views.py +++ b/views.py @@ -1,6 +1,6 @@ from flask import render_template, request, redirect, session -from models import Dessert, create_dessert, delete_dessert, edit_dessert +from models import * from users import * from app import app @@ -10,8 +10,12 @@ def index(): if session.get('username'): # this will be executed if 'username' is present in the session print "Logged-in: Found session" username = session['username'] - desserts = Dessert.query.all() - return render_template('index.html', desserts=desserts) + + user_id = get_user_id(username) + + desserts = get_desserts(user_id) + + return render_template('index.html', desserts=desserts, username=username) else: print "Logged-in: No session" return render_template('login.html', error="Please login.") @@ -90,7 +94,7 @@ def add(): username = session['username'] if request.method == 'GET': - return render_template('add.html',error="e.message") + return render_template('add.html') # Because we 'returned' for a 'GET', if we get to this next bit, we must # have received a POST @@ -105,17 +109,19 @@ def add(): dessert_origin = request.form.get('origin_field') dessert_image_url = request.form.get('image_url_field') + user_id = get_user_id(username) + # Now we are checking the input in create_dessert, we need to handle # the Exception that might happen here. # Wrap the thing we're trying to do in a 'try' block: try: - dessert = create_dessert(dessert_name, dessert_price, dessert_cals, dessert_origin, dessert_image_url) - return render_template('add.html', dessert=dessert) + dessert = create_dessert(dessert_name, dessert_price, dessert_cals, dessert_origin, dessert_image_url, user_id) + return render_template('add.html', dessert=dessert, username=username) except Exception as e: # Oh no, something went wrong! # We can access the error message via e.message: - return render_template('add.html', error=e.message) + return render_template('add.html', error=e.message, username=username) else: print "Logged-in: No session" @@ -134,12 +140,16 @@ def edit(id): dessert = Dessert.query.get(id) + user_id = get_user_id(username) if request.method == 'GET': if dessert is None: - return render_template('edit.html',dessert=dessert, error="The dessert ID do not exist.") + return render_template('edit.html',dessert=dessert, error="The dessert ID do not exist.", username=username) + if dessert.user_id != user_id: + dessert = None + return render_template('edit.html',dessert=dessert, error="You can't edit this dessert.", username=username) else: - return render_template('edit.html',dessert=dessert) + return render_template('edit.html',dessert=dessert, error=None, username=username) # Because we 'returned' for a 'GET', if we get to this next bit, we must # have received a POST @@ -160,11 +170,11 @@ def edit(id): # Wrap the thing we're trying to do in a 'try' block: try: dessert = edit_dessert(dessert, dessert_name, dessert_price, dessert_cals, dessert_origin, dessert_image_url) - return render_template('edit.html', dessert=dessert) + return render_template('edit.html', dessert=dessert, success=True, username=username) except Exception as e: # Oh no, something went wrong! # We can access the error message via e.message: - return render_template('edit.html', dessert=dessert, error=e.message) + return render_template('edit.html', dessert=dessert, error=e.message, username=username) else: print "Logged-in: No session" return render_template('login.html', error="Please login.") @@ -177,11 +187,19 @@ def view_dessert(id): print "Logged-in: Found session" username = session['username'] - # We could define this inside its own function but it's simple enough - # that we don't really need to. dessert = Dessert.query.get(id) - return render_template('details.html', dessert=dessert) + user_id = get_user_id(username) + + + if dessert is None: + return render_template('details.html',dessert=dessert, error="The dessert ID do not exist.", username=username) + if dessert.user_id != user_id: + dessert = None + return render_template('details.html',dessert=dessert, error="You can't view this dessert.", username=username) + else: + return render_template('details.html',dessert=dessert, error=None, username=username) + else: print "Logged-in: No session" return render_template('login.html', error="Please login.") @@ -193,13 +211,20 @@ def delete(id): print "Logged-in: Found session" username = session['username'] - message = delete_dessert(id) + user = get_user_by_username(username) + user_id = user.id + + user_id = get_user_id(username) - return index() # Look at the URL bar when you do this. What happens? + desserts = get_desserts(user_id) + error = delete_dessert(id, user_id) + + + return render_template('index.html', desserts=desserts, error="You can't edit this dessert.", username=username) else: print "Logged-in: No session" - return render_template('login.html', error="Please login.") + return render_template('login.html', error="Please login.", username=username) @app.route('/search', methods=['POST']) @@ -216,11 +241,11 @@ def search(): print if dessert: - return render_template('details.html', dessert=dessert) + return render_template('details.html', dessert=dessert, username=username) else: # Oh no, something went wrong! # We can access the error message via e.message: - return render_template('details.html', dessert=dessert, error="Name does not exist") + return render_template('details.html', dessert=dessert, error="Name does not exist", username=username) else: print "Logged-in: No session" return render_template('login.html', error="Please login.") From 82c597e31120db9015ba78897fc36c43a0468db5 Mon Sep 17 00:00:00 2001 From: Karla Lopez Date: Sun, 14 Jun 2015 22:28:37 -0700 Subject: [PATCH 9/9] Added API - list desserts and list desserts by user --- models.py | 5 +++++ views.py | 22 +++++++++++++++++++++- 2 files changed, 26 insertions(+), 1 deletion(-) diff --git a/models.py b/models.py index cca8f28..2020588 100644 --- a/models.py +++ b/models.py @@ -58,6 +58,11 @@ def get_desserts(user_id): desserts = Dessert.query.filter_by(user_id=user_id).all() return desserts +def get_all_desserts(): + desserts = Dessert.query.all() + return desserts + + def get_user_id(username): user = get_user_by_username(username) user_id = user.id diff --git a/views.py b/views.py index c1fddb7..fabe50c 100644 --- a/views.py +++ b/views.py @@ -1,4 +1,4 @@ -from flask import render_template, request, redirect, session +from flask import render_template, request, redirect, session, jsonify from models import * from users import * @@ -273,3 +273,23 @@ def logout_user(): print "Logout: Deleting settion" del session['username'] return redirect("/") + +@app.route('/api') +def api(): + desserts = get_all_desserts() + api_dict = {} + for x in desserts: + dessert = dict([('name', x.name), ('price', x.price), ('calories', x.calories), ('origin', x.origin),('image_url', x.image_url), ('user_id', x.user_id)]) + index = x.id + api_dict[index] = dessert + return jsonify(api_dict) + +@app.route('/api/') +def api_id(user_id): + desserts = get_desserts(user_id) + api_dict = {} + for x in desserts: + dessert = dict([('name', x.name), ('price', x.price), ('calories', x.calories), ('origin', x.origin),('image_url', x.image_url), ('user_id', x.user_id)]) + index = x.id + api_dict[index] = dessert + return jsonify(api_dict)