Created
March 14, 2013 10:34
-
-
Save jdu/5160339 to your computer and use it in GitHub Desktop.
Start of OData-esque layer on top of SQLAlchemy
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import pprint | |
from sqlalchemy import desc, func | |
from libs.database import Session | |
def importer(name): | |
mod = __import__(name) | |
components = name.split('.') | |
for comp in components[1:]: | |
mod = getattr(mod, comp) | |
return mod | |
class API: | |
def __init__(self, model): | |
self.model = model | |
def get(self, cfg): | |
""" | |
config options | |
orderby = list of "param_name direction" | |
limit = int limit amount of results | |
skip = int number of items to skip ahead | |
filter = | |
select = [list] the list of properties to return | |
""" | |
pkg = "libs.models.%s" % (self.model) | |
module = __import__(pkg, fromlist=[self.model]) | |
model = getattr(module, self.model) | |
sess = Session() | |
q = sess.query(model) | |
if 'filter' in cfg: | |
first = True | |
for filt in cfg['filter']: | |
if first is True: | |
q = q.filter("%s='%s'" % (filt['property'], filt['value'])) | |
first = False | |
else: | |
q = q.filter("AND %s='%s'" % (filt['property'], filt['value'])) | |
if 'orderby' in cfg: | |
for order in cfg['orderby']: | |
order_string = "%s.%s %s" % (model.__dict__['__tablename__'], order['property'], order['direction']) | |
q = q.order_by(order_string) | |
if 'limit' in cfg: | |
q = q.limit(cfg['limit']) | |
if 'skip' in cfg: | |
q = q.offset(cfg['skip']) | |
items = q.all() | |
total_items = sess.query(func.count(model.id)).scalar() | |
sess.close() | |
data = { | |
"results": [i.serialize for i in items], | |
"total": total_items | |
} | |
return data | |
def update(self, cfg): | |
pass | |
def delete(self, cfg): | |
pass | |
def insert(self, cfg): | |
pass |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment