swadhinbiswas 📦 v2.0.8: security fixes, documentation, testing improvements · 7/28/2026
3e270a0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
use pyo3::prelude::*;
use pyo3_async_runtimes::tokio::future_into_py;
use std::fs;
use std::io::{Read, Seek, SeekFrom, Write};
use std::path::PathBuf;
use std::sync::{Arc, Mutex};
struct Inner {
temp_path: PathBuf,
pos: u64,
closed: bool,
}
/// Python-facing `UploadFile` class.
///
/// Mirrors FastAPI/Starlette's `UploadFile`: exposes `filename`, `content_type`,
/// `size`, `headers` and a standard file object via `.file`, plus async
/// `read`/`write`/`seek`/`close` that perform the (blocking) file I/O on
/// Rust's blocking thread pool so they stay awaitable without stalling the
/// async runtime. The actual bytes live in a Rust-managed temp file (written by
/// `justapi-core`'s multipart parser), keeping the hot path in Rust.
#[pyclass(name = "UploadFile")]
pub struct UploadFile {
#[pyo3(get)]
pub filename: String,
#[pyo3(get)]
pub content_type: String,
#[pyo3(get)]
pub size: u64,
#[pyo3(get)]
pub headers: Py<pyo3::types::PyDict>,
inner: Arc<Mutex<Inner>>,
}
#[pymethods]
impl UploadFile {
/// The underlying standard Python file object (blocking, not async).
/// Provided for parity with FastAPI; prefer the async `read`/`write`.
#[getter]
fn file(&self, py: Python<'_>) -> PyResult<Py<PyAny>> {
let path = self.inner.lock().unwrap_or_else(|e| e.into_inner()).temp_path.clone();
let io = py.import("io")?;
let f = io.call_method1("open", (path, "rb"))?;
Ok(f.unbind())
}
/// Read up to `size` bytes from the current position. `size < 0` (default)
/// reads the remainder of the file. Runs on the blocking pool.
#[pyo3(signature = (size = -1))]
fn read<'py>(&self, py: Python<'py>, size: i64) -> PyResult<Bound<'py, PyAny>> {
let inner = self.inner.clone();
future_into_py(py, async move {
let inner = inner.clone();
let data = tokio::task::spawn_blocking(move || -> PyResult<Vec<u8>> {
let mut g = inner.lock().unwrap_or_else(|e| e.into_inner());
if g.closed {
return Err(pyo3::exceptions::PyValueError::new_err("file is closed"));
}
let mut file = fs::File::open(&g.temp_path)?;
file.seek(SeekFrom::Start(g.pos))?;
let meta = fs::metadata(&g.temp_path)?;
let remaining = meta.len().saturating_sub(g.pos);
let limit: usize = if size < 0 { usize::MAX } else { size as usize };
let to_read = (remaining as usize).min(limit);
let mut buf = vec![0u8; to_read];
let n = file.read(&mut buf)?;
buf.truncate(n);
g.pos += n as u64;
Ok(buf)
})
.await
.map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(e.to_string()))??;
Ok(data)
})
}
/// Write `data` at the current position. Runs on the blocking pool.
fn write<'py>(&self, py: Python<'py>, data: Vec<u8>) -> PyResult<Bound<'py, PyAny>> {
let inner = self.inner.clone();
future_into_py(py, async move {
let inner = inner.clone();
tokio::task::spawn_blocking(move || -> PyResult<()> {
let mut g = inner.lock().unwrap_or_else(|e| e.into_inner());
if g.closed {
return Err(pyo3::exceptions::PyValueError::new_err("file is closed"));
}
let mut file = fs::OpenOptions::new()
.write(true)
.create(true)
.truncate(false)
.open(&g.temp_path)?;
file.seek(SeekFrom::Start(g.pos))?;
file.write_all(&data)?;
g.pos += data.len() as u64;
Ok(())
})
.await
.map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(e.to_string()))??;
Ok(())
})
}
/// Move to `offset` bytes from the start of the file. Returns the new
/// position. Runs on the blocking pool.
fn seek<'py>(&self, py: Python<'py>, offset: i64) -> PyResult<Bound<'py, PyAny>> {
let inner = self.inner.clone();
future_into_py(py, async move {
let inner = inner.clone();
let new_pos = tokio::task::spawn_blocking(move || -> PyResult<u64> {
let mut g = inner.lock().unwrap_or_else(|e| e.into_inner());
if g.closed {
return Err(pyo3::exceptions::PyValueError::new_err("file is closed"));
}
let meta = fs::metadata(&g.temp_path)?;
let len = meta.len();
let pos =
if offset < 0 { len.saturating_sub((-offset) as u64) } else { offset as u64 };
g.pos = pos;
Ok(pos)
})
.await
.map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(e.to_string()))??;
Ok(new_pos)
})
}
/// Close the file and delete the backing temp file. Runs on the blocking
/// pool. Safe to call more than once.
fn close<'py>(&self, py: Python<'py>) -> PyResult<Bound<'py, PyAny>> {
let inner = self.inner.clone();
future_into_py(py, async move {
let inner = inner.clone();
tokio::task::spawn_blocking(move || -> PyResult<()> {
let mut g = inner.lock().unwrap_or_else(|e| e.into_inner());
if g.closed {
return Ok(());
}
g.closed = true;
let _ = fs::remove_file(&g.temp_path);
Ok(())
})
.await
.map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(e.to_string()))??;
Ok(())
})
}
}
impl UploadFile {
pub fn new(
filename: String,
content_type: String,
size: u64,
headers: Py<pyo3::types::PyDict>,
temp_path: PathBuf,
) -> Self {
Self {
filename,
content_type,
size,
headers,
inner: Arc::new(Mutex::new(Inner { temp_path, pos: 0, closed: false })),
}
}
}
impl Drop for UploadFile {
fn drop(&mut self) {
let g = self.inner.lock().unwrap_or_else(|e| e.into_inner());
if !g.closed {
let _ = fs::remove_file(&g.temp_path);
}
}
}