Skip to content

Commit

Permalink
Merge pull request #68 from olinlibrary/newsch/restructuring
Browse files Browse the repository at this point in the history
Newsch/restructuring
  • Loading branch information
newsch authored Jul 19, 2017
2 parents 922e9b8 + 6a0f9fa commit 3fe147c
Show file tree
Hide file tree
Showing 8 changed files with 107 additions and 82 deletions.
3 changes: 2 additions & 1 deletion abe/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,8 @@
FORMAT = "%(levelname)s:ABE: _||_ %(message)s"
logging.basicConfig(level=logging.DEBUG, format=FORMAT)

from .resource_models import EventApi, LabelApi, ICSFeed
from .resource_models.event_resources import EventApi, ICSFeed
from .resource_models.label_resources import LabelApi

app = Flask(__name__)
CORS(app)
Expand Down
3 changes: 2 additions & 1 deletion abe/database.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
#!/usr/bin/env python3
"""Connect to mongodb"""
from mongoengine import *
from .document_models import Event, Label, RecurringEventExc, ICS
from .document_models.event_documents import Event, RecurringEventExc
from .document_models.label_documents import Label
import os
import logging
logging.basicConfig(level=logging.DEBUG)
Expand Down
Empty file added abe/document_models/__init__.py
Empty file.
Original file line number Diff line number Diff line change
Expand Up @@ -57,12 +57,3 @@ class Event(Document):
meta = {'allow_inheritance': True} # TODO: set indexes

# TODO: look into clean() function for more advanced data validation

class Label(Document):
"""Model for labels of events"""
name = StringField(required=True, unique=True) # TODO: set to primary key?
description = StringField()
url = URLField()

class ICS(Document):
url = StringField()
11 changes: 11 additions & 0 deletions abe/document_models/label_documents.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
#!/usr/bin/env python3
"""Document models for mongoengine"""
from mongoengine import *
from bson import ObjectId


class Label(Document):
"""Model for labels of events"""
name = StringField(required=True, unique=True) # TODO: set to primary key?
description = StringField()
url = URLField()
Empty file added abe/resource_models/__init__.py
Empty file.
74 changes: 3 additions & 71 deletions abe/resource_models.py → abe/resource_models/event_resources.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,14 +12,14 @@
from icalendar import Calendar
import isodate

from .helpers import *
from abe.helpers import *

import pdb
import requests

import logging

from . import database as db
from abe import database as db


class EventApi(Resource):
Expand Down Expand Up @@ -152,74 +152,6 @@ def delete(self, event_id, rec_id=None):
return mongo_to_dict(result)


class LabelApi(Resource):
"""API for interacting with all labels (searching, creating)"""
def get(self, label_name=None):
"""Retrieve labels"""
if label_name: # use label name/object id if present
logging.debug('Label requested: ' + label_name)
search_fields = ['name', 'id']
result = multi_search(db.Label, label_name, search_fields)
if not result:
return "Label not found with identifier '{}'".format(label_name), 404
else:
return mongo_to_dict(result)
else: # search database based on parameters
# TODO: search based on terms
results = db.Label.objects()
if not results:
return []
else:
return [mongo_to_dict(result) for result in results]

def post(self):
"""Create new label with parameters passed in through args or form"""
received_data = request_to_dict(request)
logging.debug("Received POST data: {}".format(received_data))
try:
new_label = db.Label(**received_data)
new_label.save()
except ValidationError as error:
logging.warning("POST request rejected: {}".format(str(error)))
return {'error_type': 'validation',
'validation_errors': [str(err) for err in error.errors],
'error_message': error.message}, 400
else: # return success
return mongo_to_dict(new_label), 201

def put(self, label_name):
"""Modify individual label"""
logging.debug('Label requested: ' + label_name)
search_fields = ['name', 'id']
result = multi_search(db.Label, label_name, search_fields)
if not result:
return "Label not found with identifier '{}'".format(label_name), 404

try:
result.update(**received_data)
result.reload() # load the new document data into the local object
except ValidationError as error:
return {'error_type': 'validation',
'validation_errors': [str(err) for err in error.errors],
'error_message': error.message}, 400

else: # return success
return mongo_to_dict(result)

def delete(self, label_name):
"""Delete individual label"""
logging.debug('Label requested: ' + label_name)
search_fields = ['name', 'id']
result = multi_search(db.Label, label_name, search_fields)
if not result:
return "Label not found with identifier '{}'".format(label_name), 404

received_data = request_to_dict(request)
logging.debug("Received DELETE data: {}".format(received_data))
result.delete()
return mongo_to_dict(result)


class ICSFeed(Resource):
"""API for interacting with ics feeds"""
def get(self, ics_name=None):
Expand All @@ -245,7 +177,7 @@ def post(self):
labels = ['unlabeled']

extract_ics(cal, url['url'], labels)


def put(self, ics_name):
pass
Expand Down
89 changes: 89 additions & 0 deletions abe/resource_models/label_resources.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
#!/usr/bin/env python3
"""Resource models for flask"""

from flask import jsonify, request, abort, Response, make_response
from flask_restful import Resource
from mongoengine import ValidationError
from bson.objectid import ObjectId
from pprint import pprint, pformat
from bson import json_util, objectid
from datetime import datetime, timedelta
from dateutil.rrule import rrule, MONTHLY, WEEKLY, DAILY, YEARLY
from icalendar import Calendar
import isodate

from abe.helpers import *

import pdb
import requests

import logging

from abe import database as db


class LabelApi(Resource):
"""API for interacting with all labels (searching, creating)"""
def get(self, label_name=None):
"""Retrieve labels"""
if label_name: # use label name/object id if present
logging.debug('Label requested: ' + label_name)
search_fields = ['name', 'id']
result = multi_search(db.Label, label_name, search_fields)
if not result:
return "Label not found with identifier '{}'".format(label_name), 404
else:
return mongo_to_dict(result)
else: # search database based on parameters
# TODO: search based on terms
results = db.Label.objects()
if not results:
return []
else:
return [mongo_to_dict(result) for result in results]

def post(self):
"""Create new label with parameters passed in through args or form"""
received_data = request_to_dict(request)
logging.debug("Received POST data: {}".format(received_data))
try:
new_label = db.Label(**received_data)
new_label.save()
except ValidationError as error:
logging.warning("POST request rejected: {}".format(str(error)))
return {'error_type': 'validation',
'validation_errors': [str(err) for err in error.errors],
'error_message': error.message}, 400
else: # return success
return mongo_to_dict(new_label), 201

def put(self, label_name):
"""Modify individual label"""
logging.debug('Label requested: ' + label_name)
search_fields = ['name', 'id']
result = multi_search(db.Label, label_name, search_fields)
if not result:
return "Label not found with identifier '{}'".format(label_name), 404

try:
result.update(**received_data)
except ValidationError as error:
return {'error_type': 'validation',
'validation_errors': [str(err) for err in error.errors],
'error_message': error.message}, 400

else: # return success
return mongo_to_dict(result)

def delete(self, label_name):
"""Delete individual label"""
logging.debug('Label requested: ' + label_name)
search_fields = ['name', 'id']
result = multi_search(db.Label, label_name, search_fields)
if not result:
return "Label not found with identifier '{}'".format(label_name), 404

received_data = request_to_dict(request)
logging.debug("Received DELETE data: {}".format(received_data))
result.delete()
return mongo_to_dict(result)

0 comments on commit 3fe147c

Please sign in to comment.