Skip to content

Commit cb5293b

Browse files
committed
Use the proper API functions to look up codec functions
1 parent 3295beb commit cb5293b

File tree

2 files changed

+8
-11
lines changed

2 files changed

+8
-11
lines changed

psycopg/connection.h

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -122,9 +122,11 @@ struct connectionObject {
122122

123123
PyObject *cursor_factory; /* default cursor factory from cursor() */
124124

125-
/* Pointer to a decoding function, e.g. PyUnicode_DecodeUTF8 */
125+
/* Optional pointer to a decoding C function, e.g. PyUnicode_DecodeUTF8 */
126126
PyObject *(*cdecoder)(const char *, Py_ssize_t, const char *);
127127

128+
/* Pointers to python encoding/decoding functions, e.g.
129+
* codecs.getdecoder('utf8') */
128130
PyObject *pyencoder; /* python codec encoding function */
129131
PyObject *pydecoder; /* python codec decoding function */
130132
};

psycopg/connection_int.c

Lines changed: 5 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -451,17 +451,15 @@ conn_get_python_codec(const char *encoding,
451451
int rv = -1;
452452
char *pgenc = NULL;
453453
PyObject *encname = NULL;
454-
PyObject *m = NULL, *f = NULL, *codec = NULL;
455454
PyObject *enc_tmp = NULL, *dec_tmp = NULL;
456455

456+
/* get the Python name of the encoding as a C string */
457457
if (!(encname = conn_pgenc_to_pyenc(encoding, &pgenc))) { goto exit; }
458+
if (!(encname = psycopg_ensure_bytes(encname))) { goto exit; }
458459

459-
/* Look up the python codec */
460-
if (!(m = PyImport_ImportModule("codecs"))) { goto exit; }
461-
if (!(f = PyObject_GetAttrString(m, "lookup"))) { goto exit; }
462-
if (!(codec = PyObject_CallFunctionObjArgs(f, encname, NULL))) { goto exit; }
463-
if (!(enc_tmp = PyObject_GetAttrString(codec, "encode"))) { goto exit; }
464-
if (!(dec_tmp = PyObject_GetAttrString(codec, "decode"))) { goto exit; }
460+
/* Look up the codec functions */
461+
if (!(enc_tmp = PyCodec_Encoder(Bytes_AS_STRING(encname)))) { goto exit; }
462+
if (!(dec_tmp = PyCodec_Decoder(Bytes_AS_STRING(encname)))) { goto exit; }
465463

466464
/* success */
467465
*pyenc = enc_tmp; enc_tmp = NULL;
@@ -472,9 +470,6 @@ conn_get_python_codec(const char *encoding,
472470
exit:
473471
Py_XDECREF(enc_tmp);
474472
Py_XDECREF(dec_tmp);
475-
Py_XDECREF(codec);
476-
Py_XDECREF(f);
477-
Py_XDECREF(m);
478473
Py_XDECREF(encname);
479474
PyMem_Free(pgenc);
480475

0 commit comments

Comments
 (0)