Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -25,3 +25,9 @@ $ python app.py
```

Visit [http://localhost:5000/](http://localhost:5000/) in your browser to see the results.

### Running Tests

```
python test_models.py
```
2 changes: 1 addition & 1 deletion app.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,14 +7,14 @@
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///desserts.db'
db = SQLAlchemy(app)

app.secret_key = '\xa5MY\xb4\xc7\x03\x04\xa5I+C\x86\x1e\xae\x04\xb2-\xe4|\x06\x1e\x7f\x1f4'

if __name__ == "__main__":

# We need to make sure Flask knows about its views before we run
# the app, so we import them. We could do it earlier, but there's
# a risk that we may run into circular dependencies, so we do it at the
# last minute here.

from views import *

app.run(debug=True)
Empty file added backup.csv
Empty file.
27 changes: 27 additions & 0 deletions backup.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
from models import *


def save_data():

with open('backup.csv', 'w') as f: # Open file 'backup.csv' for writing

for dessert in Dessert.query.all():
# Create a comma separated line
line = "{},{},{}\n".format(dessert.name, dessert.price,
dessert.calories)
# Write it to the file
f.write(line)

def load_data():

with open('backup.csv') as f:
for line in f:
name, price, calories = line.split(',')
d = Dessert(name, price, calories)
db.session.add(d)
db.session.commit()


if __name__=="__main__":
# save_data()
load_data()
Binary file added desserts.db
Binary file not shown.
172 changes: 160 additions & 12 deletions models.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,17 @@
from app import db

from flask import session


class Menu(db.Model):

id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(100))

def __init__(self, name):
self.name = name

# DESSERTS
class Dessert(db.Model):
# See http://flask-sqlalchemy.pocoo.org/2.0/models/#simple-example
# for details on the column types.
Expand All @@ -13,39 +24,176 @@ class Dessert(db.Model):
price = db.Column(db.Float)
calories = db.Column(db.Integer)

def __init__(self, name, price, calories):
user_id = db.Column(db.Integer, db.ForeignKey('user.id'))
user = db.relationship("User", backref="desserts")

def __init__(self, name, price, calories, user_id):
self.name = name
self.price = price
self.calories = calories
self.user_id = user_id

def calories_per_dollar(self):
if self.calories:
return self.calories / self.price

def create_dessert(new_name, new_price, new_calories, user_id):
# Create a dessert with the provided input.
# We need every piece of input to be provided.

class Menu(db.Model):
# 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 or user_id is None:
raise Exception("Need name, price, calories, and user!")

id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(100))
# 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!")

def __init__(self, name):
self.name = name
if int(new_calories) > 10000:
raise Exception("That can't be right. Check the calories again.")

if int(new_price) > 100:
raise Exception("That can't be right. No dessert is worth that much.")

def create_dessert(new_name, new_price, new_calories):
# Create a dessert with the provided input.
# At first, we will trust the user.
if Dessert.query.filter_by(name=new_name).first():
raise Exception("There's already one of those. Pick another.")

# 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, user_id)

# Actually add this dessert to the database
db.session.add(dessert)

# Save all pending changes to the database
db.session.commit()
try:
db.session.commit()
return dessert
except:
# If something went wrong, explicitly roll back the database
db.session.rollback()

def update_dessert(dessert_name, dessert_price, dessert_cals, id):
# Create a dessert with the provided input.
# We need every piece of input to be provided.
dessert = Dessert.query.get(id)

# Can you think of other ways to write this following check?
if dessert_name is None or dessert_price is None or dessert_cals is None:
raise Exception("Need name, price and calories!")

# They can also be empty strings if submitted from a form
if dessert_name == '' or dessert_price == '' or dessert_cals == '':
raise Exception("Need name, price and calories!")

if int(dessert_cals) > 10000:
raise Exception("That can't be right. Check the calories again.")

if float(dessert_price) > 100:
raise Exception("That can't be right. No dessert is worth that much.")

# This is where the dessert gets updated
dessert.name = dessert_name
dessert.price = dessert_price
dessert.calories = dessert_cals
print 'dessert updated'

return dessert
# 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)
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"


# USERS
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

def log_in(username, password):
if username is None or password is None:
raise Exception("Please include your username and password.")

# They can also be empty strings if submitted from a form
if username == '' or password == '':
raise Exception("Please include your username and password.")

try:
user = get_user_by_username(username)
session["user_id"] = user.id
return user
except:
raise Exception("You don't have an account.")

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, name=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 name:
user.name = name

if avatar:
user.avatar = avatar

db.session.commit()
return user


if __name__ == "__main__":
Expand Down
19 changes: 19 additions & 0 deletions templates/account.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
{% include 'header.html' %}

<body>
<div class="container">
<h3>{{ user.name }}'s Account Details</h3>

<ul>
<li>Username: {{ user.username}}</li>
<li>Password: {{ user.password }}</li>
<li>Real name: {{ user.name }}</li>
<li>Email: {{ user.email }}</li>
<li>Avatar: {{ user.avatar }}</li>
<li>User id: {{ user.id }}</li>
</ul>


<a href="/menu">See your desserts</a>
</div>
</body>
71 changes: 44 additions & 27 deletions templates/add.html
Original file line number Diff line number Diff line change
@@ -1,27 +1,44 @@
<h3>Add Dessert</h3>

{% if dessert %}

<p><strong>{{dessert.name}}</strong> successfully created! Add another below.</p>
<p><a href="/">Back to Dessert List</a></p>

{% endif %}


<!-- The form action and method correspond to a Flask route -->
<form action="/add" method="POST">

<label for="name_id">Name</label>
<input id="name_id" name="name_field" type="text" />

<label for="price_id">Price</label>
<input id="price_id" name="price_field" type="text" size="4" />

<label for="cals_id">Calories</label>
<input id="cals_id" name="cals_field" type="text" size="4" />


<!-- We need a submit button to submit a form! -->
<input type="submit" value="Add"/>

</form>
{% include 'header.html' %}

<body>
<div class="container">
<h3>Add Dessert</h3>
{% if dessert %}

<!-- http://getbootstrap.com/components/#alerts -->
<div class="alert alert-success" role="alert">
<p><strong>{{dessert.name}}</strong> successfully created! Add another below.</p>
<p><a href="/menu">Back to Dessert List</a></p>
</div>
{% endif %}

{% if error %}
<div class="alert alert-danger" role="alert">
An error occurred trying to create your dessert:
{{ error }}
</div>
{% endif %}

<!-- Bootstrap: http://getbootstrap.com/css/#forms -->
<!-- The form action and method correspond to a Flask route -->
<form action="/add" method="POST" class="form-inline">
<div class="form-group">
<label for="name_id">Name</label>
<input class="form-control" id="name_id" name="name_field" type="text" />
</div>

<div class="form-group">
<label for="price_id">Price</label>
<input class="form-control" id="price_id" name="price_field" type="text" size="4" />
</div>

<div class="form-group">
<label for="cals_id">Calories</label>
<input class="form-control" id="cals_id" name="cals_field" type="text" size="4" />
</div>

<!-- We need a submit button to submit a form! -->
<input type="submit" value="Add" class="btn btn-success"/>
</form>
</div>
</body>
11 changes: 11 additions & 0 deletions templates/create-account.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
<h1>Confirm Your Account Details</h1>

<ul>
<li>Username: {{ user.username}}</li>
<li>Password: {{ user.password }}</li>
<li>Real name: {{ user.name }}</li>
<li>Email: {{ user.email }}</li>
<li>Avatar: {{ user.avatar }}</li>
</ul>

<a href="/login">Yup, Let's Log In</a>
Loading