Merge PR #507: Add support for datetime objects to pluginStorage in python plugins

This commit is contained in:
jenkins 2022-05-03 23:27:03 +02:00
commit 1a06fabda2
3 changed files with 24 additions and 2 deletions

View File

@ -61,7 +61,6 @@ static int PyThingDescriptor_init(PyThingDescriptor *self, PyObject *args, PyObj
}
if (parentId) {
Py_INCREF(parentId);
qCritical() << "++++" << ThingId(PyUnicode_AsUTF8(parentId));
self->pyParentId = parentId;
}
if (params) {

View File

@ -2,9 +2,11 @@
#define PYUTILS_H
#include <Python.h>
#include <datetime.h>
#include <QLoggingCategory>
#include <QVariant>
#include <QDateTime>
Q_DECLARE_LOGGING_CATEGORY(dcPythonIntegrations)
@ -34,8 +36,17 @@ PyObject *QVariantToPyObject(const QVariant &value)
pyValue = Py_None;
Py_INCREF(pyValue);
break;
case QVariant::DateTime: {
PyObject *longObj = PyLong_FromLongLong(value.toDateTime().toMSecsSinceEpoch() / 1000);
PyObject *timeTuple = Py_BuildValue("(O)", longObj);
pyValue = PyDateTime_FromTimestamp(timeTuple);
Py_DECREF(longObj);
Py_DECREF(timeTuple);
break;
}
default:
qCWarning(dcPythonIntegrations()) << "Unhandled data type in conversion from Param to PyParam!";
Q_ASSERT_X(false, "pyutils.h", QString("Unhandled data type in converting QVariant to PyObject: %1").arg(value.type()).toUtf8());
qCWarning(dcPythonIntegrations()) << "Unhandled data type" << value.type() << "in conversion from Param to PyParam!";
pyValue = Py_None;
Py_INCREF(pyValue);
break;
@ -66,6 +77,15 @@ QVariant PyObjectToQVariant(PyObject *pyObject)
return QVariant(PyObject_IsTrue(pyObject));
}
if (qstrcmp(pyObject->ob_type->tp_name, "datetime.datetime") == 0) {
PyObject *timestampFunction = PyObject_GetAttrString(pyObject, "timestamp");
PyObject *timestampFunctionResult = PyObject_CallFunction(timestampFunction, nullptr);
QDateTime ret = QDateTime::fromMSecsSinceEpoch(PyLong_AsLongLong(timestampFunctionResult) * 1000);
Py_DECREF(timestampFunction);
Py_DECREF(timestampFunctionResult);
return ret;
}
Q_ASSERT_X(false, "pyutils.h", QString("Unhandled data type in converting PyObject to QVariant: %1").arg(pyObject->ob_type->tp_name).toUtf8());
qCWarning(dcPythonIntegrations()) << QString("Unhandled data type in converting PyObject to QVariant: %1").arg(pyObject->ob_type->tp_name).toUtf8();
return QVariant();

View File

@ -268,6 +268,9 @@ void PythonIntegrationPlugin::initPython()
Py_InitializeEx(0);
PyEval_InitThreads();
// Needs to be imported once to be able to use PyDateTime functions
PyDateTime_IMPORT;
// Store the main thread state and release the GIL
s_mainThreadState = PyEval_SaveThread();
}