sveltekit-python-vercel 0.4.1 → 1.0.2
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.
- package/README.md +45 -116
- package/package.json +1 -1
- package/esm/src/vite/mod.js +0 -136
- package/esm/src/vite/sveltekit_python_vercel/__init__.py +0 -0
- package/esm/src/vite/sveltekit_python_vercel/bin.mjs +0 -6
- package/esm/src/vite/sveltekit_python_vercel/build.py +0 -45
- package/esm/src/vite/sveltekit_python_vercel/deploy.py +0 -55
- package/esm/src/vite/sveltekit_python_vercel/serve.py +0 -82
- package/types/src/vite/mod.d.ts +0 -8
package/README.md
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
<p align="middle">
|
|
2
2
|
<img width="100" alt="image" src="https://user-images.githubusercontent.com/20548516/218344678-d41f4c4a-6b1b-48cc-8553-2b9fbe2169d6.png"/>
|
|
3
|
-
<img width="100" alt="image" src="https://
|
|
4
|
-
<img width="100" alt="image" src="https://
|
|
3
|
+
<img width="100" alt="image" src="https://avatars.githubusercontent.com/u/1525981?s=200&v=4"/>
|
|
4
|
+
<img width="100" alt="image" src="https://avatars.githubusercontent.com/u/14985020?s=200&v=4"/>
|
|
5
5
|
</p>
|
|
6
6
|
|
|
7
7
|
# sveltekit-python-vercel
|
|
@@ -22,7 +22,7 @@ Write Python endpoints in [SvelteKit](https://kit.svelte.dev/) and seamlessly de
|
|
|
22
22
|
## Current Features
|
|
23
23
|
|
|
24
24
|
- Write `+server.py` files nearly the same way you would write `+server.js` files
|
|
25
|
-
- Deploy
|
|
25
|
+
- Deploy automatically to Vercel Serverless (Python 3.12 runtime)
|
|
26
26
|
|
|
27
27
|
## Installing
|
|
28
28
|
|
|
@@ -36,17 +36,15 @@ Write Python endpoints in [SvelteKit](https://kit.svelte.dev/) and seamlessly de
|
|
|
36
36
|
import { sveltekit } from "@sveltejs/kit/vite";
|
|
37
37
|
import { sveltekit_python_vercel } from "sveltekit-python-vercel/vite";
|
|
38
38
|
|
|
39
|
-
export default defineConfig(
|
|
40
|
-
|
|
41
|
-
plugins: [sveltekit_python_vercel(), sveltekit()],
|
|
42
|
-
};
|
|
39
|
+
export default defineConfig({
|
|
40
|
+
plugins: [sveltekit(), ...(await sveltekit_python_vercel())],
|
|
43
41
|
});
|
|
44
42
|
```
|
|
45
43
|
|
|
46
44
|
- Update your `svelte.config.js`:
|
|
47
45
|
|
|
48
46
|
```javascript
|
|
49
|
-
import adapter from "@sveltejs/adapter-vercel";
|
|
47
|
+
import adapter from "@sveltejs/adapter-vercel";
|
|
50
48
|
import { vitePreprocess } from "@sveltejs/kit/vite";
|
|
51
49
|
|
|
52
50
|
/** @type {import('@sveltejs/kit').Config} */
|
|
@@ -63,23 +61,12 @@ Write Python endpoints in [SvelteKit](https://kit.svelte.dev/) and seamlessly de
|
|
|
63
61
|
|
|
64
62
|
- Update your `vercel.json`
|
|
65
63
|
|
|
66
|
-
- The build command
|
|
67
|
-
-
|
|
64
|
+
- The build command first runs `vite build` (which generates `.vercel/output/` via the SvelteKit adapter), then runs our script to write the Python function into that same output directory and patch the routing config.
|
|
65
|
+
- No `routes` or `functions` keys are needed — routing is handled automatically via the [Vercel Build Output API](https://vercel.com/docs/build-output-api/v3).
|
|
68
66
|
|
|
69
67
|
```json
|
|
70
68
|
{
|
|
71
|
-
"buildCommand": "node ./node_modules/sveltekit-python-vercel/esm/src/vite/sveltekit_python_vercel/bin.mjs
|
|
72
|
-
"functions": {
|
|
73
|
-
"api/**/*.py": {
|
|
74
|
-
"runtime": "@vercel/python@3.0.7"
|
|
75
|
-
}
|
|
76
|
-
},
|
|
77
|
-
"routes": [
|
|
78
|
-
{
|
|
79
|
-
"src": "/api/(.*)",
|
|
80
|
-
"dest": "api/index.py"
|
|
81
|
-
}
|
|
82
|
-
]
|
|
69
|
+
"buildCommand": "vite build; node ./node_modules/sveltekit-python-vercel/esm/src/vite/sveltekit_python_vercel/bin.mjs"
|
|
83
70
|
}
|
|
84
71
|
```
|
|
85
72
|
|
|
@@ -87,112 +74,59 @@ Write Python endpoints in [SvelteKit](https://kit.svelte.dev/) and seamlessly de
|
|
|
87
74
|
|
|
88
75
|
## Testing Locally
|
|
89
76
|
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
- Run `poetry init` to create a new virtual environment, and follow the steps. Or simply create a `pyproject.toml` like the one below.
|
|
93
|
-
|
|
94
|
-
```toml
|
|
95
|
-
[tool.poetry]
|
|
96
|
-
name = "sveltekit-python-example"
|
|
97
|
-
version = "0.1.0"
|
|
98
|
-
description = ""
|
|
99
|
-
authors = ["Your Name <email@gmail.com>"]
|
|
100
|
-
readme = "README.md"
|
|
101
|
-
|
|
102
|
-
[tool.poetry.dependencies]
|
|
103
|
-
python = "^3.9"
|
|
104
|
-
fastapi = "^0.95.2"
|
|
105
|
-
uvicorn = "^0.22.0"
|
|
106
|
-
|
|
107
|
-
[tool.poetry.group.dev.dependencies]
|
|
108
|
-
watchfiles = "^0.19.0"
|
|
109
|
-
|
|
110
|
-
[build-system]
|
|
111
|
-
requires = ["poetry-core"]
|
|
112
|
-
build-backend = "poetry.core.masonry.api"
|
|
113
|
-
```
|
|
114
|
-
|
|
115
|
-
- Required packages are python3.9 (that is what Vercel's runtime uses), `fastapi`, and `uvicorn`.
|
|
116
|
-
- Install whatever other dependencies you need from pypi using `poetry add package-name`
|
|
77
|
+
[uv](https://docs.astral.sh/uv/) is recommended for managing your Python environment.
|
|
117
78
|
|
|
118
|
-
-
|
|
119
|
-
-
|
|
120
|
-
|
|
79
|
+
- Run `uv init --python 3.12` to create a `pyproject.toml` pinned to Python 3.12 (the same version Vercel's runtime uses).
|
|
80
|
+
- Add the required packages: `uv add fastapi uvicorn`
|
|
81
|
+
- Add any other dependencies you need: `uv add numpy pandas ...`
|
|
82
|
+
- Run your dev server inside uv:
|
|
83
|
+
- `uv run pnpm dev`
|
|
84
|
+
- You should see both the usual SvelteKit server start and the uvicorn server (by default on `http://0.0.0.0:8000`) in the console.
|
|
121
85
|
|
|
122
86
|
## Deploying to Vercel
|
|
123
87
|
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
- When you make changes to your python endpoints, you have to manually regenerate the `/api` folder by running:
|
|
127
|
-
1. `poetry export -f requirements.txt --output requirements.txt --without-hashes`
|
|
128
|
-
2. `node ./node_modules/sveltekit-python-vercel/esm/src/vite/sveltekit_python_vercel/bin.mjs`
|
|
129
|
-
- Then commit `requirements.txt` and the changes in `/api` and push.
|
|
88
|
+
Just push to your repository — no extra steps required.
|
|
130
89
|
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
...
|
|
137
|
-
"py-update": "poetry export -f requirements.txt --output requirements.txt --without-hashes; node ./node_modules/sveltekit-python-vercel/esm/src/vite/sveltekit_python_vercel/bin.mjs"
|
|
138
|
-
}
|
|
139
|
-
```
|
|
140
|
-
- and then just run `pnpm py-update`
|
|
90
|
+
- The `buildCommand` in `vercel.json` handles everything automatically:
|
|
91
|
+
1. `vite build` runs the SvelteKit build and writes `.vercel/output/` via `@sveltejs/adapter-vercel`
|
|
92
|
+
2. `bin.mjs` then writes your Python endpoints into `.vercel/output/functions/` using the [Build Output API](https://vercel.com/docs/build-output-api/v3) and patches the routing config
|
|
93
|
+
- Your `+server.py` files and dependency declarations (`requirements.txt`, `pyproject.toml`, `Pipfile`, etc.) are bundled automatically — there is no need to commit an `/api` folder or manually generate a `requirements.txt`.
|
|
94
|
+
- Python packages are pre-installed into the function bundle at build time using `pip install --target`, so they are available in Vercel's raw Python 3.12 Lambda environment without any extra configuration.
|
|
141
95
|
|
|
142
96
|
## Example
|
|
143
97
|
|
|
144
98
|
- Frontend: `/src/routes/py/+page.svelte`
|
|
145
99
|
|
|
146
100
|
```html
|
|
147
|
-
<script
|
|
148
|
-
let a = 0;
|
|
149
|
-
let b = 0;
|
|
150
|
-
let total = 0;
|
|
101
|
+
<script>
|
|
102
|
+
let a = $state(0);
|
|
103
|
+
let b = $state(0);
|
|
104
|
+
let total = $state(0);
|
|
151
105
|
|
|
152
106
|
async function pyAddPost() {
|
|
153
|
-
const
|
|
107
|
+
const res = await fetch("/py", {
|
|
154
108
|
method: "POST",
|
|
155
109
|
body: JSON.stringify({ a, b }),
|
|
156
|
-
headers: {
|
|
157
|
-
"content-type": "application/json",
|
|
158
|
-
},
|
|
110
|
+
headers: { "content-type": "application/json" },
|
|
159
111
|
});
|
|
160
|
-
|
|
161
|
-
total = res.sum;
|
|
112
|
+
total = (await res.json()).sum;
|
|
162
113
|
}
|
|
163
114
|
|
|
164
115
|
async function pyAddGet() {
|
|
165
|
-
const
|
|
166
|
-
|
|
167
|
-
headers: {
|
|
168
|
-
"content-type": "application/json",
|
|
169
|
-
},
|
|
170
|
-
});
|
|
171
|
-
|
|
172
|
-
let res = await response.json();
|
|
173
|
-
total = res.sum;
|
|
116
|
+
const res = await fetch(`/py?a=${a}&b=${b}`);
|
|
117
|
+
total = (await res.json()).sum;
|
|
174
118
|
}
|
|
175
119
|
</script>
|
|
176
120
|
|
|
177
|
-
<h1>
|
|
178
|
-
|
|
179
|
-
<
|
|
180
|
-
<
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
<
|
|
186
|
-
|
|
187
|
-
<br />
|
|
188
|
-
|
|
189
|
-
<h3>GET Example</h3>
|
|
190
|
-
<form>
|
|
191
|
-
<input type="number" name="a" placeholder="Number 1" bind:value="{a}" />
|
|
192
|
-
<input type="number" name="b" placeholder="Number 2" bind:value="{b}" />
|
|
193
|
-
<button on:click|preventDefault="{pyAddGet}">Add</button>
|
|
194
|
-
</form>
|
|
195
|
-
<h4>Total: {total}</h4>
|
|
121
|
+
<h1>SvelteKit page with a Python backend</h1>
|
|
122
|
+
|
|
123
|
+
<label>a: <input type="number" bind:value={a} /></label>
|
|
124
|
+
<label>b: <input type="number" bind:value={b} /></label>
|
|
125
|
+
|
|
126
|
+
<button type="button" onclick={pyAddPost}>POST</button>
|
|
127
|
+
<button type="button" onclick={pyAddGet}>GET</button>
|
|
128
|
+
|
|
129
|
+
<p>Total: {total}</p>
|
|
196
130
|
```
|
|
197
131
|
|
|
198
132
|
- Backend: `/src/routes/py/+server.py`
|
|
@@ -212,17 +146,12 @@ Note:
|
|
|
212
146
|
|
|
213
147
|
async def GET(a: float, b: float):
|
|
214
148
|
return {"sum": a + b}
|
|
215
|
-
|
|
216
149
|
```
|
|
217
150
|
|
|
218
151
|
### Backend Caveats
|
|
219
152
|
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
- `GET` endpoints are directly fed the parameters from the url, so when you define an endpoint
|
|
223
|
-
- All other endpoints are fed the body as a JSON. The recommended way to deal with this is to use a pydantic model and pass it as the singular input to the function.
|
|
224
|
-
|
|
225
|
-
See the example above.
|
|
153
|
+
- `GET` endpoints receive query parameters directly as function arguments. Type annotations are used for coercion (e.g. `a: float` parses `?a=3` as `3.0`).
|
|
154
|
+
- All other HTTP methods receive the request body as JSON. The recommended pattern is a Pydantic model as the single argument — FastAPI handles validation and parsing automatically.
|
|
226
155
|
|
|
227
156
|
## Fork of `sveltekit-modal`
|
|
228
157
|
|
|
@@ -231,8 +160,8 @@ Check out the awesome [sveltekit-modal](https://github.com/semicognitive/sveltek
|
|
|
231
160
|
## Possible future plans
|
|
232
161
|
|
|
233
162
|
- [X] Add hot reloading in dev mode
|
|
234
|
-
- [
|
|
235
|
-
- [
|
|
163
|
+
- [X] Generate endpoints automatically during build (via Vercel Build Output API)
|
|
164
|
+
- [X] Auto-bundle requirements.txt / pyproject.toml / Pipfile at build time
|
|
236
165
|
- [ ] Add form actions
|
|
237
166
|
- [ ] Add load functions
|
|
238
|
-
- [ ] Add helper functions to automatically call API endpoints in project
|
|
167
|
+
- [ ] Add helper functions to automatically call API endpoints in project
|
package/package.json
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
"module": "./esm/mod.js",
|
|
3
3
|
"types": "./types/mod.d.ts",
|
|
4
4
|
"name": "sveltekit-python-vercel",
|
|
5
|
-
"version": "
|
|
5
|
+
"version": "1.0.2",
|
|
6
6
|
"description": "Write Sveltekit server endpoints in Python and seamlessly deploy to Vercel",
|
|
7
7
|
"repository": {
|
|
8
8
|
"type": "git",
|
package/esm/src/vite/mod.js
DELETED
|
@@ -1,136 +0,0 @@
|
|
|
1
|
-
import { loadEnv } from "vite";
|
|
2
|
-
import { $ as run$, cd as cd$, which, path, chalk, } from "zx";
|
|
3
|
-
const get_pyServerEndpointAsString = (app_url, serve = false) => `
|
|
4
|
-
const handle = (method) => (async ({ request, fetch, url }) => {
|
|
5
|
-
const headers = new Headers()
|
|
6
|
-
headers.append('content-type', request.headers.get('content-type'));
|
|
7
|
-
headers.append('accept', request.headers.get('accept'));
|
|
8
|
-
|
|
9
|
-
let fullURL;
|
|
10
|
-
|
|
11
|
-
if (${serve}) {
|
|
12
|
-
fullURL = new URL(url.pathname, new URL('${app_url}')) + url.search;
|
|
13
|
-
} else {
|
|
14
|
-
fullURL = new URL('/api' + url.pathname, new URL('${app_url}')) + url.search;
|
|
15
|
-
}
|
|
16
|
-
|
|
17
|
-
console.log(\`PY: Reached python endpoint of \${method} \${fullURL}\`)
|
|
18
|
-
let requestBody = await request.clone().text();
|
|
19
|
-
console.log(\`PY: Body: \${requestBody}\`);
|
|
20
|
-
|
|
21
|
-
if (method === 'GET') {
|
|
22
|
-
requestBody = null;
|
|
23
|
-
}
|
|
24
|
-
|
|
25
|
-
return fetch(fullURL, { headers, method, body: requestBody, signal: request.signal, duplex: 'half' });
|
|
26
|
-
});
|
|
27
|
-
|
|
28
|
-
export const GET = handle('GET');
|
|
29
|
-
export const POST = handle('POST');
|
|
30
|
-
export const PATCH = handle('PATCH');
|
|
31
|
-
export const PUT = handle('PUT');
|
|
32
|
-
export const DELETE = handle('DELETE');
|
|
33
|
-
`;
|
|
34
|
-
export async function sveltekit_python_vercel(opts = {}) {
|
|
35
|
-
const child_processes = [];
|
|
36
|
-
async function kill_all_process() {
|
|
37
|
-
for (const ps of child_processes) {
|
|
38
|
-
await ps.kill();
|
|
39
|
-
await ps.exitCode;
|
|
40
|
-
}
|
|
41
|
-
}
|
|
42
|
-
let sveltekit_url;
|
|
43
|
-
const plugin_python_serve = {
|
|
44
|
-
name: "vite-plugin-sveltekit-python-serve",
|
|
45
|
-
apply: "serve",
|
|
46
|
-
async closeBundle() {
|
|
47
|
-
await kill_all_process();
|
|
48
|
-
},
|
|
49
|
-
async configureServer({ config }) {
|
|
50
|
-
const packagelocation = path.join(config.root, "node_modules", "sveltekit-python-vercel", "esm/src/vite");
|
|
51
|
-
// copy asll +server.py files to package directory
|
|
52
|
-
run$.verbose = false;
|
|
53
|
-
run$.env.PYTHONDONTWRITEBYTECODE = "1";
|
|
54
|
-
cd$(packagelocation);
|
|
55
|
-
const python_path = opts.python_path ?? (await which("python3"));
|
|
56
|
-
const host = opts.host ?? "0.0.0.0";
|
|
57
|
-
const port = opts.port ?? 8000;
|
|
58
|
-
const local_process = run$ `${python_path} -m sveltekit_python_vercel.serve --host ${host} --port ${port} --root ${config.root}`;
|
|
59
|
-
child_processes.push(local_process);
|
|
60
|
-
sveltekit_url ??= new URL(`http://${host}:${port}`);
|
|
61
|
-
cd$(config.root);
|
|
62
|
-
// local_process.quiet(); // let it be loud for now
|
|
63
|
-
local_process.nothrow();
|
|
64
|
-
local_process.stderr.on("data", (s) => {
|
|
65
|
-
console.log(s.toString().trimEnd()); //Logs stderr always and all of stdout if 'log': True
|
|
66
|
-
});
|
|
67
|
-
local_process.stderr.on("error", (s) => {
|
|
68
|
-
console.error(chalk.red("Error: Python Serve Failed"));
|
|
69
|
-
console.error(s.toString().trimEnd());
|
|
70
|
-
});
|
|
71
|
-
local_process.stdout.on("error", (s) => {
|
|
72
|
-
console.error(chalk.red("Error: Python Serve Failed"));
|
|
73
|
-
console.error(s.toString().trimEnd());
|
|
74
|
-
});
|
|
75
|
-
},
|
|
76
|
-
};
|
|
77
|
-
const plugin_python_build = {
|
|
78
|
-
name: "vite-plugin-sveltekit_python-build",
|
|
79
|
-
apply: "build",
|
|
80
|
-
async configResolved(config) {
|
|
81
|
-
console.log("PY: BUILD DEBUG");
|
|
82
|
-
console.log("PY: ROOT PATH: " + config.root);
|
|
83
|
-
console.log("PY: LOADED VERCEL URL: " + loadEnv("", config.root, "").VERCEL_URL);
|
|
84
|
-
const packagelocation = path.join(config.root, "node_modules", "sveltekit-python-vercel", "esm/src/vite");
|
|
85
|
-
console.log("PY: PACKAGE LOCATION: " + packagelocation);
|
|
86
|
-
const python_path = opts.python_path ?? (await which("python3"));
|
|
87
|
-
await run$ `cd ${packagelocation}`;
|
|
88
|
-
await run$ `${python_path} ${packagelocation}/sveltekit_python_vercel/build.py --root ${config.root}`;
|
|
89
|
-
// check if env var starts with http
|
|
90
|
-
let httpPrefix = "";
|
|
91
|
-
if (!loadEnv("", config.root, "").VERCEL_URL.startsWith("http")) {
|
|
92
|
-
httpPrefix = "https://";
|
|
93
|
-
}
|
|
94
|
-
const api_url = path.join(httpPrefix + loadEnv("", config.root, "").VERCEL_URL);
|
|
95
|
-
// get current Vercel deploy URL
|
|
96
|
-
sveltekit_url = new URL(api_url);
|
|
97
|
-
console.log("PY: Build API URL: " + sveltekit_url.toString());
|
|
98
|
-
},
|
|
99
|
-
};
|
|
100
|
-
const plugin_py_server_endpoint_serve = {
|
|
101
|
-
name: "vite-plugin-sveltekit_python-server-endpoint",
|
|
102
|
-
apply: "serve",
|
|
103
|
-
transform(src, id) {
|
|
104
|
-
// console.log("Transform function called for", id); // Add this line
|
|
105
|
-
if (/\.py$/.test(id)) {
|
|
106
|
-
if (sveltekit_url === undefined)
|
|
107
|
-
throw new Error(`${plugin_python_serve.name} failed to produce a sveltekit_url`);
|
|
108
|
-
return {
|
|
109
|
-
code: get_pyServerEndpointAsString(sveltekit_url, true),
|
|
110
|
-
map: null, // provide source map if available
|
|
111
|
-
};
|
|
112
|
-
}
|
|
113
|
-
},
|
|
114
|
-
};
|
|
115
|
-
const plugin_py_server_endpoint_build = {
|
|
116
|
-
name: "vite-plugin-sveltekit_python-server-endpoint",
|
|
117
|
-
apply: "build",
|
|
118
|
-
transform(src, id) {
|
|
119
|
-
// console.log("Transform function called for", id); // Add this line
|
|
120
|
-
if (/\.py$/.test(id)) {
|
|
121
|
-
if (sveltekit_url === undefined)
|
|
122
|
-
throw new Error(`${plugin_python_serve.name} failed to produce a sveltekit_url`);
|
|
123
|
-
return {
|
|
124
|
-
code: get_pyServerEndpointAsString(sveltekit_url, false),
|
|
125
|
-
map: null, // provide source map if available
|
|
126
|
-
};
|
|
127
|
-
}
|
|
128
|
-
},
|
|
129
|
-
};
|
|
130
|
-
return [
|
|
131
|
-
plugin_python_serve,
|
|
132
|
-
plugin_python_build,
|
|
133
|
-
plugin_py_server_endpoint_serve,
|
|
134
|
-
plugin_py_server_endpoint_build,
|
|
135
|
-
];
|
|
136
|
-
}
|
|
File without changes
|
|
@@ -1,6 +0,0 @@
|
|
|
1
|
-
#!/usr/bin/env zx --install
|
|
2
|
-
|
|
3
|
-
import {$} from "zx";
|
|
4
|
-
|
|
5
|
-
const python_path = await $`which python3`;
|
|
6
|
-
await $`${python_path} ./node_modules/sveltekit-python-vercel/esm/src/vite/sveltekit_python_vercel/build.py --root . --packagedir ./node_modules/sveltekit-python-vercel/esm/src/vite/sveltekit_python_vercel`;
|
|
@@ -1,45 +0,0 @@
|
|
|
1
|
-
import argparse
|
|
2
|
-
import shutil
|
|
3
|
-
import glob
|
|
4
|
-
|
|
5
|
-
from pathlib import Path, PurePosixPath
|
|
6
|
-
|
|
7
|
-
parser = argparse.ArgumentParser(description="Run Sveltekit Python Deployment")
|
|
8
|
-
parser.add_argument("--root", default=".", help="Root directory of Vercel project")
|
|
9
|
-
parser.add_argument("--packagedir", default=None, help="Root directory of Vercel project")
|
|
10
|
-
args = parser.parse_args()
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
root_dir = Path(args.root).absolute()
|
|
14
|
-
api_dir = root_dir / "api"
|
|
15
|
-
|
|
16
|
-
if not api_dir.exists():
|
|
17
|
-
api_dir.mkdir()
|
|
18
|
-
|
|
19
|
-
if args.packagedir:
|
|
20
|
-
shutil.copy(Path(args.packagedir).absolute() / "deploy.py", api_dir / "index.py")
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
# Add all +server.py routes to web_app
|
|
24
|
-
for module_path in glob.glob(str(root_dir / 'src/routes/**/+server.py'), recursive=True):
|
|
25
|
-
|
|
26
|
-
# replace the root_dir with api_dir
|
|
27
|
-
api_route = api_dir / Path(module_path).absolute().relative_to(root_dir / "src/routes")
|
|
28
|
-
|
|
29
|
-
# replace square brackets with curly brackets
|
|
30
|
-
api_route = Path(str(api_route).replace('[', '{').replace(']', '}'))
|
|
31
|
-
|
|
32
|
-
# remove any groups from the URL
|
|
33
|
-
api_route = Path(str(PurePosixPath(*[part for part in PurePosixPath(api_route).parts if not part.startswith("(") and not part.endswith(")")])))
|
|
34
|
-
|
|
35
|
-
if not api_route.parent.exists():
|
|
36
|
-
api_route.parent.mkdir(parents=True)
|
|
37
|
-
|
|
38
|
-
# copy module path to api_route
|
|
39
|
-
shutil.copy(module_path, api_route.parent)
|
|
40
|
-
|
|
41
|
-
# create __init__.py if it doesn't exist
|
|
42
|
-
if not (api_route.parent / "__init__.py").exists():
|
|
43
|
-
(api_route.parent / "__init__.py").touch()
|
|
44
|
-
|
|
45
|
-
print(f"PYTHON ENDPOINT: Copied {module_path} to {api_route.parent}")
|
|
@@ -1,55 +0,0 @@
|
|
|
1
|
-
import glob
|
|
2
|
-
import importlib
|
|
3
|
-
import importlib.util
|
|
4
|
-
import os
|
|
5
|
-
from pathlib import Path, PurePosixPath
|
|
6
|
-
|
|
7
|
-
from fastapi import FastAPI, Request
|
|
8
|
-
from fastapi.responses import JSONResponse
|
|
9
|
-
|
|
10
|
-
app = FastAPI()
|
|
11
|
-
|
|
12
|
-
async def hello_world():
|
|
13
|
-
return {"message": "Hello World!"}
|
|
14
|
-
|
|
15
|
-
app.add_api_route("/api", hello_world, methods=["GET"])
|
|
16
|
-
|
|
17
|
-
# Add all +server.py routes to web_app
|
|
18
|
-
for module_path in glob.glob('./**/+server.py', recursive=True):
|
|
19
|
-
|
|
20
|
-
module_name_joined = module_path[2:].replace(os.path.sep, '.')
|
|
21
|
-
module_name, module_package = module_name_joined.rsplit('.', maxsplit=1)
|
|
22
|
-
|
|
23
|
-
api_route = module_path[1:] if module_path.startswith('./') else module_path
|
|
24
|
-
api_route = str(Path(api_route).parent)
|
|
25
|
-
|
|
26
|
-
# Replace square brackets with curly brackets
|
|
27
|
-
api_route = api_route.replace('[', '{').replace(']', '}')
|
|
28
|
-
|
|
29
|
-
# remove any groups from the URL
|
|
30
|
-
api_route = str(PurePosixPath(*[part for part in PurePosixPath(api_route).parts if not part.startswith("(") and not part.endswith(")")]))
|
|
31
|
-
|
|
32
|
-
mod = importlib.import_module(module_name, module_package)
|
|
33
|
-
|
|
34
|
-
# Add endpoints
|
|
35
|
-
for method in ["GET", "POST", "PATCH", "PUT", "DELETE"]:
|
|
36
|
-
|
|
37
|
-
# Check for duplicate methods
|
|
38
|
-
if hasattr(mod, method) and hasattr(mod, method.lower()):
|
|
39
|
-
raise Exception(
|
|
40
|
-
f"Duplicate method {method} and {method.lower()} in {api_route}"
|
|
41
|
-
)
|
|
42
|
-
|
|
43
|
-
elif hasattr(mod, method):
|
|
44
|
-
app.add_api_route(api_route, getattr(mod, method), methods=[method])
|
|
45
|
-
print(f"PYTHON ENDPOINT: Added {module_path} [{method}] at {api_route}")
|
|
46
|
-
elif hasattr(mod, method.lower()):
|
|
47
|
-
app.add_api_route(api_route, getattr(mod, method.lower()), methods=[method])
|
|
48
|
-
print(f"PYTHON ENDPOINT: Added {module_path} [{method}] at {api_route}")
|
|
49
|
-
|
|
50
|
-
@app.exception_handler(Exception)
|
|
51
|
-
async def unicorn_exception_handler(request: Request, exc: Exception):
|
|
52
|
-
return JSONResponse(
|
|
53
|
-
status_code=500,
|
|
54
|
-
content={"error": f"{exc}"},
|
|
55
|
-
)
|
|
@@ -1,82 +0,0 @@
|
|
|
1
|
-
import argparse
|
|
2
|
-
import glob
|
|
3
|
-
import importlib
|
|
4
|
-
import importlib.util
|
|
5
|
-
import shutil
|
|
6
|
-
from pathlib import Path, PurePosixPath
|
|
7
|
-
|
|
8
|
-
import uvicorn
|
|
9
|
-
from fastapi import FastAPI
|
|
10
|
-
|
|
11
|
-
parser = argparse.ArgumentParser(description="Run Sveltekit Python Server")
|
|
12
|
-
parser.add_argument("--host", default="0.0.0.0", help="Server hostname")
|
|
13
|
-
parser.add_argument("--port", type=int, default=8000, help="Server port")
|
|
14
|
-
parser.add_argument("--root", default=".", help="Directory where the API is located")
|
|
15
|
-
args = parser.parse_args()
|
|
16
|
-
|
|
17
|
-
app = FastAPI()
|
|
18
|
-
|
|
19
|
-
root_dir = Path(args.root).absolute()
|
|
20
|
-
|
|
21
|
-
api_dir = Path("./sveltekit_python_vercel").absolute()
|
|
22
|
-
|
|
23
|
-
route_dir = root_dir.joinpath("src/routes")
|
|
24
|
-
|
|
25
|
-
watch_modules = [] # list of modules to watch for changes
|
|
26
|
-
|
|
27
|
-
for module_path in glob.glob(
|
|
28
|
-
route_dir.joinpath("**/+server.py").as_posix(), recursive=True
|
|
29
|
-
):
|
|
30
|
-
abs_module_path = Path(module_path).absolute()
|
|
31
|
-
|
|
32
|
-
watch_modules.append(abs_module_path.parent.as_posix())
|
|
33
|
-
|
|
34
|
-
api_route = api_dir.joinpath(abs_module_path.relative_to(root_dir / "src/routes"))
|
|
35
|
-
|
|
36
|
-
if not api_route.parent.exists():
|
|
37
|
-
api_route.parent.mkdir(parents=True)
|
|
38
|
-
|
|
39
|
-
# copy module path to api_route
|
|
40
|
-
shutil.copy(module_path, api_route.parent)
|
|
41
|
-
|
|
42
|
-
module_name = api_route.stem
|
|
43
|
-
|
|
44
|
-
spec = importlib.util.spec_from_file_location(module_name, api_route)
|
|
45
|
-
mod = importlib.util.module_from_spec(spec)
|
|
46
|
-
spec.loader.exec_module(mod)
|
|
47
|
-
|
|
48
|
-
# Get the relative path of the module from the API directory
|
|
49
|
-
rel_path = api_route.relative_to(api_dir)
|
|
50
|
-
|
|
51
|
-
# Convert the relative path to a string and remove the file extension
|
|
52
|
-
api_path = f"/{rel_path.parent}"
|
|
53
|
-
|
|
54
|
-
# Replace square brackets with curly brackets
|
|
55
|
-
api_path = api_path.replace("[", "{").replace("]", "}")
|
|
56
|
-
|
|
57
|
-
# remove any groups from the URL
|
|
58
|
-
api_path = str(PurePosixPath(*[part for part in PurePosixPath(api_path).parts if not part.startswith("(") and not part.endswith(")")]))
|
|
59
|
-
|
|
60
|
-
# Add endpoints
|
|
61
|
-
for method in ["GET", "POST", "PATCH", "PUT", "DELETE"]:
|
|
62
|
-
# Check for duplicate methods
|
|
63
|
-
if hasattr(mod, method) and hasattr(mod, method.lower()):
|
|
64
|
-
raise Exception(
|
|
65
|
-
f"Duplicate method {method} and {method.lower()} in {api_route}"
|
|
66
|
-
)
|
|
67
|
-
elif hasattr(mod, method):
|
|
68
|
-
app.add_api_route(api_path, getattr(mod, method), methods=[method])
|
|
69
|
-
elif hasattr(mod, method.lower()):
|
|
70
|
-
app.add_api_route(api_path, getattr(mod, method.lower()), methods=[method])
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
if __name__ == "__main__":
|
|
74
|
-
uvicorn.run(
|
|
75
|
-
"sveltekit_python_vercel.serve:app",
|
|
76
|
-
host=args.host,
|
|
77
|
-
port=args.port,
|
|
78
|
-
log_level="info",
|
|
79
|
-
reload=True,
|
|
80
|
-
reload_includes=[*set(watch_modules)],
|
|
81
|
-
reload_excludes=[api_dir.as_posix()],
|
|
82
|
-
)
|
package/types/src/vite/mod.d.ts
DELETED