Skip to content

Commit

Permalink
initial commit
Browse files Browse the repository at this point in the history
  • Loading branch information
gergob committed Jan 9, 2015
1 parent 415e43a commit 8432f86
Show file tree
Hide file tree
Showing 41 changed files with 19,129 additions and 0 deletions.
52 changes: 52 additions & 0 deletions app.py
@@ -0,0 +1,52 @@
from flask import Flask, render_template, request, redirect, url_for
from bson.objectid import ObjectId
from contact import Contact
from contacts_repository import ContactsRepository

app = Flask(__name__)
repository = ContactsRepository()

@app.route("/")
def index():
return render_template("index.html")

@app.route("/add_contact", methods=["GET","POST"])
def add_contact():
if request.method == "GET":
return render_template("add_contact.html")
elif request.method == "POST":
for item,val in request.form.items():
print("{0}={1}".format(item, val))
try:
contact = Contact(first_name=request.form['first_name'],
last_name=request.form['last_name'],
birthday=request.form['birthday'],
website=request.form['website'],
home_phone=request.form['home_phone'],
mobile_phone=request.form['mobile_phone'],
work_phone=request.form['work_phone'],
email=request.form['email'])
contact_id = repository.create(contact)
print("Contact succesfully created with id={0}".format(contact_id))
except Error as e:
print(e)

return redirect(url_for("index"))
else:
return redirect(url_for("index"))

@app.route("/contacts")
def contacts():
contacts_to_display = []
contacts_from_db = repository.read()
for c in contacts_from_db:
tempContact = Contact.build_from_json(c)
print("Contact converted: {0}".format(tempContact))
contacts_to_display.append(tempContact)
return render_template("contacts.html", contacts = contacts_to_display)


if __name__ == "__main__":
app.run(debug=True)


56 changes: 56 additions & 0 deletions contact.py
@@ -0,0 +1,56 @@
from bson.objectid import ObjectId
from datetime import datetime

class Contact(object):
"""A class for storing Contact information"""

def __init__(self, contact_id=None, first_name=None, last_name=None, birthday=None, website=None, home_phone=None, mobile_phone=None, work_phone=None, email=None):
if contact_id is None:
self._id = ObjectId()
else:
self._id = contact_id
self.first_name = first_name
self.last_name = last_name

if birthday is not None:
if type(birthday) == datetime:
self.birthday = birthday
else:
try:
tmpBd = datetime.strptime(birthday,"%Y-%m-%dT%H:%M")
self.birthday = tmpBd
except ValueError as e:
self.birthday = None
print(e)
else:
self.birthday = None
self.website = website
self.home_phone = home_phone
self.work_phone = work_phone
self.mobile_phone = mobile_phone
self.email = email

def get_as_json(self):
""" Method returns the JSON representation of the Contac object, this can be saved to MongoDB """
return self.__dict__


@staticmethod
def build_from_json(json_data):
""" Method used to build Contact objects from JSON data returned from MongoDB """
if json_data is not None:
try:
return Contact(json_data.get('_id', None),
json_data['first_name'],
json_data['last_name'],
json_data['birthday'],
json_data['website'],
json_data['home_phone'],
json_data['mobile_phone'],
json_data['work_phone'],
json_data['email'])
except KeyError as e:
raise Exception("Key not found in json_data: {}".format(e.message))
else:
raise Exception("No data to create Contact from!")

46 changes: 46 additions & 0 deletions contacts_repository.py
@@ -0,0 +1,46 @@
from pymongo import MongoClient
from bson.objectid import ObjectId
from contact import Contact

class ContactsRepository(object):
""" Repository implementing CRUD operations on contacts collection in MongoDB """

def __init__(self):
# initializing the MongoClient, this helps to
# access the MongoDB databases and collections
self.client = MongoClient(host='localhost', port=27017)
self.database = self.client['contact_db']


def create(self, contact):
created_id = None
if contact is not None:
created_id = self.database.contacts.insert(contact.get_as_json())
else:
raise Exception("Nothing to save, becuase contact parameter is None")

return created_id

def read(self, contact_id=None):
if contact_id is None:
return self.database.contacts.find({})
else:
return self.database.contacts.find({"_id":contact_id})


def update(self, contact):
if contact is not None:
# the save() method updates the document if this has an _id property
# which appers in the collection, otherwise it saces the data
# as a new document in the collection
self.database.contacts.save(project.get_as_json())
else:
raise Exception("Nothing to update, becuase contact parameter is None")


def delete(self, contact):
if contact is not None:
self.database.contacts.remove(contact.get_as_json())
else:
raise Exception("Nothing to delete, becuase contact parameter is None")

20 changes: 20 additions & 0 deletions static/css/app.css
@@ -0,0 +1,20 @@
.icon-bar {
background: #388E8E;
}

.icon-bar > * label {
color: #000000;
}

.button {
background-color: #388E8E;
}

table tr th {
background: #F2F2F2;
}

table tr td {
font-family: monospace;
}

15 changes: 15 additions & 0 deletions static/css/app.css~
@@ -0,0 +1,15 @@
.icon-bar {
background: #388E8E;
}

.icon-bar > * label {
color: #000000;
}

.button {
background-color: #388E8E;
}

table tr th {
background: #F2F2F2;
}

0 comments on commit 8432f86

Please sign in to comment.