mantisbase 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,86 @@
1
+ cmake_minimum_required(VERSION 3.22)
2
+ project(mantisbase-python LANGUAGES CXX)
3
+
4
+ set(CMAKE_CXX_STANDARD 20)
5
+ set(CMAKE_CXX_STANDARD_REQUIRED ON)
6
+
7
+ # When included from the parent CMakeLists.txt, nanobind may not be installed.
8
+ # Skip gracefully so the rest of the build can proceed.
9
+ find_package(Python 3.9 COMPONENTS Interpreter Development.Module QUIET)
10
+ if(NOT Python_FOUND)
11
+ message(STATUS "[mantisbase-python] Python >= 3.9 not found; skipping Python bindings.")
12
+ message(STATUS " Build via: pip install -e bindings/python")
13
+ return()
14
+ endif()
15
+
16
+ # CPython's Windows import library is an MSVC .lib. MinGW ld records data
17
+ # exports (Py_None and the rest) as functions, and loading the extension
18
+ # fails with "The specified procedure could not be found." The wheel job
19
+ # builds a GNU import library with gendef/dlltool and points here.
20
+ if(MINGW AND DEFINED ENV{PYTHON_MINGW_LIB})
21
+ set(_mb_pyimp "$ENV{PYTHON_MINGW_LIB}")
22
+ if(NOT EXISTS "${_mb_pyimp}")
23
+ message(FATAL_ERROR "PYTHON_MINGW_LIB does not exist: ${_mb_pyimp}")
24
+ endif()
25
+ foreach(_mb_cfg "" "_RELEASE" "_DEBUG" "_RELWITHDEBINFO" "_MINSIZEREL")
26
+ set_target_properties(Python::Module PROPERTIES
27
+ "IMPORTED_IMPLIB${_mb_cfg}" "${_mb_pyimp}")
28
+ endforeach()
29
+ endif()
30
+
31
+ # Locate nanobind via Python's package metadata
32
+ execute_process(
33
+ COMMAND "${Python_EXECUTABLE}" -m nanobind --cmake_dir
34
+ OUTPUT_VARIABLE nanobind_ROOT
35
+ OUTPUT_STRIP_TRAILING_WHITESPACE
36
+ RESULT_VARIABLE _nb_result
37
+ ERROR_QUIET
38
+ )
39
+ if(NOT _nb_result EQUAL 0)
40
+ message(STATUS "[mantisbase-python] nanobind not found; skipping Python bindings.")
41
+ message(STATUS " Install nanobind: pip install nanobind")
42
+ return()
43
+ endif()
44
+
45
+ find_package(nanobind CONFIG REQUIRED)
46
+
47
+ nanobind_add_module(mantisbase_python
48
+ src/module.cpp
49
+ src/app_bind.cpp
50
+ src/router_bind.cpp
51
+ src/request_bind.cpp
52
+ src/response_bind.cpp
53
+ src/db_bind.cpp
54
+ )
55
+
56
+ if(MINGW AND CMAKE_CXX_COMPILER_ID STREQUAL "GNU")
57
+ # nanobind compiles Release with -Os, which enables -fdeclone-ctor-dtor.
58
+ # GCC 16 then references a unified std::string constructor that MinGW's
59
+ # libstdc++-6.dll does not export (GCC PR 125359). LoadLibrary reports
60
+ # that as "The specified procedure could not be found."
61
+ # The flag must follow -Os; repeating it after nanobind_opt_size does that.
62
+ target_compile_options(mantisbase_python PRIVATE -fno-declone-ctor-dtor)
63
+ if(TARGET nanobind-static)
64
+ target_compile_options(nanobind-static PRIVATE -fno-declone-ctor-dtor)
65
+ endif()
66
+ # libmantisbase.dll is linked with --export-all-symbols, so its import
67
+ # library also advertises std:: instantiations. Resolving those from the
68
+ # engine DLL fails at load time. Bind libstdc++ first.
69
+ target_link_libraries(mantisbase_python PRIVATE stdc++)
70
+ endif()
71
+
72
+ # Link against mantisbase shared library
73
+ if(TARGET mb::shared)
74
+ target_link_libraries(mantisbase_python PRIVATE mb::shared)
75
+ else()
76
+ find_library(MANTISBASE_LIB mantisbase REQUIRED)
77
+ find_path(MANTISBASE_INCLUDE mantisbase/mantisbase.h REQUIRED)
78
+ target_link_libraries(mantisbase_python PRIVATE ${MANTISBASE_LIB})
79
+ target_include_directories(mantisbase_python PRIVATE ${MANTISBASE_INCLUDE})
80
+ endif()
81
+
82
+ set_target_properties(mantisbase_python PROPERTIES
83
+ OUTPUT_NAME "mantisbase"
84
+ )
85
+
86
+ install(TARGETS mantisbase_python LIBRARY DESTINATION .)
@@ -0,0 +1,121 @@
1
+ Metadata-Version: 2.4
2
+ Name: mantisbase
3
+ Version: 0.1.0
4
+ Summary: Python bindings for mantisbase – Flask-style HTTP server backed by a C++ engine
5
+ Author: Allan Koech
6
+ License-Expression: MIT
7
+ Classifier: Development Status :: 3 - Alpha
8
+ Classifier: Programming Language :: Python :: 3
9
+ Classifier: Programming Language :: C++
10
+ Classifier: Topic :: Internet :: WWW/HTTP :: HTTP Servers
11
+ Requires-Python: >=3.9
12
+ Description-Content-Type: text/markdown
13
+
14
+ # mantisbase (Python)
15
+
16
+ Python bindings for [mantisbase](https://github.com/allankoechke/mantisbase), a
17
+ C++20 single-binary backend-as-a-service. Import it like Flask and drive the
18
+ whole server from Python.
19
+
20
+ ```bash
21
+ pip install mantisbase
22
+ ```
23
+
24
+ ```python
25
+ import mantisbase
26
+
27
+ app = mantisbase.App(port=8080, data_dir="./data")
28
+
29
+
30
+ @app.router.get("/hello/{name}")
31
+ def hello(req, res):
32
+ res.json(200, {"message": f"Hello, {req.path_param('name')}!"})
33
+
34
+
35
+ @app.router.post("/items")
36
+ def create_item(req, res):
37
+ body = req.json()
38
+ rows = app.db.query("INSERT INTO items (name) VALUES (:name) RETURNING *",
39
+ {"name": body["name"]})
40
+ res.json(201, rows[0])
41
+
42
+
43
+ app.start() # blocks until stop() is called
44
+ ```
45
+
46
+ ## API
47
+
48
+ ### `App(**config)`
49
+
50
+ Keyword arguments mirror the CLI flags: `port`, `host`, `data_dir`, `db_type`,
51
+ `db_url`, `public_dir`, `scripts_dir`, `migrations_dir`, `pool_size`, `dev`,
52
+ `skip_admin_setup`. `secret_key` sets the `MB_JWT_SECRET` environment variable.
53
+
54
+ - `start(blocking=True)` — run the HTTP server. Pass `blocking=False` to run it
55
+ on a background thread.
56
+ - `stop()` — shut the server down.
57
+ - `router` / `db` — the `Router` and `Database` instances.
58
+
59
+ ### `Router`
60
+
61
+ `get(path, handler=None)`, `post(...)`, `patch(...)`, `delete(...)`. Called with
62
+ only a path they return a decorator, so both styles work:
63
+
64
+ ```python
65
+ app.router.get("/a", handler)
66
+
67
+ @app.router.get("/b")
68
+ def handler_b(req, res): ...
69
+ ```
70
+
71
+ ### `MantisRequest`
72
+
73
+ `path_param(name)`, `query_param(name)`, `header(name)`, `json()`, `body()`,
74
+ and the read-only properties `method`, `path`, `remote_addr`.
75
+
76
+ ### `MantisResponse`
77
+
78
+ `json(status, data)`, `html(status, body)`, `text(status, body)`,
79
+ `send(status, data, content_type)`, `redirect(url, status=302)`,
80
+ `set_header(name, value)`.
81
+
82
+ ### `Database`
83
+
84
+ `query(sql, *params)` where each param is a dict of named binds. Returns a list
85
+ of dicts keyed by column name. The GIL is released for the duration of the
86
+ query.
87
+
88
+ ## Threading
89
+
90
+ Route handlers are invoked from mantisbase's C++ worker threads, and the GIL is
91
+ acquired before each call. Python handlers therefore serialise against each
92
+ other — the same model as Flask's default threaded server.
93
+
94
+ ## Building from source
95
+
96
+ The bindings link the mantisbase shared library, so build and install it first
97
+ (`install` only runs on `cmake --install` — a plain build is not enough):
98
+
99
+ ```bash
100
+ cmake -B build -DMB_BUILD_SHARED_LIB=ON
101
+ cmake --build build
102
+ cmake --install build --prefix ./install
103
+ ```
104
+
105
+ Then point the standalone bindings build at that prefix:
106
+
107
+ ```bash
108
+ pip install -e bindings/python \
109
+ --config-settings=cmake.define.CMAKE_PREFIX_PATH=$PWD/install
110
+ ```
111
+
112
+ Requires CMake >= 3.22, a C++20 compiler, and `nanobind`/`scikit-build-core`
113
+ (fetched automatically via pip build isolation). At runtime the loader must
114
+ find `libmantisbase.so`, e.g. `export LD_LIBRARY_PATH=$PWD/install/lib`.
115
+
116
+ To produce a distributable wheel instead, see `.github/workflows/bindings-python.yml`
117
+ (engine install → `pip wheel` → `auditwheel`/`delocate`/`delvewheel` repair).
118
+
119
+ ## License
120
+
121
+ MIT
@@ -0,0 +1,108 @@
1
+ # mantisbase (Python)
2
+
3
+ Python bindings for [mantisbase](https://github.com/allankoechke/mantisbase), a
4
+ C++20 single-binary backend-as-a-service. Import it like Flask and drive the
5
+ whole server from Python.
6
+
7
+ ```bash
8
+ pip install mantisbase
9
+ ```
10
+
11
+ ```python
12
+ import mantisbase
13
+
14
+ app = mantisbase.App(port=8080, data_dir="./data")
15
+
16
+
17
+ @app.router.get("/hello/{name}")
18
+ def hello(req, res):
19
+ res.json(200, {"message": f"Hello, {req.path_param('name')}!"})
20
+
21
+
22
+ @app.router.post("/items")
23
+ def create_item(req, res):
24
+ body = req.json()
25
+ rows = app.db.query("INSERT INTO items (name) VALUES (:name) RETURNING *",
26
+ {"name": body["name"]})
27
+ res.json(201, rows[0])
28
+
29
+
30
+ app.start() # blocks until stop() is called
31
+ ```
32
+
33
+ ## API
34
+
35
+ ### `App(**config)`
36
+
37
+ Keyword arguments mirror the CLI flags: `port`, `host`, `data_dir`, `db_type`,
38
+ `db_url`, `public_dir`, `scripts_dir`, `migrations_dir`, `pool_size`, `dev`,
39
+ `skip_admin_setup`. `secret_key` sets the `MB_JWT_SECRET` environment variable.
40
+
41
+ - `start(blocking=True)` — run the HTTP server. Pass `blocking=False` to run it
42
+ on a background thread.
43
+ - `stop()` — shut the server down.
44
+ - `router` / `db` — the `Router` and `Database` instances.
45
+
46
+ ### `Router`
47
+
48
+ `get(path, handler=None)`, `post(...)`, `patch(...)`, `delete(...)`. Called with
49
+ only a path they return a decorator, so both styles work:
50
+
51
+ ```python
52
+ app.router.get("/a", handler)
53
+
54
+ @app.router.get("/b")
55
+ def handler_b(req, res): ...
56
+ ```
57
+
58
+ ### `MantisRequest`
59
+
60
+ `path_param(name)`, `query_param(name)`, `header(name)`, `json()`, `body()`,
61
+ and the read-only properties `method`, `path`, `remote_addr`.
62
+
63
+ ### `MantisResponse`
64
+
65
+ `json(status, data)`, `html(status, body)`, `text(status, body)`,
66
+ `send(status, data, content_type)`, `redirect(url, status=302)`,
67
+ `set_header(name, value)`.
68
+
69
+ ### `Database`
70
+
71
+ `query(sql, *params)` where each param is a dict of named binds. Returns a list
72
+ of dicts keyed by column name. The GIL is released for the duration of the
73
+ query.
74
+
75
+ ## Threading
76
+
77
+ Route handlers are invoked from mantisbase's C++ worker threads, and the GIL is
78
+ acquired before each call. Python handlers therefore serialise against each
79
+ other — the same model as Flask's default threaded server.
80
+
81
+ ## Building from source
82
+
83
+ The bindings link the mantisbase shared library, so build and install it first
84
+ (`install` only runs on `cmake --install` — a plain build is not enough):
85
+
86
+ ```bash
87
+ cmake -B build -DMB_BUILD_SHARED_LIB=ON
88
+ cmake --build build
89
+ cmake --install build --prefix ./install
90
+ ```
91
+
92
+ Then point the standalone bindings build at that prefix:
93
+
94
+ ```bash
95
+ pip install -e bindings/python \
96
+ --config-settings=cmake.define.CMAKE_PREFIX_PATH=$PWD/install
97
+ ```
98
+
99
+ Requires CMake >= 3.22, a C++20 compiler, and `nanobind`/`scikit-build-core`
100
+ (fetched automatically via pip build isolation). At runtime the loader must
101
+ find `libmantisbase.so`, e.g. `export LD_LIBRARY_PATH=$PWD/install/lib`.
102
+
103
+ To produce a distributable wheel instead, see `.github/workflows/bindings-python.yml`
104
+ (engine install → `pip wheel` → `auditwheel`/`delocate`/`delvewheel` repair).
105
+
106
+ ## License
107
+
108
+ MIT
@@ -0,0 +1,8 @@
1
+ //
2
+ // Created by codeart on 14/10/2026.
3
+ //
4
+
5
+ #ifndef MANTISBASE_MANTISBASE_PY_H
6
+ #define MANTISBASE_MANTISBASE_PY_H
7
+
8
+ #endif //MANTISBASE_MANTISBASE_PY_H
@@ -0,0 +1,22 @@
1
+ [build-system]
2
+ requires = ["scikit-build-core>=0.10", "nanobind>=2.0"]
3
+ build-backend = "scikit_build_core.build"
4
+
5
+ [project]
6
+ name = "mantisbase"
7
+ version = "0.1.0"
8
+ description = "Python bindings for mantisbase – Flask-style HTTP server backed by a C++ engine"
9
+ readme = "README.md"
10
+ license = "MIT"
11
+ requires-python = ">=3.9"
12
+ authors = [{ name = "Allan Koech" }]
13
+ classifiers = [
14
+ "Development Status :: 3 - Alpha",
15
+ "Programming Language :: Python :: 3",
16
+ "Programming Language :: C++",
17
+ "Topic :: Internet :: WWW/HTTP :: HTTP Servers",
18
+ ]
19
+
20
+ [tool.scikit-build]
21
+ cmake.build-type = "Release"
22
+ wheel.packages = []
@@ -0,0 +1,115 @@
1
+ #include <nanobind/nanobind.h>
2
+ #include <nanobind/stl/string.h>
3
+ #include <mantisbase/mantisbase.h>
4
+ #include <nlohmann/json.hpp>
5
+ #include <thread>
6
+ #include <atomic>
7
+ #include <memory>
8
+ #include <cstdlib>
9
+
10
+ namespace nb = nanobind;
11
+ using json = nlohmann::json;
12
+
13
+ namespace {
14
+ class PyApp {
15
+ public:
16
+ explicit PyApp(const nb::kwargs& kwargs) {
17
+ json config = json::object();
18
+ config["serve"] = json::object();
19
+
20
+ if (kwargs.contains("port"))
21
+ config["serve"]["port"] = nb::cast<int>(kwargs["port"]);
22
+ if (kwargs.contains("host"))
23
+ config["serve"]["host"] = nb::cast<std::string>(kwargs["host"]);
24
+ if (kwargs.contains("data_dir"))
25
+ config["data-dir"] = nb::cast<std::string>(kwargs["data_dir"]);
26
+ if (kwargs.contains("db_type"))
27
+ config["db"] = nb::cast<std::string>(kwargs["db_type"]);
28
+ if (kwargs.contains("db_url"))
29
+ config["db_url"] = nb::cast<std::string>(kwargs["db_url"]);
30
+ if (kwargs.contains("public_dir"))
31
+ config["public-dir"] = nb::cast<std::string>(kwargs["public_dir"]);
32
+ if (kwargs.contains("scripts_dir"))
33
+ config["scripts-dir"] = nb::cast<std::string>(kwargs["scripts_dir"]);
34
+ if (kwargs.contains("migrations_dir"))
35
+ config["migrations-dir"] = nb::cast<std::string>(kwargs["migrations_dir"]);
36
+ if (kwargs.contains("pool_size"))
37
+ config["serve"]["pool-size"] = nb::cast<int>(kwargs["pool_size"]);
38
+ // `dev` is a presence-only flag in MantisBase::create() -- only add the
39
+ // key when the caller actually asked for dev mode.
40
+ if (kwargs.contains("dev") && nb::cast<bool>(kwargs["dev"]))
41
+ config["dev"] = true;
42
+ if (kwargs.contains("skip_admin_setup"))
43
+ config["serve"]["skip-admin-setup"] = nb::cast<bool>(kwargs["skip_admin_setup"]);
44
+
45
+ // MantisBase reads the JWT signing key from the environment, so there is
46
+ // no CLI/config equivalent to forward it through.
47
+ if (kwargs.contains("secret_key")) {
48
+ const auto secret = nb::cast<std::string>(kwargs["secret_key"]);
49
+ #ifdef _WIN32
50
+ _putenv_s("MB_JWT_SECRET", secret.c_str());
51
+ #else
52
+ ::setenv("MB_JWT_SECRET", secret.c_str(), 1);
53
+ #endif
54
+ }
55
+
56
+ m_app = mb::MantisBase::create(config);
57
+ if (!m_app)
58
+ throw std::runtime_error("Failed to create MantisBase instance");
59
+ }
60
+
61
+ ~PyApp() {
62
+ if (m_running.load()) {
63
+ m_app->close();
64
+ if (m_serverThread.joinable())
65
+ m_serverThread.join();
66
+ }
67
+ }
68
+
69
+ void start(const bool blocking) {
70
+ if (m_running.load())
71
+ return;
72
+
73
+ m_running.store(true);
74
+
75
+ if (blocking) {
76
+ nb::gil_scoped_release release;
77
+ [[maybe_unused]] auto ret = m_app->run();
78
+ m_running.store(false);
79
+ } else {
80
+ m_serverThread = std::thread([this]() {
81
+ [[maybe_unused]] auto ret = m_app->run();
82
+ m_running.store(false);
83
+ });
84
+ }
85
+ }
86
+
87
+ void stop() {
88
+ if (!m_running.load())
89
+ return;
90
+
91
+ m_app->close();
92
+ if (m_serverThread.joinable())
93
+ m_serverThread.join();
94
+ m_running.store(false);
95
+ }
96
+
97
+ [[nodiscard]] mb::MbRouter& router() const { return m_app->router(); }
98
+ [[nodiscard]] mb::MbDatabase& db() const { return m_app->db(); }
99
+ [[nodiscard]] mb::MantisBase& app() const { return *m_app; }
100
+
101
+ private:
102
+ std::unique_ptr<mb::MantisBase> m_app;
103
+ std::thread m_serverThread;
104
+ std::atomic<bool> m_running{false};
105
+ };
106
+ }
107
+
108
+ void register_app(const nb::module_& m) {
109
+ nb::class_<PyApp>(m, "App")
110
+ .def(nb::init<nb::kwargs>())
111
+ .def("start", &PyApp::start, nb::arg("blocking") = true)
112
+ .def("stop", &PyApp::stop)
113
+ .def_prop_ro("router", &PyApp::router, nb::rv_policy::reference_internal)
114
+ .def_prop_ro("db", &PyApp::db, nb::rv_policy::reference_internal);
115
+ }
@@ -0,0 +1,144 @@
1
+ #include <nanobind/nanobind.h>
2
+ #include <nanobind/stl/string.h>
3
+ #include <mantisbase/core/database.h>
4
+ #include <soci/soci.h>
5
+ #include <nlohmann/json.hpp>
6
+
7
+ namespace nb = nanobind;
8
+ using json = nlohmann::json;
9
+
10
+ static nb::object json_to_python(const json &j) {
11
+ if (j.is_null()) return nb::none();
12
+ if (j.is_boolean()) return nb::cast(j.get<bool>());
13
+ if (j.is_number_integer()) return nb::cast(j.get<int64_t>());
14
+ if (j.is_number_float()) return nb::cast(j.get<double>());
15
+ if (j.is_string()) return nb::cast(j.get<std::string>());
16
+ if (j.is_array()) {
17
+ nb::list lst;
18
+ for (const auto &elem: j)
19
+ lst.append(json_to_python(elem));
20
+ return lst;
21
+ }
22
+ if (j.is_object()) {
23
+ nb::dict d;
24
+ for (auto it = j.begin(); it != j.end(); ++it)
25
+ d[nb::cast(it.key())] = json_to_python(it.value());
26
+ return d;
27
+ }
28
+ return nb::none();
29
+ }
30
+
31
+ static json soci_row_to_json(const soci::row &row) {
32
+ json obj = json::object();
33
+ for (size_t i = 0; i < row.size(); ++i) {
34
+ const auto &props = row.get_properties(i);
35
+ const std::string &name = props.get_name();
36
+
37
+ if (row.get_indicator(i) == soci::i_null) {
38
+ obj[name] = nullptr;
39
+ continue;
40
+ }
41
+
42
+ switch (props.get_db_type()) {
43
+ case soci::db_string:
44
+ case soci::db_xml:
45
+ obj[name] = row.get<std::string>(i);
46
+ break;
47
+ case soci::db_double:
48
+ obj[name] = row.get<double>(i);
49
+ break;
50
+ case soci::db_int8:
51
+ obj[name] = static_cast<int64_t>(row.get<int8_t>(i));
52
+ break;
53
+ case soci::db_uint8:
54
+ obj[name] = static_cast<int64_t>(row.get<uint8_t>(i));
55
+ break;
56
+ case soci::db_int16:
57
+ obj[name] = static_cast<int64_t>(row.get<int16_t>(i));
58
+ break;
59
+ case soci::db_uint16:
60
+ obj[name] = static_cast<int64_t>(row.get<uint16_t>(i));
61
+ break;
62
+ case soci::db_int32:
63
+ obj[name] = static_cast<int64_t>(row.get<int32_t>(i));
64
+ break;
65
+ case soci::db_uint32:
66
+ obj[name] = static_cast<int64_t>(row.get<uint32_t>(i));
67
+ break;
68
+ case soci::db_int64:
69
+ obj[name] = static_cast<int64_t>(row.get<int64_t>(i));
70
+ break;
71
+ case soci::db_uint64:
72
+ obj[name] = static_cast<int64_t>(row.get<uint64_t>(i));
73
+ break;
74
+ case soci::db_date: {
75
+ auto t = row.get<std::tm>(i);
76
+ char buf[32];
77
+ std::strftime(buf, sizeof(buf), "%Y-%m-%dT%H:%M:%S", &t);
78
+ obj[name] = std::string(buf);
79
+ break;
80
+ }
81
+ default:
82
+ obj[name] = row.get<std::string>(i);
83
+ break;
84
+ }
85
+ }
86
+ return obj;
87
+ }
88
+
89
+ void register_db(const nb::module_ &m) {
90
+ nb::class_<mb::MbDatabase>(m, "MbDatabase")
91
+ .def("query", [](mb::MbDatabase &self, const std::string &sql, const nb::args &params) -> nb::list {
92
+ soci::values binds;
93
+ bool has_binds = false;
94
+
95
+ for (auto &&param_i: params) {
96
+ nb::handle param = param_i;
97
+ if (!nb::isinstance<nb::dict>(param))
98
+ throw nb::type_error("Bind parameters must be dicts");
99
+
100
+ has_binds = true;
101
+ auto d = nb::cast<nb::dict>(param);
102
+ for (auto [key_handle, val]: d) {
103
+ auto key = nb::cast<std::string>(key_handle);
104
+
105
+ if (val.is_none()) {
106
+ std::optional<int> null_val;
107
+ binds.set(key, null_val, soci::i_null);
108
+ } else if (nb::isinstance<nb::str>(val)) {
109
+ binds.set(key, nb::cast<std::string>(val));
110
+ } else if (nb::isinstance<nb::bool_>(val)) {
111
+ binds.set(key, nb::cast<bool>(val));
112
+ } else if (nb::isinstance<nb::int_>(val)) {
113
+ binds.set(key, nb::cast<int>(val));
114
+ } else if (nb::isinstance<nb::float_>(val)) {
115
+ binds.set(key, nb::cast<double>(val));
116
+ }
117
+ }
118
+ }
119
+
120
+ json results;
121
+ {
122
+ nb::gil_scoped_release release;
123
+ auto session = self.session();
124
+
125
+ soci::row data_row;
126
+ soci::statement st = has_binds
127
+ ? (session->prepare << sql, soci::use(binds), soci::into(data_row))
128
+ : (session->prepare << sql, soci::into(data_row));
129
+ st.execute();
130
+
131
+ results = json::array();
132
+ while (st.fetch()) {
133
+ results.push_back(soci_row_to_json(data_row));
134
+ }
135
+ }
136
+
137
+ nb::list py_results;
138
+ for (const auto &row: results) {
139
+ py_results.append(json_to_python(row));
140
+ }
141
+ return py_results;
142
+ }, nb::arg("sql"), nb::arg("params"))
143
+ .def_prop_ro("connected", &mb::MbDatabase::isConnected);
144
+ }
@@ -0,0 +1,19 @@
1
+ #include <nanobind/nanobind.h>
2
+
3
+ namespace nb = nanobind;
4
+
5
+ void register_app(const nb::module_& m);
6
+ void register_router(nb::module_& m);
7
+ void register_request(const nb::module_& m);
8
+ void register_response(nb::module_& m);
9
+ void register_db(const nb::module_& m);
10
+
11
+ NB_MODULE(mantisbase, m) {
12
+ m.doc() = "Python bindings for mantisbase – Flask-style HTTP server backed by a C++ engine";
13
+
14
+ register_app(m);
15
+ register_router(m);
16
+ register_request(m);
17
+ register_response(m);
18
+ register_db(m);
19
+ }
@@ -0,0 +1,65 @@
1
+ #include <nanobind/nanobind.h>
2
+ #include <nanobind/stl/string.h>
3
+ #include <mantisbase/core/http.h>
4
+ #include <nlohmann/json.hpp>
5
+
6
+ namespace nb = nanobind;
7
+ using json = nlohmann::json;
8
+
9
+ static nb::object json_to_python(const json &j) {
10
+ if (j.is_null()) return nb::none();
11
+ if (j.is_boolean()) return nb::cast(j.get<bool>());
12
+ if (j.is_number_integer()) return nb::cast(j.get<int64_t>());
13
+ if (j.is_number_float()) return nb::cast(j.get<double>());
14
+ if (j.is_string()) return nb::cast(j.get<std::string>());
15
+ if (j.is_array()) {
16
+ nb::list lst;
17
+ for (const auto &elem: j)
18
+ lst.append(json_to_python(elem));
19
+ return lst;
20
+ }
21
+ if (j.is_object()) {
22
+ nb::dict d;
23
+ for (auto it = j.begin(); it != j.end(); ++it)
24
+ d[nb::cast(it.key())] = json_to_python(it.value());
25
+ return d;
26
+ }
27
+ return nb::none();
28
+ }
29
+
30
+ void register_request(const nb::module_ &m) {
31
+ nb::class_<mb::MbRequest>(m, "MbRequest")
32
+ .def("path_param", [](const mb::MbRequest &self, const std::string &name) {
33
+ return self.pathParamValue(name);
34
+ }, nb::arg("name"))
35
+ .def("has_path_params", [](const mb::MbRequest &self) {
36
+ return self.hasPathParams();
37
+ })
38
+ .def("has_path_param", [](const mb::MbRequest &self, const std::string &name) {
39
+ return self.hasPathParam(name);
40
+ }, nb::arg("name"))
41
+ .def("query_param", [](const mb::MbRequest &self, const std::string &name) {
42
+ return self.queryParamValue(name);
43
+ }, nb::arg("name"))
44
+ .def("header", [](const mb::MbRequest &self, const std::string &name) {
45
+ return self.headerValue(name);
46
+ }, nb::arg("name"))
47
+ .def("hasHeader", [](const mb::MbRequest &self, const std::string &name) {
48
+ return self.hasHeader(name);
49
+ }, nb::arg("name"))
50
+ .def("body", &mb::MbRequest::body)
51
+ .def("json", [](const mb::MbRequest &self) -> nb::object {
52
+ try {
53
+ const json j = self.jsonBody();
54
+ return json_to_python(j);
55
+ } catch (const std::exception &e) {
56
+ throw nb::value_error(e.what());
57
+ }
58
+ })
59
+ .def_prop_ro("method", &mb::MbRequest::method)
60
+ .def_prop_ro("path", &mb::MbRequest::path)
61
+ .def_prop_ro("remote_addr", &mb::MbRequest::remoteAddr)
62
+ .def_prop_ro("remote_port", &mb::MbRequest::remotePort)
63
+ .def_prop_ro("local_addr", &mb::MbRequest::localAddr)
64
+ .def_prop_ro("local_port", &mb::MbRequest::localPort);
65
+ }
@@ -0,0 +1,43 @@
1
+ #include <nanobind/nanobind.h>
2
+ #include <nanobind/stl/string.h>
3
+ #include <mantisbase/core/http.h>
4
+ #include <nlohmann/json.hpp>
5
+
6
+ namespace nb = nanobind;
7
+ using json = nlohmann::json;
8
+
9
+ static json python_to_json(const nb::handle obj) {
10
+ if (obj.is_none()) return nullptr;
11
+ if (nb::isinstance<nb::bool_>(obj)) return nb::cast<bool>(obj);
12
+ if (nb::isinstance<nb::int_>(obj)) return nb::cast<int64_t>(obj);
13
+ if (nb::isinstance<nb::float_>(obj)) return nb::cast<double>(obj);
14
+ if (nb::isinstance<nb::str>(obj)) return nb::cast<std::string>(obj);
15
+ if (nb::isinstance<nb::list>(obj)) {
16
+ json arr = json::array();
17
+ for (const auto item : obj)
18
+ arr.push_back(python_to_json(item));
19
+ return arr;
20
+ }
21
+ if (nb::isinstance<nb::dict>(obj)) {
22
+ json d = json::object();
23
+ for (auto item : nb::cast<nb::dict>(obj))
24
+ d[nb::cast<std::string>(item.first)] = python_to_json(item.second);
25
+ return d;
26
+ }
27
+ return nullptr;
28
+ }
29
+
30
+ void register_response(nb::module_& m) {
31
+ nb::class_<mb::MbResponse>(m, "MbResponse")
32
+ .def("json", [](const mb::MbResponse& self, const int status, const nb::handle data) {
33
+ self.sendJSON(status, python_to_json(data));
34
+ }, nb::arg("status"), nb::arg("data"))
35
+ .def("html", &mb::MbResponse::sendHtml, nb::arg("status"), nb::arg("body"))
36
+ .def("text", &mb::MbResponse::sendText, nb::arg("status"), nb::arg("body"))
37
+ .def("send", &mb::MbResponse::send,
38
+ nb::arg("status"), nb::arg("data") = "", nb::arg("content_type") = "text/plain")
39
+ .def("redirect", &mb::MbResponse::setRedirect,
40
+ nb::arg("url"), nb::arg("status") = 302)
41
+ .def("set_header", &mb::MbResponse::setHeader,
42
+ nb::arg("name"), nb::arg("value"));
43
+ }
@@ -0,0 +1,57 @@
1
+ #include <nanobind/nanobind.h>
2
+ #include <nanobind/stl/string.h>
3
+ #include <mantisbase/core/router.h>
4
+ #include <mantisbase/core/http.h>
5
+ #include <mantisbase/core/types.h>
6
+
7
+ namespace nb = nanobind;
8
+
9
+ using RegisterMethod = void(mb::MbRouter::*)(const std::string&, const mb::MbHandlerFn&, const mb::MbMiddlewares&);
10
+
11
+ static void register_route(mb::MbRouter& router, const std::string& path,
12
+ const nb::callable &handler, const RegisterMethod method) {
13
+ nb::callable stored_handler(handler);
14
+
15
+ const mb::MbHandlerFn fn = [stored_handler](mb::MbRequest& req, mb::MbResponse& res) {
16
+ nb::gil_scoped_acquire gil;
17
+ try {
18
+ stored_handler(&req, &res);
19
+ } catch (nb::python_error& e) {
20
+ e.restore();
21
+ }
22
+ };
23
+
24
+ (router.*method)(path, fn, {});
25
+ }
26
+
27
+ static nb::object make_route_method(mb::MbRouter& router, const std::string& path,
28
+ nb::object handler_or_none, RegisterMethod method) {
29
+ if (!handler_or_none.is_none()) {
30
+ register_route(router, path, nb::callable(handler_or_none, nb::detail::borrow_t{}), method);
31
+ return handler_or_none;
32
+ }
33
+
34
+ mb::MbRouter* router_ptr = &router;
35
+ return nb::cpp_function([router_ptr, path, method](nb::callable handler) -> nb::callable {
36
+ register_route(*router_ptr, path, handler, method);
37
+ return handler;
38
+ });
39
+ }
40
+
41
+ void register_router(nb::module_& m) {
42
+ nb::class_<mb::MbRouter>(m, "MbRouter")
43
+ .def("get", [](mb::MbRouter& self, const std::string& path, nb::object handler) {
44
+ return make_route_method(self, path, handler, &mb::MbRouter::Get);
45
+ }, nb::arg("path"), nb::arg("handler") = nb::none())
46
+ .def("post", [](mb::MbRouter& self, const std::string& path, nb::object handler) {
47
+ return make_route_method(self, path, handler,
48
+ static_cast<RegisterMethod>(&mb::MbRouter::Post));
49
+ }, nb::arg("path"), nb::arg("handler") = nb::none())
50
+ .def("patch", [](mb::MbRouter& self, const std::string& path, nb::object handler) {
51
+ return make_route_method(self, path, handler,
52
+ static_cast<RegisterMethod>(&mb::MbRouter::Patch));
53
+ }, nb::arg("path"), nb::arg("handler") = nb::none())
54
+ .def("delete", [](mb::MbRouter& self, const std::string& path, nb::object handler) {
55
+ return make_route_method(self, path, handler, &mb::MbRouter::Delete);
56
+ }, nb::arg("path"), nb::arg("handler") = nb::none());
57
+ }