Created
December 24, 2015 14:07
-
-
Save chozabu/86b60caa0ce211f232da to your computer and use it in GitHub Desktop.
hobby code to allow a client to construct their own queries for a django server (do not use)
This file contains 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
# /basic_api/?table=Post&sortby=-liquid_sum&startat=39 | |
def db_query(request): | |
if len(request.POST) == 0: | |
r_get = request.GET | |
else: | |
r_get = request.POST | |
# table whitelist? | |
rdata = {"Post": Post, "Tag": Tag, "Topic": Topic, "User": User} | |
table = r_get.get("table") | |
if not table: | |
return HttpResponse("no table") | |
if table not in rdata: | |
return HttpResponse("bad table") | |
objs = rdata[table].objects.filter() | |
# no black/whitelist on filter/excludes yet! | |
filters = r_get.get("filter", '[]') | |
if not filters: filters = "[]" | |
filters = json.loads(filters) | |
print filters | |
for vfilter in filters: | |
if not vfilter: continue | |
print "@filter" | |
print vfilter | |
objs = objs.filter(**vfilter) | |
excludes = r_get.get("exclude", '[]') | |
if not excludes: excludes = "[]" | |
excludes = json.loads(excludes) | |
print excludes | |
for vexclude in excludes: | |
if not vexclude: continue | |
print "@exclude" | |
print vexclude | |
objs = objs.exclude(**vexclude) | |
sortby = r_get.get("sortby") | |
if sortby: | |
print "@sortby" | |
presort = objs | |
objs = objs.order_by(sortby) | |
try: | |
print objs | |
except: | |
objs = presort | |
print "@len" | |
startat = int(r_get.get("startat", 0)) | |
length = int(r_get.get("length", 10)) | |
print startat, length | |
# o_count = objs.count() | |
objs = objs[startat:startat + length] | |
# r_count = objs.count() | |
# should probably return using .values() or another serialiser? serpy? | |
retr = [] | |
print "returning json" | |
fields = r_get.getlist("fields", ['pk', 'id']) | |
print fields | |
for i in objs: | |
ret_obj = {} | |
for f in fields: | |
ret_obj[f] = getattr(i, f) | |
retr.append(ret_obj) | |
return HttpResponse(json.dumps(retr)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment