7:5c5d433b3a14
Anton Shestakov <engored@ya.ru>, Thu, 27 Dec 2012 00:12:30 +0900
Moving toward a multi-workspace work model. There's no auth, knowing workspace id gives full access.

next change 18:fc0c0cc25502
previous change 3:fd68ae95de5e

app.py

Permissions: -rwxr-xr-x

Other formats: Feeds:
#!/usr/bin/env python
#-*- coding:utf-8 -*-
import os
from flask import Flask, g, request, render_template
from flask.ext.restful import Resource, Api
from CodernityDB.database import RecordNotFound
from CodernityDB.database_thread_safe import ThreadSafeDatabase
from fruitbar.indexes import ProjectIndex, TaskIndex
app = Flask(__name__)
api = Api(app)
db_path = os.path.join(os.path.dirname(__file__), 'db')
cdb = ThreadSafeDatabase(db_path)
if cdb.exists():
cdb.open()
cdb.reindex()
else:
cdb.create()
cdb.add_index(ProjectIndex(cdb.path, 'project'))
cdb.add_index(TaskIndex(cdb.path, 'task'))
@app.before_request
def before_request():
g.db = cdb
class ResourceList(Resource):
db_index = 'id'
doc_stub = {}
def get(self, workspace):
return [project['doc'] for project in g.db.get_many(self.db_index, workspace, with_doc=True)]
def post(self, workspace):
doc = request.json.copy()
doc.update(self.doc_stub)
doc.update({'workspace': workspace})
response = g.db.insert(doc)
return g.db.get('id', response['_id'], with_doc=True)
class CRUDResource(Resource):
""" CRUD? More like RUD!
"""
safe_fields = tuple()
def get(self, workspace, resource_id):
try:
doc = g.db.get('id', resource_id, with_doc=True)
if doc['workspace'] != workspace:
raise RecordNotFound
except RecordNotFound:
return '', 404
return doc
def put(self, workspace, resource_id):
try:
doc = g.db.get('id', resource_id, with_doc=True)
if doc['workspace'] != workspace:
raise RecordNotFound
except RecordNotFound:
return '', 404
userdata = dict((k, v) for (k, v) in request.json.items() if k in self.safe_fields)
doc.update(userdata)
response = g.db.update(doc)
return self.get(workspace, response['_id'])
def delete(self, workspace, resource_id):
try:
doc = g.db.get('id', resource_id, with_doc=True)
if doc['workspace'] != workspace:
raise RecordNotFound
except RecordNotFound:
return '', 404
g.db.delete(doc)
return '', 200
class ProjectList(ResourceList):
doc_stub = {'_t': 'project'}
db_index = 'project'
class Project(CRUDResource):
safe_fields = ('name', 'color')
def delete(self, workspace, resource_id):
g.db.run('task', 'delete_for_project', workspace, resource_id)
return super(Project, self).delete(workspace, resource_id)
class TaskList(ResourceList):
doc_stub = {'_t': 'task'}
db_index = 'task'
class Task(CRUDResource):
safe_fields = ('name', 'note', 'done')
api.add_resource(ProjectList, '/<workspace>/projects/')
api.add_resource(Project, '/<workspace>/projects/<resource_id>/')
api.add_resource(TaskList, '/<workspace>/tasks/')
api.add_resource(Task, '/<workspace>/tasks/<resource_id>/')
@app.route('/')
def index():
return render_template('index.html')
def main():
app.run(debug=True)
if __name__ == '__main__':
main()