0
|
1 /**
|
|
2 * Python plugin for Orthanc
|
|
3 * Copyright (C) 2017-2020 Osimis S.A., Belgium
|
|
4 *
|
|
5 * This program is free software: you can redistribute it and/or
|
|
6 * modify it under the terms of the GNU Affero General Public License
|
|
7 * as published by the Free Software Foundation, either version 3 of
|
|
8 * the License, or (at your option) any later version.
|
|
9 *
|
|
10 * This program is distributed in the hope that it will be useful, but
|
|
11 * WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
|
13 * Affero General Public License for more details.
|
|
14 *
|
|
15 * You should have received a copy of the GNU Affero General Public License
|
|
16 * along with this program. If not, see <http://www.gnu.org/licenses/>.
|
|
17 **/
|
|
18
|
|
19
|
|
20 #include "PythonFunction.h"
|
|
21
|
|
22 #include "PythonModule.h"
|
|
23
|
|
24 #include <OrthancPluginCppWrapper.h>
|
|
25
|
|
26
|
|
27 PythonObject* PythonFunction::CallUnchecked(PyObject* args)
|
|
28 {
|
|
29 if (!IsValid())
|
|
30 {
|
|
31 ORTHANC_PLUGINS_THROW_EXCEPTION(BadSequenceOfCalls);
|
|
32 }
|
|
33 else
|
|
34 {
|
|
35 PyObject* obj = PyObject_CallObject(func_->GetPyObject(), args);
|
|
36 return new PythonObject(lock_, obj);
|
|
37 }
|
|
38 }
|
|
39
|
|
40
|
|
41 PythonFunction::PythonFunction(PythonLock& lock,
|
|
42 PythonModule& module,
|
|
43 const std::string& name) :
|
|
44 lock_(lock)
|
|
45 {
|
|
46 if (module.IsValid() &&
|
|
47 // This check is necessary in Python 2.7, otherwise garbage collector might crash
|
|
48 PyObject_HasAttrString(module.GetPyObject(), name.c_str()))
|
|
49 {
|
|
50 func_.reset(module.GetObject().GetAttribute(name));
|
|
51
|
|
52 if (func_.get() == NULL ||
|
|
53 !func_->IsValid() ||
|
|
54 !PyCallable_Check(func_->GetPyObject()))
|
|
55 {
|
|
56 func_.reset(); // Not such a function
|
|
57 OrthancPlugins::LogWarning("Missing Python function: " + module.GetName() +
|
|
58 "." + name + "()");
|
|
59 }
|
|
60 }
|
|
61 }
|
|
62
|
|
63
|
|
64 PythonObject* PythonFunction::Call()
|
|
65 {
|
|
66 std::unique_ptr<PythonObject> result(CallUnchecked(NULL));
|
|
67
|
|
68 std::string error;
|
|
69 if (lock_.HasErrorOccurred(error))
|
|
70 {
|
|
71 OrthancPlugins::LogError("Python exception has occurred, traceback:\n" + error);
|
|
72 ORTHANC_PLUGINS_THROW_EXCEPTION(Plugin);
|
|
73 }
|
|
74 else
|
|
75 {
|
|
76 return result.release();
|
|
77 }
|
|
78 }
|
|
79
|
|
80
|
|
81 PythonObject* PythonFunction::Call(PythonObject& args)
|
|
82 {
|
|
83 std::unique_ptr<PythonObject> result(CallUnchecked(args.GetPyObject()));
|
|
84
|
|
85 std::string error;
|
|
86 if (lock_.HasErrorOccurred(error))
|
|
87 {
|
|
88 OrthancPlugins::LogError("Python exception has occurred, traceback:\n" + error);
|
|
89 ORTHANC_PLUGINS_THROW_EXCEPTION(Plugin);
|
|
90 }
|
|
91 else
|
|
92 {
|
|
93 return result.release();
|
|
94 }
|
|
95 }
|