Clean up JSON workarounds for unsupported Python versions

All Python versions supported by psycopg2 have the json module. It was
added in Python 2.6. Can remove checks for availability, slightly
simplifying the code.
This commit is contained in:
Jon Dufresne 2017-11-26 17:11:27 -08:00
parent 858bc3d42a
commit d58844e548

View File

@ -27,22 +27,13 @@ extensions importing register_json from extras.
# FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public # FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
# License for more details. # License for more details.
import json
import sys import sys
from psycopg2._psycopg import ISQLQuote, QuotedString from psycopg2._psycopg import ISQLQuote, QuotedString
from psycopg2._psycopg import new_type, new_array_type, register_type from psycopg2._psycopg import new_type, new_array_type, register_type
# import the best json implementation available
if sys.version_info[:2] >= (2, 6):
import json
else:
try:
import simplejson as json
except ImportError:
json = None
# oids from PostgreSQL 9.2 # oids from PostgreSQL 9.2
JSON_OID = 114 JSON_OID = 114
JSONARRAY_OID = 199 JSONARRAY_OID = 199
@ -67,13 +58,7 @@ class Json(object):
def __init__(self, adapted, dumps=None): def __init__(self, adapted, dumps=None):
self.adapted = adapted self.adapted = adapted
self._conn = None self._conn = None
self._dumps = dumps or json.dumps
if dumps is not None:
self._dumps = dumps
elif json is not None:
self._dumps = json.dumps
else:
self._dumps = None
def __conform__(self, proto): def __conform__(self, proto):
if proto is ISQLQuote: if proto is ISQLQuote:
@ -86,13 +71,7 @@ class Json(object):
provided in the constructor. You can override this method to create a provided in the constructor. You can override this method to create a
customized JSON wrapper. customized JSON wrapper.
""" """
dumps = self._dumps return self._dumps(obj)
if dumps is not None:
return dumps(obj)
else:
raise ImportError(
"json module not available: "
"you should provide a dumps function")
def prepare(self, conn): def prepare(self, conn):
self._conn = conn self._conn = conn
@ -181,10 +160,7 @@ def register_default_jsonb(conn_or_curs=None, globally=False, loads=None):
def _create_json_typecasters(oid, array_oid, loads=None, name='JSON'): def _create_json_typecasters(oid, array_oid, loads=None, name='JSON'):
"""Create typecasters for json data type.""" """Create typecasters for json data type."""
if loads is None: if loads is None:
if json is None: loads = json.loads
raise ImportError("no json module available")
else:
loads = json.loads
def typecast_json(s, cur): def typecast_json(s, cur):
if s is None: if s is None: