Skip to content

Commit

Permalink
Use the excellent six library for python 2/3 compatibility
Browse files Browse the repository at this point in the history
  • Loading branch information
stevearc committed May 9, 2014
1 parent 52f523a commit 069070e
Show file tree
Hide file tree
Showing 7 changed files with 31 additions and 63 deletions.
1 change: 1 addition & 0 deletions CHANGES.rst
Expand Up @@ -4,6 +4,7 @@ Changelog
0.1.2
-----
* Bug fix: Fix potential timezone issue when converting unix time to datetime
* Using the 'six' library for python 2/3 compatibility

0.1.1
-----
Expand Down
41 changes: 0 additions & 41 deletions pyramid_duh/compat.py

This file was deleted.

13 changes: 7 additions & 6 deletions pyramid_duh/params.py
Expand Up @@ -4,6 +4,7 @@
import functools
import inspect
import json
import six
from pyramid.httpexceptions import HTTPBadRequest, HTTPException
from pyramid.interfaces import IRequest
from pyramid.path import DottedNameResolver
Expand All @@ -12,7 +13,6 @@
from zope.interface.exceptions import DoesNotImplement
from zope.interface.verify import verifyObject
# pylint: enable=F0401,E0611
from .compat import string_type, bytes_types, num_types, is_string, is_num


NO_ARG = object()
Expand Down Expand Up @@ -122,11 +122,11 @@ def _param_from_dict(request, params, name, default=NO_ARG, type=None,
try:
if type is None:
value = arg
elif type is string_type:
if not is_string(arg):
elif type is six.text_type or type is six.string_types:
if not isinstance(arg, six.string_types):
raise HTTPBadRequest("Argument '%s' is the wrong type!" % name)
value = arg
elif type in bytes_types:
elif type is six.binary_type:
value = arg.encode("utf8")
elif type is list or type is dict:
if loads:
Expand All @@ -143,13 +143,14 @@ def _param_from_dict(request, params, name, default=NO_ARG, type=None,
elif type is datetime.timedelta:
value = datetime.timedelta(seconds=float(arg))
elif type is datetime.date:
if is_num(arg) or arg.isdigit():
if (isinstance(arg, six.integer_types) or
isinstance(arg, float) or arg.isdigit()):
value = datetime.datetime.utcfromtimestamp(int(arg)).date()
else:
value = datetime.datetime.strptime(arg, '%Y-%m-%d').date()
elif type is bool:
value = asbool(arg)
elif type in num_types:
elif type in six.integer_types or type is float:
value = type(arg)
else:
if loads:
Expand Down
4 changes: 2 additions & 2 deletions pyramid_duh/view.py
Expand Up @@ -4,9 +4,9 @@

import functools
import inspect
import six
from pyramid.httpexceptions import HTTPFound

from .compat import is_string
from .params import is_request


Expand Down Expand Up @@ -105,7 +105,7 @@ def simple(request)
"""

def __init__(self, paths, config):
if is_string(paths):
if isinstance(paths, six.string_types):
paths = (paths,)
self.paths = paths
self.config = config
Expand Down
1 change: 1 addition & 0 deletions setup.py
Expand Up @@ -11,6 +11,7 @@

REQUIREMENTS = [
'pyramid',
'six',
]

TEST_REQUIREMENTS = [
Expand Down
6 changes: 6 additions & 0 deletions tests/__init__.py
@@ -1 +1,7 @@
""" Tests """
import six

if six.PY3: # pragma: no cover
import unittest
# pylint: disable=E1101
unittest.TestCase.assertItemsEqual = unittest.TestCase.assertCountEqual
28 changes: 14 additions & 14 deletions tests/test_params.py
@@ -1,18 +1,18 @@
""" Tests for param utilities """
from __future__ import unicode_literals

import calendar
import datetime
import json
import time

import calendar
import json
import six
from mock import MagicMock, call, patch
from pyramid.config import Configurator
from pyramid.httpexceptions import HTTPBadRequest
from pyramid.testing import DummyRequest

import pyramid_duh
from pyramid_duh.compat import is_bytes, is_string, string_type
from pyramid_duh.params import argify, param, includeme


Expand Down Expand Up @@ -73,7 +73,7 @@ def test_unicode_param(self):
request.params = {'field': 'myfield'}
field = param(request, 'field')
self.assertEquals(field, 'myfield')
self.assertTrue(is_string(field, strict=True))
self.assertTrue(isinstance(field, six.text_type))

def test_unicode_json_body(self):
""" Pull unicode params out of json body """
Expand All @@ -83,30 +83,30 @@ def test_unicode_json_body(self):
request.headers = {'Content-Type': 'application/json'}
field = param(request, 'field')
self.assertEquals(field, 'myfield')
self.assertTrue(is_string(field, strict=True))
self.assertTrue(isinstance(field, six.text_type))

def test_unicode_param_explicit(self):
""" Specifying type=unicode checks arg type before returning it """
request = DummyRequest()
request.params = {'field': 'myfield'}
field = param(request, 'field', type=string_type)
field = param(request, 'field', type=six.text_type)
self.assertEquals(field, 'myfield')
self.assertTrue(is_string(field, strict=True))
self.assertTrue(isinstance(field, six.text_type))

def test_unicode_param_bad_type(self):
""" Raise exception if unicode param as incorrect type """
request = DummyRequest()
request.params = {'field': 4}
with self.assertRaises(HTTPBadRequest):
param(request, 'field', type=string_type)
param(request, 'field', type=six.text_type)

def test_str_param(self):
""" Pull binary string param off of request object """
request = DummyRequest()
request.params = {'field': 'myfield'}
field = param(request, 'field', type=bytes)
self.assertEquals(field, b'myfield')
self.assertTrue(is_bytes(field))
self.assertTrue(isinstance(field, six.binary_type))

def test_str_json_body(self):
""" Pull str params out of json body """
Expand All @@ -116,15 +116,15 @@ def test_str_json_body(self):
request.headers = {'Content-Type': 'application/json'}
field = param(request, 'field', type=bytes)
self.assertEquals(field, b'myfield')
self.assertTrue(is_bytes(field))
self.assertTrue(isinstance(field, six.binary_type))

def test_bytes_param(self):
""" Pull binary string param off of request object """
request = DummyRequest()
request.params = {'field': 'myfield'}
field = param(request, 'field', type=bytes)
self.assertEquals(field, b'myfield')
self.assertTrue(is_bytes(field))
self.assertTrue(isinstance(field, six.binary_type))

def test_int_param(self):
""" Pull integer off of request object """
Expand Down Expand Up @@ -480,7 +480,7 @@ def test_validate(self):
""" argify() can run a validation check on parameter values """
validate = lambda x: x.startswith('foo')

@argify(field=(string_type, validate))
@argify(field=(six.text_type, validate))
def base_req(request, field):
return field
context = object()
Expand All @@ -493,7 +493,7 @@ def test_validate_failure(self):
""" if argify fails validation check, raise exception """
validate = lambda x: x.startswith('foo')

@argify(field=(string_type, validate))
@argify(field=(six.text_type, validate))
def base_req(request, field): # pragma: no cover
return field
context = object()
Expand All @@ -506,7 +506,7 @@ def test_validate_kwargs_failure(self):
""" if argify fails validation check for kwargs, raise exception """
validate = lambda x: x.startswith('foo')

@argify(field=(string_type, validate))
@argify(field=(six.text_type, validate))
def base_req(request, field=None): # pragma: no cover
return field
context = object()
Expand Down

0 comments on commit 069070e

Please sign in to comment.