Merge pull request #53 from sagidayan/API_Dev

Api dev
This commit is contained in:
Sagi Dayan 2015-06-22 08:18:39 +03:00
commit b1de4f2875
10 changed files with 295 additions and 142 deletions

View file

@ -48,7 +48,7 @@ def create_campus(token):
<br> <br>
<b>Response</b> <b>Response</b>
<br> <br>
201 - Created 200 - OK
<br> <br>
403 - Invalid Token/Forbidden 403 - Invalid Token/Forbidden
""" """
@ -108,7 +108,8 @@ def get_campuses(token):
'title': 'JCE',<br> 'title': 'JCE',<br>
'email_ending': '@post.jce.ac.il',<br> 'email_ending': '@post.jce.ac.il',<br>
'master_user_id': 123453433341, (User that created the campus)<br> 'master_user_id': 123453433341, (User that created the campus)<br>
'avatar_url': 'http://some.domain.com/imagefile.jpg'<br> 'avatar_url': 'http://some.domain.com/imagefile.jpg',<br>
'id' : 1234567890<br>
},<br> },<br>
....<br> ....<br>
{<br> {<br>
@ -140,15 +141,16 @@ def get_campuses(token):
return forbidden("Invalid Token") return forbidden("Invalid Token")
@campus_routes.route('/api/campuses/deleteCampus/<string:token>/<string:campusName>', methods=['DELETE'])
@campus_routes.route('/api/campuses/deleteCampus/<string:token>/<string:campusid>', methods=['DELETE'])
@auto.doc() @auto.doc()
def deleteCampus(token,campusName): def deleteCampus(token,campusid):
""" """
<span class="card-title">This Call will delete a specific campus</span> <span class="card-title">This Call will delete a specific campus</span>
<br> <br>
<b>Route Parameters</b><br> <b>Route Parameters</b><br>
- seToken: 'seToken' - seToken: 'seToken'
- title: 'campusName' - campusid: 'campusid'
<br> <br>
<br> <br>
<b>Payload</b><br> <b>Payload</b><br>
@ -159,42 +161,33 @@ def deleteCampus(token,campusName):
<br> <br>
202 - Deleted campus 202 - Deleted campus
<br> <br>
204 - No Matching Campus Found
<br>
....<br> ....<br>
{<br> {<br>
...<br> ...<br>
}req<br> }req<br>
]<br> ]<br>
400 - Bad Request 400 - no such campus
<br> <br>
403 - Invalid token or not a lecturer!<br> 403 - Invalid token or not a lecturer or lecturer is not owner of campus!<br>
""" """
if not is_lecturer(token): #todo: change to lecturer id if not is_lecturer(token): #todo: change to lecturer id
return forbidden("Invalid token or not a lecturer!") return forbidden("Invalid token or not a lecturer!")
user = get_user_by_token(token) user = get_user_by_token(token)
query = Campus.all() camp = Campus.get_by_id(int(campusid))
query.filter('master_user_id =',user.key().id())
try: if camp is None:
query.filter('title =', campusName) return bad_request("no such campus")
except Exception as e:
print e
return bad_request("invalid campus title attribute")
for c in query.run(): if camp.master_user_id == user.key().id():
db.delete(c) db.delete(camp)
db.save db.save
return accepted("campus deleted") return accepted("campus deleted")
return forbidden("lecturer is not owner of campus")
return bad_request("no such campus found")

View file

@ -189,6 +189,8 @@ def getCourseByCampusName(name):
'startDate': '2015-14-3'<br> 'startDate': '2015-14-3'<br>
'endDate': '2015-29-6'<br> 'endDate': '2015-29-6'<br>
'taskFlag': 'False'<br> 'taskFlag': 'False'<br>
'id' : 1234567890<br>
} }
</code> </code>
<br> <br>
@ -232,7 +234,9 @@ def getMessagesByCourseName(name):
'campusName': 'JCE',<br> 'campusName': 'JCE',<br>
'startDate': '2015-14-3'<br> 'startDate': '2015-14-3'<br>
'endDate': '2015-29-6'<br> 'endDate': '2015-29-6'<br>
'taskFlag': 'False'<br> 'taskFlag': false,<br>
'id' : 1234567890<br>
} }
</code> </code>
<br> <br>
@ -272,15 +276,21 @@ def getMessagesByCourseName(name):
#---------------------------------------------------------- #----------------------------------------------------------
# DELETE # DELETE
#---------------------------------------------------------- #----------------------------------------------------------
@course_routes.route('/api/courses/deleteCourse/<string:token>/<string:courseName>', methods=['DELETE'])
@course_routes.route('/api/courses/deleteCourse/<string:token>/<string:courseid>', methods=['DELETE'])
@auto.doc() @auto.doc()
def deleteCourse(token,courseName): def deleteCourse(token,courseid):
""" """
<span class="card-title">This Call will delete a specific course</span> <span class="card-title">This Call will delete a specific Course</span>
<br> <br>
<b>Route Parameters</b><br> <b>Route Parameters</b><br>
- seToken: 'seToken' - seToken: 'seToken'
- title: 'courseName' - courseid: 'courseid'
<br> <br>
<br> <br>
<b>Payload</b><br> <b>Payload</b><br>
@ -289,9 +299,7 @@ def deleteCourse(token,courseName):
<br> <br>
<b>Response</b> <b>Response</b>
<br> <br>
202 - Deleted campus 202 - Deleted Course
<br>
204 - No Matching Campus Found
<br> <br>
....<br> ....<br>
{<br> {<br>
@ -299,33 +307,27 @@ def deleteCourse(token,courseName):
}req<br> }req<br>
]<br> ]<br>
400 - Bad Request 400 - no such Course
<br> <br>
403 - Invalid token or not a lecturer!<br> 403 - Invalid token or not a lecturer or lecturer is not owner of Course!<br>
""" """
if not is_lecturer(token): #todo: change to lecturer id if not is_lecturer(token): #todo: change to lecturer id
return forbidden("Invalid token or not a lecturer!") return forbidden("Invalid token or not a lecturer!")
user = get_user_by_token(token) user = get_user_by_token(token)
query = Course.all() c = Course.get_by_id(int(courseid))
query.filter('master_id =',user.key().id())
try: if c is None:
query.filter('courseName =', courseName) return bad_request("no such course")
except Exception as e:
print e
return bad_request("invalid course title attribute")
for c in query.run(): if c.master_id == user.key().id():
db.delete(c) db.delete(c)
db.save db.save
return accepted("course deleted") return accepted("course deleted")
return forbidden("lecturer is not owner of course")
return bad_request("no such course or not owner of course")
@course_routes.route('/api/courses/deleteCoursesByCampus/<string:token>/<string:campusName>', methods=['DELETE']) @course_routes.route('/api/courses/deleteCoursesByCampus/<string:token>/<string:campusName>', methods=['DELETE'])

View file

@ -106,7 +106,8 @@ def getProjectsByCourseName(name):
'grade': 98,<br> 'grade': 98,<br>
'logo_url': 'http://location.domain.com/image.jpg',<br> 'logo_url': 'http://location.domain.com/image.jpg',<br>
'gitRepository': 'http://location.git.com/somthing',<br> 'gitRepository': 'http://location.git.com/somthing',<br>
'membersId': ['bob', 'dylan', 'quentin', 'terentino']<br> 'membersId': ['bob', 'dylan', 'quentin', 'terentino'],<br>
'id' : 1234567890<br>
} }
</code> </code>
<br> <br>
@ -130,6 +131,53 @@ def getProjectsByCourseName(name):
@project_routes.route('/api/projects/deleteProject/<string:token>/<string:projectid>', methods=['DELETE'])
@auto.doc()
def deleteProject(token,projectid):
"""
<span class="card-title">This Call will delete a specific Project</span>
<br>
<b>Route Parameters</b><br>
- seToken: 'seToken'
- courseid: 'projectid'
<br>
<br>
<b>Payload</b><br>
- NONE <br>
<br>
<br>
<b>Response</b>
<br>
202 - Deleted Project
<br>
....<br>
{<br>
...<br>
}req<br>
]<br>
400 - no such Project
<br>
403 - Invalid token or not the owner of Project!<br>
"""
# if not is_lecturer(token): #todo: change to lecturer id
# return forbidden("Invalid token or not a lecturer!")
user = get_user_by_token(token)
p = Project.get_by_id(int(projectid))
if p is None:
return bad_request("no such Project")
if p.master_id == user.key().id():
db.delete(p)
db.save
return accepted("Project deleted")
return forbidden("user is not owner of Project")
@project_routes.route('/api/projects/help') @project_routes.route('/api/projects/help')
def documentation(): def documentation():

View file

@ -18,6 +18,7 @@ from flask.ext.autodoc import Autodoc
# DB Models # DB Models
from models.Task import Task from models.Task import Task
from models.Course import Course from models.Course import Course
from models.TaskComponent import TaskComponent
#Validation Utils Libs #Validation Utils Libs
from SE_API.Validation_Utils import * from SE_API.Validation_Utils import *
@ -42,14 +43,35 @@ def create_task(token):
<b>Payload</b><br> <b>Payload</b><br>
- JSON Object, Example: <br> - JSON Object, Example: <br>
{<br> {<br>
'title' : self.title,<br> "title":"task1",<br>
'courseName' : self.course,<br> "courseName":"aran",<br>
'description' : self.description,<br> "description":"pls fddfsdfdsk",<br>
'dueDate' : self.dueDate,<br> "dueDate":{"year":2010,<br>
'isClose' : self.membersId,<br> "month":2,<br>
'isDone' : self.isDone,<br> "day":4<br>
'taskGrade' : self.taskGrade<br> },
}<br> "isPersonal":true,<br>
"components":[<br>
{<br>
"type" : "should be type1",<br>
"label" : "should be label1",<br>
"isMandatory" : true,<br>
"order" : 1<br>
},<br>
{<br>
"type" : "should be type2",<br>
"label" : "should be label2",<br>
"isMandatory" : true,<br>
"order" : 2<br>
},<br>
{<br>
"type" : "should be type3",<br>
"label" : "should be label3",<br>
"isMandatory" : false,<br>
"order" : 3<br>
}<br>
]<br>
}
<br> <br>
<br> <br>
<b>Response</b> <b>Response</b>
@ -90,89 +112,37 @@ def create_task(token):
date = datetime.date(payload['dueDate']['year'],payload['dueDate']['month'],payload['dueDate']['day']) date = datetime.date(payload['dueDate']['year'],payload['dueDate']['month'],payload['dueDate']['day'])
except Exception: except Exception:
return bad_request("invalid dueDate format") return bad_request("invalid dueDate format")
#TODO: add time. now, its only date
task = Task(title=payload['title'], courseName=payload['courseName'], description=payload['description'], dueDate=date) task = Task(title=payload['title'], courseName=payload['courseName'], description=payload['description'], dueDate=date)
#parse isClose # print "id: ",task.key().id()
#parse isPersonal
try: try:
task.isClose = payload['isClose'] task.isPersonal = payload['isPersonal']
except Exception: except Exception:
pass pass
#parse isDone
try:
task.isDone = payload['isDone']
except Exception:
pass
#parse taskGrade
try:
task.taskGrade = payload['taskGrade']
except Exception:
pass
except Exception as e: except Exception as e:
print e print e
return bad_request() return bad_request()
db.put(task) db.put(task)
db.save db.save
#create components
for c in payload['components']:
try:
component = TaskComponent(taskId=task.key().id(), userId=-1, type=c['type'], label=c['label'], isMandatory=c['isMandatory'], order=c['order'])
except Exception as e:
print e
return bad_request("Bad component")
db.put(component)
db.save
return created() return created()
@task_routes.route('/api/tasks/getClosestTask/<string:courseName>', methods=["GET"])
@auto.doc()
def getClosestTask(courseName):
"""
<span class="card-title">>This Call will return an array of all projects in a given course</span>
<br>
<b>Route Parameters</b><br>
- name: 'course name'
<br>
<br>
<b>Payload</b><br>
- NONE
<br>
<br>
<b>Response</b>
<br>
200 - JSON Example:<br>
<code>
{<br>
'projectName': 'Advance Math',<br>
'courseName': 'JCE',<br>
'grade': 98,<br>
'logo_url': 'http://location.domain.com/image.jpg',<br>
'gitRepository': 'http://location.git.com/somthing',<br>
'membersId': ['bob', 'dylan', 'quentin', 'terentino']<br>
}
</code>
<br>
"""
#get all tasks for a specific course
arr = []
query = Task.all()
query.filter("courseName =", courseName)
index = -1
count = -1
closestDate = datetime.date(3000,1,1)
for t in query.run():
count+=1
if t.dueDate < closestDate:
closestDate = t.dueDate
index = count
arr.append(dict(json.loads(t.to_JSON())))
print arr
if len(arr) != 0:
return Response(response=json.dumps(arr[index]),
status=200,
mimetype="application/json")
else:
return no_content("no Tasks")
@ -180,7 +150,7 @@ def getClosestTask(courseName):
@auto.doc() @auto.doc()
def getAllTasks(courseName): def getAllTasks(courseName):
""" """
<span class="card-title">>This Call will return an array of all projects in a given course</span> <span class="card-title">>This Call will return an array of all Tasks in a course by date</span>
<br> <br>
<b>Route Parameters</b><br> <b>Route Parameters</b><br>
- name: 'course name' - name: 'course name'
@ -195,13 +165,17 @@ def getAllTasks(courseName):
200 - JSON Example:<br> 200 - JSON Example:<br>
<code> <code>
{<br> {<br>
'projectName': 'Advance Math',<br> 'title' : 'Task1',<br>
'courseName': 'JCE',<br> 'courseName' : 'advance Math',<br>
'grade': 98,<br> 'description' : 'prepare by sunday',<br>
'logo_url': 'http://location.domain.com/image.jpg',<br> 'dueDate' : {
'gitRepository': 'http://location.git.com/somthing',<br> 'year' : 2015,
'membersId': ['bob', 'dylan', 'quentin', 'terentino']<br> 'month' : 12,
} 'day' : 23
}<br>
'isPersonal' : true,<br>
'task_id' : 589689456894<br>
}<br>
</code> </code>
<br> <br>
""" """
@ -227,12 +201,124 @@ def getAllTasks(courseName):
status=200, status=200,
mimetype="application/json") mimetype="application/json")
else: else:
return Response(response=[], return no_content()
@task_routes.route('/api/tasks/getTaskComponents/<string:taskId>', methods=["GET"])
@auto.doc()
def getTaskComponents(taskId):
"""
<span class="card-title">>This Call will return an array of all components for a given task</span>
<br>
<b>Route Parameters</b><br>
- taskId: integer
<br>
<br>
<b>Payload</b><br>
- NONE
<br>
<br>
<b>Response</b>
<br>
200 - JSON Example:<br>
<code>
[
{<br>
'taskId' : 7589454894,
'userId' : -1,
'type' : 'kindOfType',
'label' : 'kindOfLabel',
'isMandatory' : true,
'order' : 2
}<br>
{<br>
'taskId' : 7589454894,
'userId' : yossi,
'type' : 'otherKindOfType',
'label' : 'otherKindOfLabel',
'isMandatory' : false,
'order' : 4
}<br>
]
</code>
<br>
"""
arr = []
query = TaskComponent.all()
query.filter("taskId = ", taskId)
for tc in query.run():
arr.append(dict(json.loads(tc.to_JSON())))
#sort array by order, and remove added key
arr = sorted(arr, key=itemgetter('order'), reverse=False)
if len(arr) != 0:
return Response(response=json.dumps(arr),
status=200, status=200,
mimetype="application/json") mimetype="application/json")
else:
return no_content()
@task_routes.route('/api/tasks/help') @task_routes.route('/api/tasks/help')
def documentation(): def documentation():
return auto.html() return auto.html()
# @task_routes.route('/api/tasks/getClosestTask/<string:courseName>', methods=["GET"])
# @auto.doc()
# def getClosestTask(courseName):
# """
# <span class="card-title">>This Call will return an array of all projects in a given course</span>
# <br>
# <b>Route Parameters</b><br>
# - name: 'course name'
# <br>
# <br>
# <b>Payload</b><br>
# - NONE
# <br>
# <br>
# <b>Response</b>
# <br>
# 200 - JSON Example:<br>
# <code>
# {<br>
# 'projectName': 'Advance Math',<br>
# 'courseName': 'JCE',<br>
# 'grade': 98,<br>
# 'logo_url': 'http://location.domain.com/image.jpg',<br>
# 'gitRepository': 'http://location.git.com/somthing',<br>
# 'membersId': ['bob', 'dylan', 'quentin', 'terentino']<br>
# }
# </code>
# <br>
# """
# #get all tasks for a specific course
# arr = []
# query = Task.all()
# query.filter("courseName =", courseName)
# for t in query.run():
# count+=1
# if t.dueDate < closestDate:
# closestDate = t.dueDate
# index = count
# arr.append(dict(json.loads(t.to_JSON())))
#
# print arr
# if len(arr) != 0:
# return Response(response=json.dumps(arr[index]),
# status=200,
# mimetype="application/json")
# else:
# return no_content("no Tasks")
#

View file

@ -14,7 +14,8 @@ class Campus(db.Model):
data = {'title': self.title, data = {'title': self.title,
'email_ending': self.email_ending, 'email_ending': self.email_ending,
'master_user_id': self.master_user_id, 'master_user_id': self.master_user_id,
'avatar_url': self.avatar_url 'avatar_url': self.avatar_url,
'id' : self.key().id()
} }
return json.dumps(data) return json.dumps(data)

View file

@ -25,6 +25,7 @@ class Course(db.Model):
'year': self.endDate.year, 'year': self.endDate.year,
'month': self.endDate.month, 'month': self.endDate.month,
'day': self.endDate.day, 'day': self.endDate.day,
} },
} 'id' : self.key().id()
}
return json.dumps(data) return json.dumps(data)

View file

@ -18,6 +18,7 @@ class Message(db.Model):
'day': self.msgDate.day, 'day': self.msgDate.day,
'hour': self.msgDate.hour, 'hour': self.msgDate.hour,
'minute': self.msgDate.minute 'minute': self.msgDate.minute
} },
'id' : self.key().id()
} }
return json.dumps(data) return json.dumps(data)

View file

@ -20,5 +20,6 @@ class Project(db.Model):
'logo_url' : self.logo_url, 'logo_url' : self.logo_url,
'gitRepository' : self.gitRepository, 'gitRepository' : self.gitRepository,
'membersId' : self.membersId, 'membersId' : self.membersId,
'id' : self.key().id()
} }
return json.dumps(data) return json.dumps(data)

View file

@ -9,10 +9,7 @@ class Task(db.Model):
courseName = db.StringProperty(required=True) courseName = db.StringProperty(required=True)
description = db.StringProperty(required=True,default=" ") description = db.StringProperty(required=True,default=" ")
dueDate = db.DateProperty(required=True) dueDate = db.DateProperty(required=True)
#isProject = db.BooleanProperty(required=False) isPersonal = db.BooleanProperty(required=True, default=True)
isClose = db.BooleanProperty(required=True, default=False)
isDone = db.BooleanProperty(required=True, default=False)
taskGrade = db.IntegerProperty(required=True, default=0)
def to_JSON(self): def to_JSON(self):
data = {'title' : self.title, data = {'title' : self.title,
@ -23,10 +20,8 @@ class Task(db.Model):
'month': self.dueDate.month, 'month': self.dueDate.month,
'day': self.dueDate.day 'day': self.dueDate.day
}, },
#'isProject' : self.isProject, 'isPersonal' : self.isPersonal,
'isClose' : self.isClose, 'id' : self.key().id()
'isDone' : self.isDone,
'taskGrade' : self.taskGrade,
} }
return json.dumps(data) return json.dumps(data)

25
models/TaskComponent.py Normal file
View file

@ -0,0 +1,25 @@
__author__ = 'Aran'
import json
from google.appengine.ext import db
class TaskComponent(db.Model):
taskId = db.IntegerProperty(required=True)
userId = db.IntegerProperty(required=True, default = -1)
type = db.StringProperty(required=True,default=" ")
label = db.StringProperty(required=True,default=" ")
isMandatory = db.BooleanProperty(required=True, default=True)
order = db.IntegerProperty(required=True)
def to_JSON(self):
data = {'taskId' : self.taskId,
'userId' : self.userId,
'type' : self.type,
'label' : self.label,
'isMandatory' : self.isMandatory,
'order' : self.order,
'id' : self.key().id()
}
return json.dumps(data)