From d4e5cb06cc707dbffbbfd2db4209c91e534cfd8a Mon Sep 17 00:00:00 2001 From: Daniele Varrazzo Date: Thu, 29 Dec 2016 21:13:19 +0100 Subject: Use the proper API functions to look up codec functions --- psycopg/connection.h | 4 +++- psycopg/connection_int.c | 15 +++++---------- 2 files changed, 8 insertions(+), 11 deletions(-) diff --git a/psycopg/connection.h b/psycopg/connection.h index 6c5a5f6..2e2d51d 100644 --- a/psycopg/connection.h +++ b/psycopg/connection.h @@ -122,9 +122,11 @@ struct connectionObject { PyObject *cursor_factory; /* default cursor factory from cursor() */ - /* Pointer to a decoding function, e.g. PyUnicode_DecodeUTF8 */ + /* Optional pointer to a decoding C function, e.g. PyUnicode_DecodeUTF8 */ PyObject *(*cdecoder)(const char *, Py_ssize_t, const char *); + /* Pointers to python encoding/decoding functions, e.g. + * codecs.getdecoder('utf8') */ PyObject *pyencoder; /* python codec encoding function */ PyObject *pydecoder; /* python codec decoding function */ }; diff --git a/psycopg/connection_int.c b/psycopg/connection_int.c index 38688d3..f92a658 100644 --- a/psycopg/connection_int.c +++ b/psycopg/connection_int.c @@ -451,17 +451,15 @@ conn_get_python_codec(const char *encoding, int rv = -1; char *pgenc = NULL; PyObject *encname = NULL; - PyObject *m = NULL, *f = NULL, *codec = NULL; PyObject *enc_tmp = NULL, *dec_tmp = NULL; + /* get the Python name of the encoding as a C string */ if (!(encname = conn_pgenc_to_pyenc(encoding, &pgenc))) { goto exit; } + if (!(encname = psycopg_ensure_bytes(encname))) { goto exit; } - /* Look up the python codec */ - if (!(m = PyImport_ImportModule("codecs"))) { goto exit; } - if (!(f = PyObject_GetAttrString(m, "lookup"))) { goto exit; } - if (!(codec = PyObject_CallFunctionObjArgs(f, encname, NULL))) { goto exit; } - if (!(enc_tmp = PyObject_GetAttrString(codec, "encode"))) { goto exit; } - if (!(dec_tmp = PyObject_GetAttrString(codec, "decode"))) { goto exit; } + /* Look up the codec functions */ + if (!(enc_tmp = PyCodec_Encoder(Bytes_AS_STRING(encname)))) { goto exit; } + if (!(dec_tmp = PyCodec_Decoder(Bytes_AS_STRING(encname)))) { goto exit; } /* success */ *pyenc = enc_tmp; enc_tmp = NULL; @@ -472,9 +470,6 @@ conn_get_python_codec(const char *encoding, exit: Py_XDECREF(enc_tmp); Py_XDECREF(dec_tmp); - Py_XDECREF(codec); - Py_XDECREF(f); - Py_XDECREF(m); Py_XDECREF(encname); PyMem_Free(pgenc); -- cgit v1.2.1