Nick Nick - 6 months ago 17
Python Question

Python Falcon filtering through URL

I have a small API that i'm working on, everything works ok, all my requests do what they are supposed to but when I try to filter results through the URL query for some reason it works for id but not for device field.

def on_get(self, req, resp):
"""Handles GET requests"""
if req.get_param("id"):
result = {'location': r.db(PROJECT_DB).table(PROJECT_TABLE).get(req.get_param("id")).run(db_connection)}

elif req.get_param("device"):
result = {'location': r.db(PROJECT_DB).table(PROJECT_TABLE).get(req.get_param("device")).run(db_connection)}

else:
location = r.db(PROJECT_DB).table(PROJECT_TABLE).run(db_connection)
result = {'locations': [i for i in location]}
resp.body = json.dumps(result)


example
http://localhost:8000/location?id=(some random id)
this will work

but if i do
http://localhost:8000/location?device=(some device)
this will not work, returns null

So could anyone tell me what am I doing wrong? or better yet if anyone knows a better way to filter using the URL?

Note: I am using rethinkdb

EDIT:

This is what I have normally:

{
"locations": [
{
"id": "4bf4b94f-747a-42db-9d54-a8399d995025",
"location": "gps coords",
"device": "Device 2"
},
{
"id": "b5cce561-37d2-42e7-86e4-a31c008b0af2",
"location": "gps coords",
"device": "Device 1"
},
{
"id": "bebba7cf-710c-4ee8-ad69-2d58174d4e02",
"location": "gps coords",
"device": "Device 1"
},
{
"id": "e928f84b-60ff-40f3-b839-920bc99e5480",
"location": "gps coords",
"device": "Device1"
}
]
}


Filtering by id works ok, but not by device which is weird

Answer

I found the answer to this problem, the reason why it did not war was because rethinkdb only gets via primary key on the get query

result = {'location': r.db(PROJECT_DB).table(PROJECT_TABLE).get(req.get_param("device")).run(db_connection)}

so what I should have done was to filter the results by what I wanted like this and it would have worked

result = {'location': list(r.db(PROJECT_DB).table(PROJECT_TABLE).filter({'device': param}).run(db_connection))}

Thanks for the help everyone and hope this answer helps.