feat(util): Add to_query_str helper
This patch adds falcon.to_query_str(params) to make it fast and easy to create query strings based on a dictionary of (name, value) fields. Closes #104
This commit is contained in:
@@ -37,7 +37,7 @@ from falcon.api import API, DEFAULT_MEDIA_TYPE # NOQA
|
||||
from falcon.status_codes import * # NOQA
|
||||
from falcon.exceptions import * # NOQA
|
||||
from falcon.http_error import HTTPError # NOQA
|
||||
from falcon.util import dt_to_http # NOQA
|
||||
from falcon.util import dt_to_http, to_query_str # NOQA
|
||||
from falcon.hooks import before, after # NOQA
|
||||
from falcon.request import Request # NOQA
|
||||
from falcon.response import Response # NOQA
|
||||
|
||||
@@ -31,3 +31,35 @@ def dt_to_http(dt):
|
||||
|
||||
# Tue, 15 Nov 1994 12:45:26 GMT
|
||||
return dt.strftime('%a, %d %b %Y %H:%M:%S GMT')
|
||||
|
||||
|
||||
def to_query_str(params):
|
||||
"""Converts a dict of params to an actual query string.
|
||||
|
||||
Args:
|
||||
params: dict of simple key-value types, where key is a string and
|
||||
value is a string or something that can be converted into a
|
||||
string.
|
||||
|
||||
Returns:
|
||||
A URI query string starting with '?', or and empty string if there
|
||||
are no params (the dict is empty).
|
||||
|
||||
"""
|
||||
if not params:
|
||||
return ''
|
||||
|
||||
# PERF: This is faster than a list comprehension and join, mainly
|
||||
# because it allows us to inline the value transform.
|
||||
query_str = '?'
|
||||
for k, v in params.items():
|
||||
if v is True:
|
||||
v = 'true'
|
||||
elif v is False:
|
||||
v = 'false'
|
||||
else:
|
||||
v = str(v)
|
||||
|
||||
query_str += k + '=' + v + '&'
|
||||
|
||||
return query_str[:-1]
|
||||
|
||||
@@ -14,3 +14,39 @@ class TestFalconUtils(testtools.TestCase):
|
||||
self.assertEquals(
|
||||
falcon.dt_to_http(datetime(2013, 4, 4, 10, 28, 54)),
|
||||
'Thu, 04 Apr 2013 10:28:54 GMT')
|
||||
|
||||
def test_pack_query_params_none(self):
|
||||
self.assertEquals(
|
||||
falcon.to_query_str({}),
|
||||
'')
|
||||
|
||||
def test_pack_query_params_one(self):
|
||||
self.assertEquals(
|
||||
falcon.to_query_str({'limit': 10}),
|
||||
'?limit=10')
|
||||
|
||||
def test_pack_query_params_several(self):
|
||||
garbage_in = {
|
||||
'limit': 17,
|
||||
'echo': True,
|
||||
'doit': False,
|
||||
'x': 'val',
|
||||
'y': 0.2
|
||||
}
|
||||
|
||||
query_str = falcon.to_query_str(garbage_in)
|
||||
fields = query_str[1:].split('&')
|
||||
|
||||
garbage_out = {}
|
||||
for field in fields:
|
||||
k, v = field.split('=')
|
||||
garbage_out[k] = v
|
||||
|
||||
expected = {
|
||||
'echo': 'true',
|
||||
'limit': '17',
|
||||
'x': 'val',
|
||||
'y': '0.2',
|
||||
'doit': 'false'}
|
||||
|
||||
self.assertEquals(expected, garbage_out)
|
||||
|
||||
Reference in New Issue
Block a user