From a9787663ede02deb665ed7dada982d47794caae1 Mon Sep 17 00:00:00 2001
From: FITAHIANA Nomeniavo Joe <24nomeniavo@gmail.com>
Date: Wed, 4 Nov 2026 20:00:36 +0300
Subject: [PATCH 1/5] chore: bump version to v0.11.6
---
Cargo.lock | 2 +-
Cargo.toml | 2 +-
README.md | 2 +-
3 files changed, 3 insertions(+), 3 deletions(-)
diff --git a/Cargo.lock b/Cargo.lock
index 1665bf8..228137d 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -1356,7 +1356,7 @@ checksum = "1a80800c0488c3a21695ea981a54918fbb37abf04f4d0720c453632255e2ff0e"
[[package]]
name = "oxapy"
-version = "0.11.5"
+version = "0.11.6"
dependencies = [
"ahash",
"ctrlc",
diff --git a/Cargo.toml b/Cargo.toml
index c39f832..c58b725 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -1,6 +1,6 @@
[package]
name = "oxapy"
-version = "0.11.5"
+version = "0.11.6"
edition = "2024"
authors = ["FITAHIANA Nomeniavo Joe <24nomeniavo@gmail.com>"]
repository = "https://github.com/j03-dev/oxapy"
diff --git a/README.md b/README.md
index 784243b..c49d1f3 100644
--- a/README.md
+++ b/README.md
@@ -9,7 +9,7 @@
OxAPY is Python HTTP server library build in Rust - a fast, safe and featureementation.
-
+
From 5e0b2a8e0627e91d750335fa0e58dc526236bbf9 Mon Sep 17 00:00:00 2001
From: FITAHIANA Nomeniavo Joe <24nomeniavo@gmail.com>
Date: Wed, 4 Nov 2026 20:43:26 +0300
Subject: [PATCH 2/5] chore: maximum thread
---
src/lib.rs | 159 +++++++++++++++++++++++++++++++++++++++++++----------
1 file changed, 129 insertions(+), 30 deletions(-)
diff --git a/src/lib.rs b/src/lib.rs
index 4b42631..6237f55 100644
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -85,7 +85,7 @@ impl ShutDownSignal {
ctrlc::set_handler(move || {
println!("\nShutting Down...");
running.store(false, Ordering::SeqCst);
- let _ = block_on(tx.send(()), None);
+ let _ = block_on(tx.send(()), None, 1);
})
.into_py_exception()?;
Ok(Self { rx })
@@ -149,6 +149,7 @@ struct HttpServer {
app_data: Option>>,
wrapper: Option>>,
channel_capacity: usize,
+ handler_threads: usize,
cors: Option>,
is_async: bool,
routers: Vec>,
@@ -208,6 +209,7 @@ impl HttpServer {
app_data: None,
wrapper: None,
channel_capacity: 100,
+ handler_threads: 1,
cors: None,
is_async: false,
routers: Vec::new(),
@@ -367,6 +369,31 @@ impl HttpServer {
slf
}
+ /// Set the number of OS threads used to execute synchronous handlers.
+ ///
+ /// By default synchronous handlers run one at a time on a single thread.
+ /// Raising this value lets handlers overlap blocking work (database
+ /// drivers, file I/O, network calls) that releases the GIL. It does not
+ /// bypass the GIL: pure-Python CPU-bound work still needs ``processes=N``.
+ ///
+ /// This option only affects sync mode; async handlers are unaffected.
+ /// Values below ``1`` are treated as ``1``.
+ ///
+ /// Args:
+ /// handler_threads (int): Number of handler threads (default 1).
+ ///
+ /// Returns:
+ /// Self
+ ///
+ /// Example:
+ /// ```python
+ /// server.handler_threads(8)
+ /// ```
+ fn handler_threads(mut slf: PyRefMut<'_, Self>, handler_threads: usize) -> PyRefMut<'_, Self> {
+ slf.handler_threads = handler_threads.max(1);
+ slf
+ }
+
/// Add a global wrapper (middleware) to the server.
///
/// The wrapper is invoked with `(request, response)` after every handler.
@@ -458,10 +485,11 @@ impl HttpServer {
#[pyo3(signature=(workers=None))]
fn run<'py>(&self, workers: Option, py: Python<'py>) -> PyResult> {
let server = self.clone();
+ let handler_threads = self.handler_threads;
if self.is_async {
future_into_py(py, async move { server.run_server().await })
} else {
- py.detach(move || block_on(server.run_server(), workers))?;
+ py.detach(move || block_on(server.run_server(), workers, handler_threads))?;
Ok(py.None().into_bound(py))
}
}
@@ -562,6 +590,11 @@ impl HttpServer {
) -> PyResult<()> {
let mut batch = Vec::with_capacity(64);
let mut tasks = JoinSet::new();
+ let sync_semaphore = if locals.is_none() && self.handler_threads > 1 {
+ Some(Arc::new(Semaphore::new(self.handler_threads)))
+ } else {
+ None
+ };
loop {
batch.clear();
tokio::select! {
@@ -573,8 +606,14 @@ impl HttpServer {
if let Some(ref local) = locals {
let local = local.clone();
tasks.spawn(async move { scope(local, pr.respond(true)).await});
+ } else if let Some(ref semaphore) = sync_semaphore {
+ let permit = semaphore.clone().acquire_owned().await.unwrap();
+ tasks.spawn_blocking(move || {
+ let _permit = permit;
+ pr.respond_sync();
+ });
} else {
- pr.respond(false).await;
+ pr.respond_sync();
}
}
},
@@ -591,6 +630,14 @@ impl HttpServer {
impl ProcessRequest {
pub async fn respond(self, is_async: bool) {
+ if is_async {
+ self.respond_async().await;
+ } else {
+ self.respond_sync();
+ }
+ }
+
+ pub fn respond_sync(self) {
let Self {
match_route,
middlewares,
@@ -600,7 +647,25 @@ impl ProcessRequest {
cors,
} = self;
- let response = Self::dispatch(match_route, middlewares, wrapper, request, is_async)
+ let response = Self::dispatch_sync(match_route, middlewares, wrapper, request)
+ .unwrap_or_else(Response::from)
+ .apply_cors(&cors)
+ .unwrap_or_else(Response::from);
+
+ let _ = response_sender.send(response);
+ }
+
+ async fn respond_async(self) {
+ let Self {
+ match_route,
+ middlewares,
+ wrapper,
+ request,
+ response_sender,
+ cors,
+ } = self;
+
+ let response = Self::dispatch_async(match_route, middlewares, wrapper, request)
.await
.unwrap_or_else(Response::from)
.apply_cors(&cors)
@@ -609,24 +674,65 @@ impl ProcessRequest {
let _ = response_sender.send(response);
}
- async fn dispatch(
+ fn dispatch_sync(
match_route: Option,
middlewares: Option>,
wrapper: Option>>,
request: Request,
- is_async: bool,
) -> PyResult {
let Some(match_route) = match_route else {
- return match wrapper.as_deref() {
- Some(wrapper) => Python::attach(|py| {
- let request = Py::new(py, request)?;
- Self::apply_wrapper(py, &request, Status::NOT_FOUND.into(), wrapper)
- }),
- None => Ok(Status::NOT_FOUND.into()),
- };
+ return Self::not_found(wrapper, request);
};
- let (result, request) = Python::attach(|py| -> PyResult<_> {
+ let (result, request) = Self::invoke_route(&match_route, middlewares.as_deref(), request)?;
+
+ Python::attach(|py| {
+ let response = into_response::convert_to_response(result, py)?;
+ match wrapper.as_deref() {
+ Some(wrapper) => Self::apply_wrapper(py, &request, response, wrapper),
+ None => Ok(response),
+ }
+ })
+ }
+
+ async fn dispatch_async(
+ match_route: Option,
+ middlewares: Option>,
+ wrapper: Option>>,
+ request: Request,
+ ) -> PyResult {
+ let Some(match_route) = match_route else {
+ return Self::not_found(wrapper, request);
+ };
+
+ let (result, request) = Self::invoke_route(&match_route, middlewares.as_deref(), request)?;
+ let result = Python::attach(|py| into_future(result.into_bound(py)))?.await?;
+
+ Python::attach(|py| {
+ let response = into_response::convert_to_response(result, py)?;
+ match wrapper.as_deref() {
+ Some(wrapper) => Self::apply_wrapper(py, &request, response, wrapper),
+ None => Ok(response),
+ }
+ })
+ }
+
+ fn not_found(wrapper: Option>>, request: Request) -> PyResult {
+ match wrapper.as_deref() {
+ Some(wrapper) => Python::attach(|py| {
+ let request = Py::new(py, request)?;
+ Self::apply_wrapper(py, &request, Status::NOT_FOUND.into(), wrapper)
+ }),
+ None => Ok(Status::NOT_FOUND.into()),
+ }
+ }
+
+ fn invoke_route(
+ match_route: &OwnedMatchRoute,
+ middlewares: Option<&[Middleware]>,
+ request: Request,
+ ) -> PyResult<(Py, Py)> {
+ Python::attach(|py| -> PyResult<_> {
let request = Py::new(py, request)?;
let route = &match_route.value;
@@ -636,7 +742,7 @@ impl ProcessRequest {
Some(build_route_params(py, &match_route.params)?)
};
- let res = match middlewares.as_deref() {
+ let res = match middlewares {
Some(chain) => MiddlewareChain::execute(
py,
chain,
@@ -649,20 +755,6 @@ impl ProcessRequest {
}?;
Ok((res, request))
- })?;
-
- let result = if is_async {
- Python::attach(|py| into_future(result.into_bound(py)))?.await?
- } else {
- result
- };
-
- Python::attach(|py| {
- let response = into_response::convert_to_response(result, py)?;
- match wrapper.as_deref() {
- Some(wrapper) => Self::apply_wrapper(py, &request, response, wrapper),
- None => Ok(response),
- }
})
}
@@ -715,9 +807,16 @@ fn parse_params_value<'py>(py: Python<'py>, value: &str, ty: &str) -> PyResult(future: F, workers: Option) -> F::Output {
+fn block_on(
+ future: F,
+ workers: Option,
+ max_blocking_threads: usize,
+) -> F::Output {
let mut runtime = tokio::runtime::Builder::new_multi_thread();
workers.map(|w| runtime.worker_threads(w));
+ if max_blocking_threads > 1 {
+ runtime.max_blocking_threads(max_blocking_threads);
+ }
runtime.enable_all().build().unwrap().block_on(future)
}
From a2c09b6a0c5414a3a469307f72b690217b7c3cf7 Mon Sep 17 00:00:00 2001
From: FITAHIANA Nomeniavo Joe <24nomeniavo@gmail.com>
Date: Wed, 4 Nov 2026 20:56:14 +0300
Subject: [PATCH 3/5] chore: async handlers
---
docs/docs/advanced/deployment.md | 2 +-
docs/docs/advanced/server-configuration.md | 22 +++++
docs/docs/api/server.md | 22 +++++
docs/docs/guides/async-handlers.md | 2 +
docs/docs/guides/multiprocess.md | 11 ++-
oxapy/__init__.pyi | 23 +++++
src/lib.rs | 108 +++++++++++++--------
tests/app.py | 2 +
tests/sync_threaded_app.py | 25 +++++
tests/test_sync_threads.py | 82 ++++++++++++++++
10 files changed, 250 insertions(+), 49 deletions(-)
create mode 100644 tests/sync_threaded_app.py
create mode 100644 tests/test_sync_threads.py
diff --git a/docs/docs/advanced/deployment.md b/docs/docs/advanced/deployment.md
index b551daf..f91d2f8 100644
--- a/docs/docs/advanced/deployment.md
+++ b/docs/docs/advanced/deployment.md
@@ -104,7 +104,7 @@ api.example.com {
- Use `Oxapy` with the default `reload=False`. Never run with `reload=True` in production.
- Run behind a reverse proxy that terminates TLS. Session cookies and JWT secrets travel over the wire otherwise.
- Set a strong `Session` secret / JWT secret via environment variables.
-- Tune `workers` to match the machine's CPU count and `max_connections` to your expected load. Add `processes` only if handlers are CPU-bound — remember it is Unix only and does not drain in-flight requests on restart.
+- Tune `workers` for network/HTTP concurrency and `max_connections` to your expected load. Add `.handler_threads(n)` when sync handlers block on I/O, or `processes` when handlers are CPU-bound — remember `processes` is Unix only and does not drain in-flight requests on restart.
- Keep anything that must be consistent across workers in a shared store. Each process has its own copy of `app_data` and module state.
- Serve static assets with a dedicated server (Nginx, CDN) when traffic is high, or keep them behind `static_file()` for small apps. `static_file()` guards against path traversal with `secure_join()`, but uploads written with `File.save()` need their own filename sanitizing.
- Budget for abrupt shutdowns: restarting a worker pool cuts in-flight requests rather than draining them. Use a draining proxy if you need zero-downtime deploys.
diff --git a/docs/docs/advanced/server-configuration.md b/docs/docs/advanced/server-configuration.md
index e343aae..0c14600 100644
--- a/docs/docs/advanced/server-configuration.md
+++ b/docs/docs/advanced/server-configuration.md
@@ -28,6 +28,7 @@ server = (
.template(template) # template engine
.max_connections(1000) # max concurrent connections (default 100)
.channel_capacity(200) # pending-request buffer (default 100)
+ .handler_threads(4) # sync handler threads (default 1 = serial)
.wrap(global_wrapper) # global response wrapper
)
```
@@ -54,6 +55,27 @@ server = (
`server.channel_capacity(n)` — how many pending requests can be buffered internally (default **100**). An advanced setting for tuning throughput under load.
+### handler_threads
+
+`server.handler_threads(n)` — number of OS threads used to execute **synchronous** handlers (default **1**, which means serial execution). Values below `1` are treated as `1`.
+
+Raise it when sync handlers block on I/O that releases the GIL — sync database drivers, `requests`, file reads. It does not bypass the GIL: pure-Python CPU-bound work still needs `processes=N`. The option is ignored in async mode.
+
+```python
+server.handler_threads(4) # up to four sync handlers at once
+```
+
+### Concurrency knobs
+
+| Option | Controls | Default | Use for |
+| --- | --- | --- | --- |
+| `handler_threads(n)` | OS threads running sync Python handlers | `1` (serial) | Blocking I/O inside sync handlers |
+| `workers=n` (`run`) | Tokio runtime threads per process | runtime decides | Network/HTTP throughput |
+| `processes=n` (`run`) | OS processes sharing the port | `1` | CPU-bound Python (bypasses the GIL) |
+| `async_mode()` | Python coroutines on the event loop | off | Non-blocking async I/O |
+| `max_connections(n)` | Concurrent connections | `100` | Load sizing |
+| `channel_capacity(n)` | Pending-request buffer | `100` | Burst absorption |
+
### cors
`server.cors(cors)` — enable automatic CORS handling. The framework adds CORS headers to every response and handles preflight `OPTIONS` requests without hitting your handlers. CORS headers are applied after the `wrap()` wrapper. See the [CORS guide](../guides/cors).
diff --git a/docs/docs/api/server.md b/docs/docs/api/server.md
index fff0111..1692017 100644
--- a/docs/docs/api/server.md
+++ b/docs/docs/api/server.md
@@ -26,6 +26,7 @@ server = Oxapy(("127.0.0.1", 8000))
| `template(template)` | Enable template rendering |
| `max_connections(max_connections)` | Max concurrent connections (default `100`) |
| `channel_capacity(channel_capacity)` | Internal pending-request buffer (default `100`) |
+| `handler_threads(handler_threads)` | OS threads for sync handlers (default `1` = serial) |
| `wrap(wrapper)` | Install a global `(request, response)` wrapper for response transformation |
| `async_mode()` | Enable async handlers; `run()` becomes awaitable |
| `set_patterns(patterns)` | Glob patterns the reload watcher reacts to (default `["*.py"]`) |
@@ -68,12 +69,33 @@ server.run(reload=True) # hot reload during development
Values of `processes` that are `None`, `0`, or negative are treated as `1`.
+:::note `workers` vs `handler_threads`
+
+`workers` controls the Tokio runtime (network and HTTP scheduling). It does not run Python handlers in parallel. `handler_threads` controls the OS threads that execute synchronous Python handlers; see below. In async mode both `workers` and `handler_threads` are ignored.
+
+:::
+
:::note `reload` and `processes` share one supervisor
Both arguments are handled by the same Python supervisor. Any spawn of more than one process — `reload=True`, `processes > 1`, or both — requires an `if __name__ == "__main__":` guard in your entry point, because workers are created by re-executing your script. `processes > 1` is Unix only, and there is no graceful drain of in-flight requests on restart. See the [Multiprocess guide](../guides/multiprocess) for the full picture.
:::
+## handler_threads
+
+```python
+handler_threads(handler_threads: int) -> HttpServer
+```
+
+Sets how many OS threads execute synchronous handlers. The default is `1`, which keeps handlers strictly serial. Values below `1` are treated as `1`.
+
+Use it when sync handlers perform blocking I/O that releases the GIL (sync database drivers, `requests`, file I/O). It does not bypass the GIL: CPU-bound Python still needs `processes=N`. The setting only applies to sync mode.
+
+```python
+server.handler_threads(4)
+server.run()
+```
+
## cors
```python
diff --git a/docs/docs/guides/async-handlers.md b/docs/docs/guides/async-handlers.md
index 4e318f0..53d9eed 100644
--- a/docs/docs/guides/async-handlers.md
+++ b/docs/docs/guides/async-handlers.md
@@ -55,6 +55,8 @@ async def async_handler(request):
Use `async_mode()` when handlers perform non-blocking I/O — HTTP calls, database queries through an async driver, websocket clients. It keeps the event loop free while those operations are in flight.
+For blocking I/O inside ordinary sync handlers, prefer `.handler_threads(n)` on the server instead: it runs up to `n` sync handlers on separate OS threads. The setting is ignored in async mode, and neither option bypasses the GIL for CPU-bound Python.
+
:::note
In async mode, `app.run()` returns an awaitable; calling it from a synchronous `main()` without awaiting will not start the server. Use the pattern above with `asyncio.run()`.
diff --git a/docs/docs/guides/multiprocess.md b/docs/docs/guides/multiprocess.md
index ebfda4c..5b03177 100644
--- a/docs/docs/guides/multiprocess.md
+++ b/docs/docs/guides/multiprocess.md
@@ -31,10 +31,11 @@ These two options control different levels of concurrency and are easy to confus
| --- | --- | --- | --- |
| `workers` | Tokio worker **threads** inside each process | runtime decides (usually one per CPU core) | Ignored in async mode — see [Limitations](#limitations) |
| `processes` | **OS processes** | `1` (no supervisor) | Unix only; uses `SO_REUSEPORT` |
+| `handler_threads` | OS threads running **sync Python handlers** | `1` (serial) | Ignored in async mode; does not bypass the GIL |
-They compose. `run(processes=4, workers=2)` gives you 4 processes with 2 Tokio threads each — 8 threads of execution for the same port.
+They compose. `run(processes=4, workers=2)` gives you 4 processes with 2 Tokio threads each — 8 threads of execution for the same port. Adding `.handler_threads(4)` lets each process run up to four sync handlers concurrently.
-Because the GIL serializes Python bytecode inside a process, `processes` is usually the more effective knob for CPU-bound handlers, while `workers` helps I/O-bound ones.
+Because the GIL serializes Python bytecode inside a process, `processes` is the effective knob for CPU-bound handlers. Use `handler_threads` when sync handlers block on I/O that releases the GIL, and `workers` for Rust-side network/HTTP concurrency. Async handlers need neither.
## How it works
@@ -91,9 +92,9 @@ Windows can still run multiple processes, but not through this mechanism: run se
The request pump stops as soon as the shutdown signal arrives; it does not wait for in-flight connections to complete (`src/lib.rs`, the `process_requests` loop). Expect dropped connections during restarts and deploys.
-### `workers` is ignored in async mode
+### `workers` and `handler_threads` are ignored in async mode
-In async mode, `run()` returns an awaitable and the `workers` argument is **not** forwarded to the Tokio runtime. Passing `workers=` alongside `.async_mode()` has no effect.
+In async mode, `run()` returns an awaitable and the `workers` argument is **not** forwarded to the Tokio runtime. `.handler_threads()` is also ignored. Passing either alongside `.async_mode()` has no effect.
### In-memory state is not shared
@@ -110,7 +111,7 @@ This is a convenience pool, not a Gunicorn replacement. There is no pre-fork soc
- You need more than one core for CPU-bound Python handlers.
- You want a self-healing pool without introducing an external dependency.
-Prefer a single process with tuned `workers` when your handlers are I/O-bound or already use async — the supervisor adds a process layer for little gain. For long-running production deployments, [Deployment](../advanced/deployment) covers running behind a reverse proxy and a service manager.
+Prefer a single process with tuned `.handler_threads()` for blocking sync I/O, or async mode for non-blocking I/O — the supervisor adds a process layer for little gain. For long-running production deployments, [Deployment](../advanced/deployment) covers running behind a reverse proxy and a service manager.
## Next steps
diff --git a/oxapy/__init__.pyi b/oxapy/__init__.pyi
index 242b026..fb692c7 100644
--- a/oxapy/__init__.pyi
+++ b/oxapy/__init__.pyi
@@ -513,6 +513,29 @@ class HttpServer:
server.channel_capacity(200)
```
"""
+ def handler_threads(self, handler_threads: builtins.int) -> HttpServer:
+ r"""
+ Set the number of OS threads used to execute synchronous handlers.
+
+ By default synchronous handlers run one at a time on a single thread.
+ Raising this value lets handlers overlap blocking work (database
+ drivers, file I/O, network calls) that releases the GIL. It does not
+ bypass the GIL: pure-Python CPU-bound work still needs ``processes=N``.
+
+ This option only affects sync mode; async handlers are unaffected.
+ Values below ``1`` are treated as ``1``.
+
+ Args:
+ handler_threads (int): Number of handler threads (default 1).
+
+ Returns:
+ Self
+
+ Example:
+ ```python
+ server.handler_threads(8)
+ ```
+ """
def wrap(self, wrapper: typing.Any) -> HttpServer:
r"""
Add a global wrapper (middleware) to the server.
diff --git a/src/lib.rs b/src/lib.rs
index 6237f55..b6e45a3 100644
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -590,11 +590,7 @@ impl HttpServer {
) -> PyResult<()> {
let mut batch = Vec::with_capacity(64);
let mut tasks = JoinSet::new();
- let sync_semaphore = if locals.is_none() && self.handler_threads > 1 {
- Some(Arc::new(Semaphore::new(self.handler_threads)))
- } else {
- None
- };
+ let dispatcher = Dispatcher::new(locals, self.handler_threads);
loop {
batch.clear();
tokio::select! {
@@ -602,19 +598,8 @@ impl HttpServer {
if n == 0 {
break;
}
- for pr in batch.drain(..) {
- if let Some(ref local) = locals {
- let local = local.clone();
- tasks.spawn(async move { scope(local, pr.respond(true)).await});
- } else if let Some(ref semaphore) = sync_semaphore {
- let permit = semaphore.clone().acquire_owned().await.unwrap();
- tasks.spawn_blocking(move || {
- let _permit = permit;
- pr.respond_sync();
- });
- } else {
- pr.respond_sync();
- }
+ for request in batch.drain(..) {
+ dispatcher.spawn(request, &mut tasks).await;
}
},
Some(_) = tasks.join_next(), if !tasks.is_empty() => {},
@@ -628,15 +613,42 @@ impl HttpServer {
}
}
-impl ProcessRequest {
- pub async fn respond(self, is_async: bool) {
- if is_async {
- self.respond_async().await;
- } else {
- self.respond_sync();
+enum Dispatcher {
+ Serial,
+ Async(TaskLocals),
+ Threaded { permits: Arc },
+}
+
+impl Dispatcher {
+ fn new(locals: Option, handler_threads: usize) -> Self {
+ match locals {
+ Some(locals) => Self::Async(locals),
+ None if handler_threads > 1 => Self::Threaded {
+ permits: Arc::new(Semaphore::new(handler_threads)),
+ },
+ None => Self::Serial,
+ }
+ }
+
+ async fn spawn(&self, request: ProcessRequest, tasks: &mut JoinSet<()>) {
+ match self {
+ Self::Serial => request.respond_sync(),
+ Self::Async(locals) => {
+ let locals = locals.clone();
+ tasks.spawn(async move { scope(locals, request.respond_async()).await });
+ }
+ Self::Threaded { permits } => {
+ let permit = permits.clone().acquire_owned().await.unwrap();
+ tasks.spawn_blocking(move || {
+ let _permit = permit;
+ request.respond_sync();
+ });
+ }
}
}
+}
+impl ProcessRequest {
pub fn respond_sync(self) {
let Self {
match_route,
@@ -647,15 +659,14 @@ impl ProcessRequest {
cors,
} = self;
- let response = Self::dispatch_sync(match_route, middlewares, wrapper, request)
- .unwrap_or_else(Response::from)
- .apply_cors(&cors)
- .unwrap_or_else(Response::from);
-
- let _ = response_sender.send(response);
+ Self::send(
+ Self::dispatch_sync(match_route, middlewares, wrapper, request),
+ &cors,
+ response_sender,
+ );
}
- async fn respond_async(self) {
+ pub async fn respond_async(self) {
let Self {
match_route,
middlewares,
@@ -665,10 +676,21 @@ impl ProcessRequest {
cors,
} = self;
- let response = Self::dispatch_async(match_route, middlewares, wrapper, request)
- .await
+ Self::send(
+ Self::dispatch_async(match_route, middlewares, wrapper, request).await,
+ &cors,
+ response_sender,
+ );
+ }
+
+ fn send(
+ response: PyResult,
+ cors: &Option>,
+ response_sender: oneshot::Sender,
+ ) {
+ let response = response
.unwrap_or_else(Response::from)
- .apply_cors(&cors)
+ .apply_cors(cors)
.unwrap_or_else(Response::from);
let _ = response_sender.send(response);
@@ -685,14 +707,7 @@ impl ProcessRequest {
};
let (result, request) = Self::invoke_route(&match_route, middlewares.as_deref(), request)?;
-
- Python::attach(|py| {
- let response = into_response::convert_to_response(result, py)?;
- match wrapper.as_deref() {
- Some(wrapper) => Self::apply_wrapper(py, &request, response, wrapper),
- None => Ok(response),
- }
- })
+ Self::finalize(result, &request, wrapper)
}
async fn dispatch_async(
@@ -707,11 +722,18 @@ impl ProcessRequest {
let (result, request) = Self::invoke_route(&match_route, middlewares.as_deref(), request)?;
let result = Python::attach(|py| into_future(result.into_bound(py)))?.await?;
+ Self::finalize(result, &request, wrapper)
+ }
+ fn finalize(
+ result: Py,
+ request: &Py,
+ wrapper: Option>>,
+ ) -> PyResult {
Python::attach(|py| {
let response = into_response::convert_to_response(result, py)?;
match wrapper.as_deref() {
- Some(wrapper) => Self::apply_wrapper(py, &request, response, wrapper),
+ Some(wrapper) => Self::apply_wrapper(py, request, response, wrapper),
None => Ok(response),
}
})
diff --git a/tests/app.py b/tests/app.py
index 4707e57..534c7d9 100644
--- a/tests/app.py
+++ b/tests/app.py
@@ -20,6 +20,8 @@ def main():
(
Oxapy(("0.0.0.0", 3000))
.attach(Router().routes([index, get_user, create_user]))
+ .max_connections(1024)
+ .channel_capacity(1024)
.run(workers=1, processes=8)
)
diff --git a/tests/sync_threaded_app.py b/tests/sync_threaded_app.py
new file mode 100644
index 0000000..c51d5fd
--- /dev/null
+++ b/tests/sync_threaded_app.py
@@ -0,0 +1,25 @@
+import sys
+import time
+
+from oxapy import Oxapy, Router, get
+
+
+@get("/health")
+def health(_request):
+ return {"message": "ok"}
+
+
+@get("/slow")
+def slow(_request):
+ time.sleep(0.25)
+ return {"message": "slow"}
+
+
+def main(port, threads):
+ app = Oxapy(("127.0.0.1", port)).attach(Router().routes([health, slow]))
+ app.handler_threads(threads)
+ app.run()
+
+
+if __name__ == "__main__":
+ main(int(sys.argv[1]), int(sys.argv[2]))
diff --git a/tests/test_sync_threads.py b/tests/test_sync_threads.py
new file mode 100644
index 0000000..248e34c
--- /dev/null
+++ b/tests/test_sync_threads.py
@@ -0,0 +1,82 @@
+import socket
+import subprocess
+import sys
+import time
+from concurrent.futures import ThreadPoolExecutor
+from pathlib import Path
+
+import pytest
+import requests
+
+
+def _free_port():
+ with socket.socket() as sock:
+ sock.bind(("127.0.0.1", 0))
+ return sock.getsockname()[1]
+
+
+def _start_server(threads):
+ port = _free_port()
+ proc = subprocess.Popen(
+ [
+ sys.executable,
+ str(Path(__file__).with_name("sync_threaded_app.py")),
+ str(port),
+ str(threads),
+ ],
+ stdout=subprocess.DEVNULL,
+ stderr=subprocess.DEVNULL,
+ )
+ base_url = f"http://127.0.0.1:{port}"
+ deadline = time.time() + 5
+ try:
+ while time.time() < deadline:
+ if proc.poll() is not None:
+ pytest.fail(f"sync server (threads={threads}) exited during startup")
+ try:
+ if requests.get(f"{base_url}/health", timeout=0.2).status_code == 200:
+ return proc, base_url
+ except requests.RequestException:
+ pass
+ time.sleep(0.05)
+ pytest.fail(f"sync server (threads={threads}) did not start")
+ except BaseException:
+ _stop(proc)
+ raise
+
+
+def _stop(proc):
+ proc.terminate()
+ try:
+ proc.wait(timeout=5)
+ except subprocess.TimeoutExpired:
+ proc.kill()
+ proc.wait()
+
+
+@pytest.fixture(scope="module", params=[1, 4], ids=["serial", "threaded"])
+def sync_server(request):
+ proc, base_url = _start_server(request.param)
+ try:
+ yield request.param, base_url
+ finally:
+ _stop(proc)
+
+
+def test_sync_handler_concurrency_matches_thread_count(sync_server):
+ threads, base_url = sync_server
+ request_count = 8
+
+ def hit(_):
+ return requests.get(f"{base_url}/slow", timeout=15)
+
+ start = time.perf_counter()
+ with ThreadPoolExecutor(max_workers=request_count) as pool:
+ responses = list(pool.map(hit, range(request_count)))
+ elapsed = time.perf_counter() - start
+
+ assert all(response.status_code == 200 for response in responses)
+ if threads == 1:
+ assert elapsed >= 1.8, f"serial handlers finished too fast: {elapsed:.2f}s"
+ else:
+ assert elapsed < 1.8, f"{threads} handler threads took {elapsed:.2f}s"
From f9f17364d339f36ee0d5b5af18bd95c79aa3cbd7 Mon Sep 17 00:00:00 2001
From: FITAHIANA Nomeniavo Joe <24nomeniavo@gmail.com>
Date: Wed, 4 Nov 2026 21:15:31 +0300
Subject: [PATCH 4/5] chore: improve code base
---
src/into_response.rs | 64 +++++-------------
src/lib.rs | 142 ++++++++++++++++++++++-----------------
src/request.rs | 54 ++++-----------
src/response.rs | 54 +++++++++------
src/routing.rs | 7 +-
src/serializer/fields.rs | 20 +++---
src/serializer/mod.rs | 12 ++--
7 files changed, 163 insertions(+), 190 deletions(-)
diff --git a/src/into_response.rs b/src/into_response.rs
index af33c7a..5e00544 100644
--- a/src/into_response.rs
+++ b/src/into_response.rs
@@ -1,13 +1,8 @@
-use hyper::{
- HeaderMap,
- body::Bytes,
- header::{CONTENT_TYPE, HeaderValue},
-};
+use hyper::{body::Bytes, header::HeaderValue};
use pyo3::{Py, prelude::*, types::PyAny};
use crate::{
- Response, cors::Cors, exceptions::IntoPyException, exceptions::*, json, response::ResponseBody,
- status::Status,
+ Response, cors::Cors, exceptions::IntoPyException, exceptions::*, json, status::Status,
};
type Error = Box;
@@ -19,13 +14,7 @@ impl TryFrom for Response {
#[inline]
fn try_from(val: String) -> Result {
- let mut headers = HeaderMap::with_capacity(1);
- headers.insert(CONTENT_TYPE, TEXT_PLAIN);
- Ok(Response {
- status: Status::OK,
- headers,
- body: ResponseBody::Bytes(val.into()),
- })
+ Ok(Response::with_content_type(Status::OK, TEXT_PLAIN, val.into()))
}
}
@@ -34,13 +23,11 @@ impl TryFrom> for Response {
#[inline]
fn try_from(val: Bound) -> Result {
- let mut headers = HeaderMap::with_capacity(1);
- headers.insert(CONTENT_TYPE, APP_JSON);
- Ok(Response {
- status: Status::OK,
- headers,
- body: ResponseBody::Bytes(json::dumps(&val)?.into()),
- })
+ Ok(Response::with_content_type(
+ Status::OK,
+ APP_JSON,
+ json::dumps(&val)?.into(),
+ ))
}
}
@@ -48,14 +35,8 @@ impl TryFrom<(String, Status)> for Response {
type Error = Error;
#[inline]
- fn try_from(val: (String, Status)) -> Result {
- let mut headers = HeaderMap::with_capacity(1);
- headers.insert(CONTENT_TYPE, TEXT_PLAIN);
- Ok(Response {
- status: val.1,
- headers,
- body: ResponseBody::Bytes(val.0.into()),
- })
+ fn try_from((val, status): (String, Status)) -> Result {
+ Ok(Response::with_content_type(status, TEXT_PLAIN, val.into()))
}
}
@@ -63,27 +44,19 @@ impl TryFrom<(Bound<'_, PyAny>, Status)> for Response {
type Error = Error;
#[inline]
- fn try_from(val: (Bound, Status)) -> Result {
- let mut headers = HeaderMap::with_capacity(1);
- headers.insert(CONTENT_TYPE, APP_JSON);
- Ok(Response {
- status: val.1,
- headers,
- body: ResponseBody::Bytes(json::dumps(&val.0)?.into()),
- })
+ fn try_from((val, status): (Bound, Status)) -> Result {
+ Ok(Response::with_content_type(
+ status,
+ APP_JSON,
+ json::dumps(&val)?.into(),
+ ))
}
}
impl From for Response {
#[inline]
fn from(val: Status) -> Self {
- let mut headers = HeaderMap::with_capacity(1);
- headers.insert(CONTENT_TYPE, APP_JSON);
- Response {
- status: val,
- headers,
- body: ResponseBody::Bytes(Bytes::new()),
- }
+ Response::with_content_type(val, APP_JSON, Bytes::new())
}
}
@@ -107,10 +80,9 @@ impl From for Response {
Status::INTERNAL_SERVER_ERROR
}
};
- let response = Response::from(status);
let detail = value.value(py).to_string().replace('"', "'");
let body = serde_json::json!({ "detail": detail }).to_string();
- response.set_body(body)
+ Response::with_content_type(status, APP_JSON, body.into())
})
}
}
diff --git a/src/lib.rs b/src/lib.rs
index b6e45a3..71ce322 100644
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -55,7 +55,7 @@ mod templating;
pyo3_stub_gen::define_stub_info_gatherer!(stub_info);
-struct ProcessRequest {
+pub(crate) struct ProcessRequest {
match_route: Option,
middlewares: Option>,
request: Request,
@@ -566,9 +566,7 @@ impl HttpServer {
hyper::service::service_fn(move |req| {
let ctx = ctx.clone();
async move {
- RequestBuilder::new(req)
- .with_app_data(&ctx.app_data)
- .with_template(&ctx.template)
+ RequestBuilder::from_context(req, &ctx)
.build()
.await
.unwrap()
@@ -649,38 +647,48 @@ impl Dispatcher {
}
impl ProcessRequest {
- pub fn respond_sync(self) {
- let Self {
+ pub(crate) fn new(
+ request: Request,
+ matched: Option<(OwnedMatchRoute, Option>)>,
+ ctx: &Context,
+ response_sender: oneshot::Sender,
+ ) -> Self {
+ let (match_route, middlewares) = match matched {
+ Some((route, mw)) => (Some(route), mw),
+ None => (None, None),
+ };
+
+ Self {
match_route,
middlewares,
- wrapper,
request,
response_sender,
- cors,
- } = self;
+ cors: ctx.cors.clone(),
+ wrapper: ctx.wrapper.clone(),
+ }
+ }
- Self::send(
- Self::dispatch_sync(match_route, middlewares, wrapper, request),
- &cors,
- response_sender,
- );
+ pub fn respond_sync(self) {
+ let (target, response_sender, cors) = self.into_dispatch_target();
+ Self::send(target.dispatch_sync(), &cors, response_sender);
}
pub async fn respond_async(self) {
- let Self {
- match_route,
- middlewares,
- wrapper,
- request,
- response_sender,
- cors,
- } = self;
+ let (target, response_sender, cors) = self.into_dispatch_target();
+ Self::send(target.dispatch_async().await, &cors, response_sender);
+ }
- Self::send(
- Self::dispatch_async(match_route, middlewares, wrapper, request).await,
- &cors,
- response_sender,
- );
+ fn into_dispatch_target(self) -> (DispatchTarget, oneshot::Sender, Option>) {
+ (
+ DispatchTarget {
+ match_route: self.match_route,
+ middlewares: self.middlewares,
+ wrapper: self.wrapper,
+ request: self.request,
+ },
+ self.response_sender,
+ self.cors,
+ )
}
fn send(
@@ -695,55 +703,62 @@ impl ProcessRequest {
let _ = response_sender.send(response);
}
+}
- fn dispatch_sync(
- match_route: Option,
- middlewares: Option>,
- wrapper: Option>>,
- request: Request,
- ) -> PyResult {
- let Some(match_route) = match_route else {
- return Self::not_found(wrapper, request);
+struct DispatchTarget {
+ match_route: Option,
+ middlewares: Option>,
+ wrapper: Option>>,
+ request: Request,
+}
+
+impl DispatchTarget {
+ fn execute(self) -> PyResult, Py), Response>> {
+ let wrapper = self.wrapper.as_deref();
+ let Some(match_route) = self.match_route else {
+ return Ok(Err(Self::not_found(self.request, wrapper)?));
};
- let (result, request) = Self::invoke_route(&match_route, middlewares.as_deref(), request)?;
- Self::finalize(result, &request, wrapper)
+ let (result, request) =
+ Self::invoke_route(&match_route, self.middlewares.as_deref(), self.request)?;
+ Ok(Ok((result, request)))
}
- async fn dispatch_async(
- match_route: Option,
- middlewares: Option>,
- wrapper: Option>>,
- request: Request,
- ) -> PyResult {
- let Some(match_route) = match_route else {
- return Self::not_found(wrapper, request);
- };
+ fn dispatch_sync(self) -> PyResult {
+ let wrapper = self.wrapper.clone();
+ match self.execute()? {
+ Ok((result, request)) => Self::finalize(result, &request, wrapper.as_deref()),
+ Err(response) => Ok(response),
+ }
+ }
- let (result, request) = Self::invoke_route(&match_route, middlewares.as_deref(), request)?;
- let result = Python::attach(|py| into_future(result.into_bound(py)))?.await?;
- Self::finalize(result, &request, wrapper)
+ async fn dispatch_async(self) -> PyResult {
+ let wrapper = self.wrapper.clone();
+ match self.execute()? {
+ Ok((result, request)) => {
+ let result = Python::attach(|py| into_future(result.into_bound(py)))?.await?;
+ Self::finalize(result, &request, wrapper.as_deref())
+ }
+ Err(response) => Ok(response),
+ }
}
fn finalize(
result: Py,
request: &Py,
- wrapper: Option>>,
+ wrapper: Option<&Py>,
) -> PyResult {
Python::attach(|py| {
let response = into_response::convert_to_response(result, py)?;
- match wrapper.as_deref() {
- Some(wrapper) => Self::apply_wrapper(py, request, response, wrapper),
- None => Ok(response),
- }
+ Self::wrap_response(py, request, response, wrapper)
})
}
- fn not_found(wrapper: Option>>, request: Request) -> PyResult {
- match wrapper.as_deref() {
+ fn not_found(request: Request, wrapper: Option<&Py>) -> PyResult {
+ match wrapper {
Some(wrapper) => Python::attach(|py| {
let request = Py::new(py, request)?;
- Self::apply_wrapper(py, &request, Status::NOT_FOUND.into(), wrapper)
+ Self::wrap_response(py, &request, Status::NOT_FOUND.into(), Some(wrapper))
}),
None => Ok(Status::NOT_FOUND.into()),
}
@@ -781,14 +796,19 @@ impl ProcessRequest {
}
#[inline]
- fn apply_wrapper(
+ fn wrap_response(
py: Python<'_>,
py_request: &Py,
response: Response,
- wrapper: &Py,
+ wrapper: Option<&Py>,
) -> PyResult {
- let wrapped = wrapper.call(py, (py_request, response), None)?;
- into_response::convert_to_response(wrapped, py)
+ match wrapper {
+ Some(wrapper) => {
+ let wrapped = wrapper.call(py, (py_request, response), None)?;
+ into_response::convert_to_response(wrapped, py)
+ }
+ None => Ok(response),
+ }
}
}
diff --git a/src/request.rs b/src/request.rs
index d17fdb6..52298f4 100644
--- a/src/request.rs
+++ b/src/request.rs
@@ -19,7 +19,7 @@ use crate::status::Status;
use crate::{
Context, IntoPyException, ProcessRequest, json, multipart::File, templating::Template,
};
-use crate::{middleware::Middleware, routing::OwnedMatchRoute};
+use crate::routing::OwnedMatchRoute;
use crate::{multipart::parse_multipart, response::Body};
/// HTTP request object containing information about the incoming request.
@@ -294,48 +294,8 @@ impl Request {
.map(|m| (OwnedMatchRoute::from(m), router.middlewares.clone()))
});
- if let Some((match_route, middlewares)) = matched {
- self.handle_found_route(&ctx, match_route, middlewares)
- .await
- } else {
- self.handle_not_found(&ctx).await
- }
- }
-
- async fn handle_found_route(
- self,
- ctx: &Context,
- match_route: OwnedMatchRoute,
- middlewares: Option>,
- ) -> Result, hyper::http::Error> {
- let (response_sender, response_receiver) = oneshot::channel();
-
- let process_request = ProcessRequest {
- match_route: Some(match_route),
- middlewares,
- request: self,
- response_sender,
- wrapper: ctx.wrapper.clone(),
- cors: ctx.cors.clone(),
- };
-
- Self::send_and_wait_response(&ctx.request_sender, process_request, response_receiver).await
- }
-
- async fn handle_not_found(
- self,
- ctx: &Context,
- ) -> Result, hyper::http::Error> {
let (response_sender, response_receiver) = oneshot::channel();
-
- let process_request = ProcessRequest {
- match_route: None,
- middlewares: None,
- request: self,
- response_sender,
- wrapper: ctx.wrapper.clone(),
- cors: ctx.cors.clone(),
- };
+ let process_request = ProcessRequest::new(self, matched, &ctx, response_sender);
Self::send_and_wait_response(&ctx.request_sender, process_request, response_receiver).await
}
@@ -377,11 +337,21 @@ impl RequestBuilder {
}
}
+ pub fn from_context(req: hyper::Request, ctx: &Context) -> Self {
+ Self {
+ app_data: ctx.app_data.clone(),
+ template: ctx.template.clone(),
+ ..Self::new(req)
+ }
+ }
+
+ #[allow(dead_code)]
pub fn with_app_data(mut self, app_data: &Option>>) -> Self {
self.app_data = app_data.clone();
self
}
+ #[allow(dead_code)]
pub fn with_template(mut self, template: &Option>) -> Self {
self.template = template.clone();
self
diff --git a/src/response.rs b/src/response.rs
index e70bc85..58ad13a 100644
--- a/src/response.rs
+++ b/src/response.rs
@@ -60,14 +60,23 @@ pub struct Response {
pub headers: HeaderMap,
}
-#[inline(always)]
-fn with_ct(status: Status, content_type: HeaderValue, body: Bytes) -> Response {
- let mut headers = HeaderMap::with_capacity(1);
- headers.insert(CONTENT_TYPE, content_type);
- Response {
- status,
- headers,
- body: ResponseBody::Bytes(body),
+#[inline]
+fn parse_header(key: &str, value: &str) -> PyResult<(HeaderName, HeaderValue)> {
+ let header_name = HeaderName::from_str(key).into_py_exception()?;
+ let header_value = HeaderValue::from_str(value).into_py_exception()?;
+ Ok((header_name, header_value))
+}
+
+impl Response {
+ #[inline(always)]
+ pub fn with_content_type(status: Status, content_type: HeaderValue, body: Bytes) -> Self {
+ let mut headers = HeaderMap::with_capacity(1);
+ headers.insert(CONTENT_TYPE, content_type);
+ Response {
+ status,
+ headers,
+ body: ResponseBody::Bytes(body),
+ }
}
}
@@ -100,19 +109,26 @@ impl Response {
#[pyo3(signature=(body, status = Status::OK , content_type="application/json"))]
#[gen_stub(override_return_type(type_repr = "typing_extensions.Self", imports = ("typing_extensions",)))]
pub fn new(body: Bound<'_, PyAny>, status: Status, content_type: &str) -> PyResult {
+ let ct = HeaderValue::from_str(content_type).into_py_exception()?;
+
if let Ok(s) = body.cast::() {
let text = s.to_str().into_py_exception()?.to_owned();
- let ct = HeaderValue::from_str(content_type).into_py_exception()?;
- return Ok(with_ct(status, ct, Bytes::from(text)));
+ return Ok(Self::with_content_type(status, ct, Bytes::from(text)));
}
if let Ok(b) = body.cast::() {
- let ct = HeaderValue::from_str(content_type).into_py_exception()?;
- return Ok(with_ct(status, ct, Bytes::copy_from_slice(b.as_bytes())));
+ return Ok(Self::with_content_type(
+ status,
+ ct,
+ Bytes::copy_from_slice(b.as_bytes()),
+ ));
}
- let ct = HeaderValue::from_str(content_type).into_py_exception()?;
- Ok(with_ct(status, ct, json::dumps(&body)?.into()))
+ Ok(Self::with_content_type(
+ status,
+ ct,
+ json::dumps(&body)?.into(),
+ ))
}
/// Get the response body as a string.
@@ -176,9 +192,8 @@ impl Response {
/// response.insert_header("Cache-Control", "no-cache")
/// ```
pub fn insert_header(&mut self, key: &str, value: &str) -> PyResult<()> {
- let header_name = HeaderName::from_str(key).into_py_exception()?;
- let header_value = HeaderValue::from_str(value).into_py_exception()?;
- self.headers.insert(header_name, header_value);
+ let (name, val) = parse_header(key, value)?;
+ self.headers.insert(name, val);
Ok(())
}
@@ -202,9 +217,8 @@ impl Response {
/// response.append_header("Set-Cookie", "theme=dark")
/// ```
pub fn append_header(&mut self, key: &str, value: &str) -> PyResult<()> {
- let header_name = HeaderName::from_str(key).into_py_exception()?;
- let header_value = HeaderValue::from_str(value).into_py_exception()?;
- self.headers.append(header_name, header_value);
+ let (name, val) = parse_header(key, value)?;
+ self.headers.append(name, val);
Ok(())
}
diff --git a/src/routing.rs b/src/routing.rs
index bf80ef5..299a1af 100644
--- a/src/routing.rs
+++ b/src/routing.rs
@@ -160,11 +160,8 @@ fn extract_params(path: &str, py: Python<'_>) -> PyResult> {
let params = re
.captures_iter(path)
.map(|cap| {
- let arg = cap[1].to_string();
- match arg.split_once(':') {
- Some((a, _)) => a.to_string(),
- None => arg,
- }
+ let arg = &cap[1];
+ arg.split_once(':').map_or(arg, |(a, _)| a).to_string()
})
.collect();
diff --git a/src/serializer/fields.rs b/src/serializer/fields.rs
index c2d8a08..cb010f1 100644
--- a/src/serializer/fields.rs
+++ b/src/serializer/fields.rs
@@ -108,6 +108,17 @@ impl Field {
}
}
+pub(crate) fn wrap_array_schema(items: Value, nullable: bool) -> Value {
+ let mut array_schema = Map::with_capacity(2);
+ if nullable {
+ array_schema.insert("type".to_string(), json!(["array", "null"]));
+ } else {
+ array_schema.insert("type".to_string(), json!("array"));
+ }
+ array_schema.insert("items".to_string(), items);
+ json!(array_schema)
+}
+
impl Field {
pub fn to_json_schema_value(&self) -> Value {
let mut schema = Map::with_capacity(6);
@@ -143,14 +154,7 @@ impl Field {
}
if self.many {
- let mut array_schema = Map::with_capacity(2);
- if self.nullable {
- array_schema.insert("type".to_string(), json!(["array", "null"]))
- } else {
- array_schema.insert("type".to_string(), json!("array"))
- };
- array_schema.insert("items".to_string(), json!(schema));
- return json!(array_schema);
+ return wrap_array_schema(json!(schema), self.nullable);
}
json!(schema)
diff --git a/src/serializer/mod.rs b/src/serializer/mod.rs
index c77e291..76dd710 100644
--- a/src/serializer/mod.rs
+++ b/src/serializer/mod.rs
@@ -475,14 +475,10 @@ impl Serializer {
Self::json_schema_value(&attr_obj.get_type(), field.nullable, py)?;
if field.many {
- let mut array_schema = Map::with_capacity(2);
- if field.nullable {
- array_schema.insert("type".to_string(), json!(["array", "null"]))
- } else {
- array_schema.insert("type".to_string(), json!("array"))
- };
- array_schema.insert("items".to_string(), nested_schema);
- properties.insert(attr_name, json!(array_schema));
+ properties.insert(
+ attr_name,
+ fields::wrap_array_schema(nested_schema, field.nullable),
+ );
} else {
properties.insert(attr_name, nested_schema);
}
From 3534edc30d49a4480fc807196bf9273f82577dc0 Mon Sep 17 00:00:00 2001
From: FITAHIANA Nomeniavo Joe <24nomeniavo@gmail.com>
Date: Wed, 4 Nov 2026 21:19:30 +0300
Subject: [PATCH 5/5] fmt: cargo fmt
---
src/into_response.rs | 6 +++++-
src/lib.rs | 4 +++-
src/request.rs | 2 +-
3 files changed, 9 insertions(+), 3 deletions(-)
diff --git a/src/into_response.rs b/src/into_response.rs
index 5e00544..3010aaf 100644
--- a/src/into_response.rs
+++ b/src/into_response.rs
@@ -14,7 +14,11 @@ impl TryFrom for Response {
#[inline]
fn try_from(val: String) -> Result {
- Ok(Response::with_content_type(Status::OK, TEXT_PLAIN, val.into()))
+ Ok(Response::with_content_type(
+ Status::OK,
+ TEXT_PLAIN,
+ val.into(),
+ ))
}
}
diff --git a/src/lib.rs b/src/lib.rs
index 71ce322..9c44aa2 100644
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -678,7 +678,9 @@ impl ProcessRequest {
Self::send(target.dispatch_async().await, &cors, response_sender);
}
- fn into_dispatch_target(self) -> (DispatchTarget, oneshot::Sender, Option>) {
+ fn into_dispatch_target(
+ self,
+ ) -> (DispatchTarget, oneshot::Sender, Option>) {
(
DispatchTarget {
match_route: self.match_route,
diff --git a/src/request.rs b/src/request.rs
index 52298f4..3bc3e57 100644
--- a/src/request.rs
+++ b/src/request.rs
@@ -15,11 +15,11 @@ use pyo3_stub_gen::derive::*;
use url::form_urlencoded;
use crate::response::Response;
+use crate::routing::OwnedMatchRoute;
use crate::status::Status;
use crate::{
Context, IntoPyException, ProcessRequest, json, multipart::File, templating::Template,
};
-use crate::routing::OwnedMatchRoute;
use crate::{multipart::parse_multipart, response::Body};
/// HTTP request object containing information about the incoming request.