mirror of
https://github.com/psycopg/psycopg2.git
synced 2024-11-26 19:03:43 +03:00
Added utility function to convert bytes to string in Python 3.
This commit is contained in:
parent
d3f3f1caf0
commit
2e22eef727
|
@ -122,6 +122,7 @@ HIDDEN char *psycopg_escape_string(PyObject *conn,
|
|||
|
||||
HIDDEN char *psycopg_strdup(const char *from, Py_ssize_t len);
|
||||
HIDDEN PyObject * psycopg_ensure_bytes(PyObject *obj);
|
||||
HIDDEN PyObject * psycopg_ensure_text(PyObject *obj);
|
||||
|
||||
/* Exceptions docstrings */
|
||||
#define Error_doc \
|
||||
|
|
|
@ -118,3 +118,27 @@ psycopg_ensure_bytes(PyObject *obj)
|
|||
return rv;
|
||||
}
|
||||
|
||||
/* Take a Python object and return text from it.
|
||||
*
|
||||
* On Py3 this means converting bytes to unicode. On Py2 bytes are fine.
|
||||
*
|
||||
* The function is ref neutral: steals a ref from obj and adds one to the
|
||||
* return value. It is safe to call it on NULL.
|
||||
*/
|
||||
PyObject *
|
||||
psycopg_ensure_text(PyObject *obj)
|
||||
{
|
||||
#if PY_MAJOR_VERSION < 3
|
||||
return obj;
|
||||
#else
|
||||
if (obj) {
|
||||
/* bytes to unicode in Py3 */
|
||||
PyObject *rv = PyUnicode_FromEncodedObject(obj, "utf8", "replace");
|
||||
Py_DECREF(obj);
|
||||
return rv;
|
||||
}
|
||||
else {
|
||||
return NULL;
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
|
Loading…
Reference in New Issue
Block a user