Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
@@ -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"
Expand Down
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
<b>OxAPY</b> is Python HTTP server library build in Rust - a fast, safe and featureementation.
</p>

<a href='https://github.com/j03-dev/oxapy/#'><img src='https://img.shields.io/badge/version-0.11.5-%23b7410e'/></a>
<a href='https://github.com/j03-dev/oxapy/#'><img src='https://img.shields.io/badge/version-0.11.6-%23b7410e'/></a>
<a href="https://pepy.tech/projects/oxapy"><img src="https://static.pepy.tech/badge/oxapy" alt="PyPI Downloads"></a>

<p>
Expand Down
2 changes: 1 addition & 1 deletion docs/docs/advanced/deployment.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
22 changes: 22 additions & 0 deletions docs/docs/advanced/server-configuration.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
)
```
Expand All @@ -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).
Expand Down
22 changes: 22 additions & 0 deletions docs/docs/api/server.md
Original file line number Diff line number Diff line change
Expand Up @@ -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"]`) |
Expand Down Expand Up @@ -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
Expand Down
2 changes: 2 additions & 0 deletions docs/docs/guides/async-handlers.md
Original file line number Diff line number Diff line change
Expand Up @@ -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()`.
Expand Down
11 changes: 6 additions & 5 deletions docs/docs/guides/multiprocess.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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

Expand All @@ -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

Expand Down
23 changes: 23 additions & 0 deletions oxapy/__init__.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
68 changes: 22 additions & 46 deletions src/into_response.rs
Original file line number Diff line number Diff line change
@@ -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<dyn std::error::Error>;
Expand All @@ -19,13 +14,11 @@ impl TryFrom<String> for Response {

#[inline]
fn try_from(val: String) -> Result<Self, Self::Error> {
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(),
))
}
}

Expand All @@ -34,56 +27,40 @@ impl TryFrom<Bound<'_, PyAny>> for Response {

#[inline]
fn try_from(val: Bound<PyAny>) -> Result<Self, Self::Error> {
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(),
))
}
}

impl TryFrom<(String, Status)> for Response {
type Error = Error;

#[inline]
fn try_from(val: (String, Status)) -> Result<Self, Self::Error> {
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<Self, Self::Error> {
Ok(Response::with_content_type(status, TEXT_PLAIN, val.into()))
}
}

impl TryFrom<(Bound<'_, PyAny>, Status)> for Response {
type Error = Error;

#[inline]
fn try_from(val: (Bound<PyAny>, Status)) -> Result<Self, Self::Error> {
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<PyAny>, Status)) -> Result<Self, Self::Error> {
Ok(Response::with_content_type(
status,
APP_JSON,
json::dumps(&val)?.into(),
))
}
}

impl From<Status> 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())
}
}

Expand All @@ -107,10 +84,9 @@ impl From<PyErr> 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())
})
}
}
Expand Down
Loading
Loading