Skip to content

Commit

Permalink
initial (working) commit
Browse files Browse the repository at this point in the history
encode uri params supporting nested dictionaries and lists
  • Loading branch information
trshafer committed Jan 7, 2015
0 parents commit 624cc84
Show file tree
Hide file tree
Showing 9 changed files with 286 additions and 0 deletions.
49 changes: 49 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
# https://raw.githubusercontent.com/github/gitignore/master/Python.gitignore
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]

*.DS_Store

# C extensions
*.so

# Distribution / packaging
.Python
env/
build/
develop-eggs/
dist/
eggs/
lib/
lib64/
parts/
sdist/
var/
*.egg-info/
.installed.cfg
*.egg

ignored/

# Installer logs
pip-log.txt
pip-delete-this-directory.txt

# Unit test / coverage reports
htmlcov/
.tox/
.coverage
.cache
nosetests.xml
coverage.xml

# Translations
*.mo
*.pot

# Django stuff:
*.log

# Sphinx documentation
docs/_build/
6 changes: 6 additions & 0 deletions .travis.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
language: python
python:
- "2.7"
- "3.2"
- "3.3"
script: nosetests
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
The MIT License (MIT)

Copyright (c) 2014 cine.io

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
43 changes: 43 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
# Nested Query String Encoder
[![Build Status](https://travis-ci.org/cine-io/nested-query-string.svg?branch=master)](https://travis-ci.org/cine-io/nested-query-string)

Query string encoder that supports nested query strings in the format of [Rack::Utils](http://www.rubydoc.info/github/rack/rack/Rack/Utils) and [Node qs](https://github.com/hapijs/qs).

## Installation

install nested_query_string via pip:

pip install nested_query_string

## Usage

```python
import nested_query_string
from nested_query_string import NestedQueryString

NestedQueryString.encode({'abc': 'def', 'ghi': 1})
# => 'abc=def&ghi=1'

# with nested list
NestedQueryString.encode({'abc': ['def', 'ghi']})
# => 'abc[]=def&abc[]=ghi'

# with nested dictionary
NestedQueryString.encode({'abc': {'def': 'ghi', 'jkl': 'mno'}, 'pqr': 'stu'})
# => 'pqr=stu&abc[jkl]=mno&abc[def]=ghi'
```

## Gotcha

This library doesn't handle stringifing dates or other classes.
If you're worried about sending unsupported classes as values, surround with a try/except.

```python
import nested_query_string
from nested_query_string import NestedQueryString, UnsupportedParameterClassException

try:
NestedQueryString.encode({'abc': NestedQueryString})
except UnsupportedParameterClassException:
# handle exception
```
18 changes: 18 additions & 0 deletions nested_query_string/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
"""
nested_query_string
=======
:copyright: (c) 2014 by cine.io
:license: MIT, see LICENSE for more details
"""

from .nested_query_string import NestedQueryString, UnsupportedParameterClassException

from .version import __version__
__all__ = [NestedQueryString, UnsupportedParameterClassException]
__author__ = 'cine.io engineering'
__copyright__ = 'Copyright 2014 cine.io'
__license__ = 'MIT'
__title__ = 'nested_query_string'
__version_info__ = tuple(int(i) for i in __version__.split('.'))
58 changes: 58 additions & 0 deletions nested_query_string/nested_query_string.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
import sys

_ver = sys.version_info
#: Python 2.x?
is_py2 = (_ver[0] == 2)

#: Python 3.x?
is_py3 = (_ver[0] == 3)

if is_py2:
from urllib import quote

elif is_py3:
from urllib.parse import quote

class UnsupportedParameterClassException(Exception):
def __init__(self, value, obj):
self.value = value
self.obj = obj
def __str__(self):
return repr(self.value) + " <" + repr(self.obj.__class__.__name__) +":" + repr(self.obj) +">"

class NestedQueryString:

@classmethod
def encode(cls, value, key = None):
class_name = value.__class__
if class_name == dict:
result = []
for k, v in value.items():
result.append(cls.encode(v, cls.__append_key(key, k)))
result = '&'.join(result)
return result
elif class_name == list:
result = []
for v in value:
result.append(cls.encode(v, key+'[]'))
result = '&'.join(result)
return result
elif class_name == str:
return key + "=" + cls.__escape(value)
elif class_name == int:
return key + "=" + str(value)
elif class_name == None:
return ''
else:
raise UnsupportedParameterClassException('Unknown value class', value)

@classmethod
def __escape(cls, value):
return quote(value)

@classmethod
def __append_key(cls, root_key, key):
if root_key is None:
return key
else:
return root_key + "["+key+"]"
1 change: 1 addition & 0 deletions nested_query_string/version.py
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
__version__ = '0.0.1'
48 changes: 48 additions & 0 deletions setup.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
#!/usr/bin/env python

import os
import re
import sys
from setuptools import setup, find_packages

packages = find_packages(exclude=['test'])
requires = []

__version__ = ''
with open('nested_query_string/version.py', 'r') as fd:
reg = re.compile(r'__version__ = [\'"]([^\'"]*)[\'"]')
for line in fd:
m = reg.match(line)
if m:
__version__ = m.group(1)
break

if not __version__:
raise RuntimeError('Cannot find version information')

def data_for(filename):
with open(filename) as fd:
content = fd.read()
return content


setup(
name="nested_query_string",
version=__version__,
description='Generate nested query strings similar to rack and node qs',
license='MIT',
author='Cine.io Engineering',
author_email='[email protected]',
url='https://github.com/cine-io/nested-query-string',
packages=packages,
package_data={'': ['LICENSE']},
include_package_data=True,
install_requires=requires,
classifiers=[
"License :: OSI Approved :: MIT License",
"Programming Language :: Python",
"Development Status :: 3 - Alpha",
"Intended Audience :: Developers",
"Topic :: Internet",
],
)
42 changes: 42 additions & 0 deletions test/nested_query_string_test.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import sys, os, time
testdir = os.path.dirname(__file__)
srcdir = '../nested_query_string'
sys.path.insert(0, os.path.abspath(os.path.join(testdir, srcdir)))
import unittest

from nested_query_string import NestedQueryString, UnsupportedParameterClassException

class EncodeTest(unittest.TestCase):
def runTest(self):
qs = NestedQueryString.encode({'abc': 'def'})
self.assertEqual(qs, 'abc=def')

class EncodeNumericTest(unittest.TestCase):
def runTest(self):
qs = NestedQueryString.encode({'abc': 1})
self.assertEqual(qs, 'abc=1')

class EncodeNumericAndStringTest(unittest.TestCase):
def runTest(self):
qs = NestedQueryString.encode({'abc': 'def', 'ghi': 1})
self.assertEqual(qs, 'abc=def&ghi=1')

class EncodeDictTest(unittest.TestCase):
def runTest(self):
qs = NestedQueryString.encode({'abc': {'def': 'ghi', 'jkl': 'mno'}, 'pqr': 'stu'})
self.assertEqual(qs, 'pqr=stu&abc[jkl]=mno&abc[def]=ghi')

class EncodeListTest(unittest.TestCase):
def runTest(self):
qs = NestedQueryString.encode({'abc': ['def', 'ghi']})
self.assertEqual(qs, 'abc[]=def&abc[]=ghi')

class EncodeMixedTest(unittest.TestCase):
def runTest(self):
qs = NestedQueryString.encode({'abc': ['def', {'ghi': 'jkl'}]})
self.assertEqual(qs, 'abc[]=def&abc[][ghi]=jkl')

class EncodeExceptionTest(unittest.TestCase):
def runTest(self):
with self.assertRaises(UnsupportedParameterClassException):
NestedQueryString.encode({'abc': EncodeExceptionTest})

0 comments on commit 624cc84

Please sign in to comment.