sveltekit-python-vercel 0.1.0
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/LICENSE.md +21 -0
- package/README.md +191 -0
- package/esm/mod.js +1 -0
- package/esm/package.json +3 -0
- package/esm/src/vite/mod.js +137 -0
- package/esm/src/vite/sveltekit_python_vercel/__init__.py +0 -0
- package/esm/src/vite/sveltekit_python_vercel/bin.mjs +6 -0
- package/esm/src/vite/sveltekit_python_vercel/build.py +39 -0
- package/esm/src/vite/sveltekit_python_vercel/deploy.py +54 -0
- package/esm/src/vite/sveltekit_python_vercel/serve.py +76 -0
- package/package.json +53 -0
- package/types/mod.d.ts +2 -0
- package/types/src/vite/mod.d.ts +8 -0
package/LICENSE.md
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2023 SemiCognitive
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,191 @@
|
|
|
1
|
+
<img width="100" alt="image" src="https://user-images.githubusercontent.com/20548516/218344678-d41f4c4a-6b1b-48cc-8553-2b9fbe2169d6.png"/>
|
|
2
|
+
<img width="100" alt="image" src="https://camo.githubusercontent.com/f1ac9955f30176e6183aeeeac1b77354c7a132696fdc77c06ef0f0bec30f258c/68747470733a2f2f6861636b616461792e636f6d2f77702d636f6e74656e742f75706c6f6164732f323031392f30392f707974686f6e2d6c6f676f2e706e67"/>
|
|
3
|
+
<img width="100" alt="image" src="https://camo.githubusercontent.com/add2c9721e333f0043ac938f3dadbc26a282776e01b95b308fcaba5afaf74ae3/68747470733a2f2f6173736574732e76657263656c2e636f6d2f696d6167652f75706c6f61642f76313538383830353835382f7265706f7369746f726965732f76657263656c2f6c6f676f2e706e67"/>
|
|
4
|
+
|
|
5
|
+
# sveltekit-python-vercel
|
|
6
|
+
|
|
7
|
+
Write Python endpoints in [SvelteKit](https://kit.svelte.dev/) and seamlessly deploy them to Vercel.
|
|
8
|
+
|
|
9
|
+
**This is very much in beta.**
|
|
10
|
+
|
|
11
|
+
## Current Features
|
|
12
|
+
|
|
13
|
+
- Write `+server.py` files nearly the same way you would write `+server.js` files
|
|
14
|
+
- These functions deploy automatically to Vercel Serverless
|
|
15
|
+
|
|
16
|
+
## Installing
|
|
17
|
+
|
|
18
|
+
- Open or set up your SvelteKit project
|
|
19
|
+
- Install with `npm i -D sveltekit-python-vercel`
|
|
20
|
+
- Update your `vite.config.js`
|
|
21
|
+
|
|
22
|
+
```javascript
|
|
23
|
+
import { defineConfig } from "vite";
|
|
24
|
+
import { sveltekit } from "@sveltejs/kit/vite";
|
|
25
|
+
import { sveltekit_python_vercel } from "sveltekit-python-vercel/vite";
|
|
26
|
+
|
|
27
|
+
export default defineConfig(({ command, mode }) => {
|
|
28
|
+
return {
|
|
29
|
+
plugins: [sveltekit_python_vercel(), sveltekit()],
|
|
30
|
+
};
|
|
31
|
+
});
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
- Update your `svelte.config.js`:
|
|
35
|
+
|
|
36
|
+
```javascript
|
|
37
|
+
import adapter from "@sveltejs/adapter-vercel";
|
|
38
|
+
import { vitePreprocess } from "@sveltejs/kit/vite";
|
|
39
|
+
|
|
40
|
+
/** @type {import('@sveltejs/kit').Config} */
|
|
41
|
+
const config = {
|
|
42
|
+
preprocess: vitePreprocess(),
|
|
43
|
+
kit: {
|
|
44
|
+
adapter: adapter(),
|
|
45
|
+
moduleExtensions: [".js", ".ts", ".py"], // add ".py" to resolve +server.py endpoints
|
|
46
|
+
},
|
|
47
|
+
};
|
|
48
|
+
|
|
49
|
+
export default config;
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
- Update your `vercel.json`
|
|
53
|
+
- The build command prepares all your endpoints and copies them to the `/api` directory where Vercel looks for functions
|
|
54
|
+
- Functions and Routes tell Vercel how to run and redirect function calls
|
|
55
|
+
```json
|
|
56
|
+
{
|
|
57
|
+
"buildCommand": "node ./node_modules/sveltekit-python-vercel/esm/src/vite/sveltekit_python_vercel/bin.mjs; vite build",
|
|
58
|
+
"functions": {
|
|
59
|
+
"api/**/*.py": {
|
|
60
|
+
"runtime": "@vercel/python@3.0.7"
|
|
61
|
+
}
|
|
62
|
+
},
|
|
63
|
+
"routes": [
|
|
64
|
+
{
|
|
65
|
+
"src": "/api/(.*)",
|
|
66
|
+
"dest": "api/index.py"
|
|
67
|
+
}
|
|
68
|
+
]
|
|
69
|
+
}
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
- Write some `+server.py` endpoints. See the example section below.
|
|
73
|
+
|
|
74
|
+
## Testing Locally
|
|
75
|
+
Using [Poetry](https://python-poetry.org/) to manage your virtual environments with this package is recommended.
|
|
76
|
+
|
|
77
|
+
- Run `poetry init` to create a new virtual environment, and follow the steps. Or simply create a `pyproject.toml` like the one below.
|
|
78
|
+
|
|
79
|
+
```toml
|
|
80
|
+
[tool.poetry]
|
|
81
|
+
name = "sveltekit-python-example"
|
|
82
|
+
version = "0.1.0"
|
|
83
|
+
description = ""
|
|
84
|
+
authors = ["Your Name <email@gmail.com>"]
|
|
85
|
+
readme = "README.md"
|
|
86
|
+
|
|
87
|
+
[tool.poetry.dependencies]
|
|
88
|
+
python = "^3.9"
|
|
89
|
+
fastapi = "^0.95.1"
|
|
90
|
+
uvicorn = "^0.22.0"
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
[build-system]
|
|
94
|
+
requires = ["poetry-core"]
|
|
95
|
+
build-backend = "poetry.core.masonry.api"
|
|
96
|
+
```
|
|
97
|
+
- Required packages are python3.9 (that is what Vercel's runtime uses), `fastapi`, and `uvicorn`.
|
|
98
|
+
- Install whatever other dependencies you need from pypi using `poetry add package-name`
|
|
99
|
+
|
|
100
|
+
- Run `pnpm dev` or `npm dev`
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
## Example
|
|
104
|
+
|
|
105
|
+
- Frontend: `/src/routes/py/+page.svelte`
|
|
106
|
+
```html
|
|
107
|
+
<script lang="ts">
|
|
108
|
+
let a = 0;
|
|
109
|
+
let b = 0;
|
|
110
|
+
let total = 0;
|
|
111
|
+
|
|
112
|
+
async function pyAddPost() {
|
|
113
|
+
const response = await fetch('/py', {
|
|
114
|
+
method: 'POST',
|
|
115
|
+
body: JSON.stringify({ a, b }),
|
|
116
|
+
headers: {
|
|
117
|
+
'content-type': 'application/json'
|
|
118
|
+
}
|
|
119
|
+
});
|
|
120
|
+
let res = await response.json();
|
|
121
|
+
total = res.sum;
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
async function pyAddGet() {
|
|
125
|
+
const response = await fetch(`/py?a=${a}&b=${b}`, {
|
|
126
|
+
method: 'GET',
|
|
127
|
+
headers: {
|
|
128
|
+
'content-type': 'application/json'
|
|
129
|
+
}
|
|
130
|
+
});
|
|
131
|
+
|
|
132
|
+
let res = await response.json();
|
|
133
|
+
total = res.sum;
|
|
134
|
+
}
|
|
135
|
+
</script>
|
|
136
|
+
|
|
137
|
+
<h1>This is a SvelteKit page with a python backend.</h1>
|
|
138
|
+
|
|
139
|
+
<h3>POST Example</h3>
|
|
140
|
+
<form>
|
|
141
|
+
<input type="number" name="a" placeholder="Number 1" bind:value={a} />
|
|
142
|
+
<input type="number" name="b" placeholder="Number 2" bind:value={b} />
|
|
143
|
+
<button on:click|preventDefault={pyAddPost}>Add</button>
|
|
144
|
+
</form>
|
|
145
|
+
<h4>Total: {total}</h4>
|
|
146
|
+
|
|
147
|
+
<br />
|
|
148
|
+
|
|
149
|
+
<h3>GET Example</h3>
|
|
150
|
+
<form>
|
|
151
|
+
<input type="number" name="a" placeholder="Number 1" bind:value={a} />
|
|
152
|
+
<input type="number" name="b" placeholder="Number 2" bind:value={b} />
|
|
153
|
+
<button on:click|preventDefault={pyAddGet}>Add</button>
|
|
154
|
+
</form>
|
|
155
|
+
<h4>Total: {total}</h4>
|
|
156
|
+
```
|
|
157
|
+
|
|
158
|
+
- Backend: `/src/routes/py/+server.py`
|
|
159
|
+
```python
|
|
160
|
+
from pydantic import BaseModel
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
class NumberSet(BaseModel):
|
|
164
|
+
a: float
|
|
165
|
+
b: float
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
async def POST(numberSet: NumberSet):
|
|
169
|
+
return {"sum": float(numberSet.a) + float(numberSet.b)}
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
async def GET(a, b):
|
|
173
|
+
return {"sum": float(a) + float(b)}
|
|
174
|
+
|
|
175
|
+
```
|
|
176
|
+
|
|
177
|
+
## Caveats
|
|
178
|
+
|
|
179
|
+
There are currently a few things that have to be worked around.
|
|
180
|
+
|
|
181
|
+
## Fork of `sveltekit-modal`
|
|
182
|
+
|
|
183
|
+
Check out the awesome [sveltekit-modal](https://github.com/semicognitive/sveltekit-modal) package by [@semicognitive](https://github.com/semicognitive), the original way to get your python code running in SvelteKit. Modal even has GPU support for running an entire ML stack within SvelteKit.
|
|
184
|
+
|
|
185
|
+
## Possible future plans
|
|
186
|
+
|
|
187
|
+
- [ ] Generate endpoints (/api folder) automatically during build
|
|
188
|
+
- [ ] Auto create requirements.txt from pyproject.toml (both related to vercel functions being checked/handled before build)
|
|
189
|
+
- [ ] Add form actions
|
|
190
|
+
- [ ] Add load functions
|
|
191
|
+
- [ ] Add helper functions to automatically call API endpoints in project
|
package/esm/mod.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export default true;
|
package/esm/package.json
ADDED
|
@@ -0,0 +1,137 @@
|
|
|
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(\`Reached python endpoint of \${method} \${fullURL}\`)
|
|
18
|
+
let requestBody = await request.clone().text();
|
|
19
|
+
console.log(\`Body: \${requestBody}\`);
|
|
20
|
+
console.log(\`Content-Type: \${request.headers.get('content-type')}\`);
|
|
21
|
+
|
|
22
|
+
if (method === 'GET') {
|
|
23
|
+
requestBody = null;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
return fetch(fullURL, { headers, method, body: requestBody, signal: request.signal, duplex: 'half' });
|
|
27
|
+
});
|
|
28
|
+
|
|
29
|
+
export const GET = handle('GET');
|
|
30
|
+
export const POST = handle('POST');
|
|
31
|
+
export const PATCH = handle('PATCH');
|
|
32
|
+
export const PUT = handle('PUT');
|
|
33
|
+
export const DELETE = handle('DELETE');
|
|
34
|
+
`;
|
|
35
|
+
export async function sveltekit_python_vercel(opts = {}) {
|
|
36
|
+
const child_processes = [];
|
|
37
|
+
async function kill_all_process() {
|
|
38
|
+
for (const ps of child_processes) {
|
|
39
|
+
await ps.kill();
|
|
40
|
+
await ps.exitCode;
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
let sveltekit_url;
|
|
44
|
+
const plugin_python_serve = {
|
|
45
|
+
name: "vite-plugin-sveltekit-python-serve",
|
|
46
|
+
apply: "serve",
|
|
47
|
+
async closeBundle() {
|
|
48
|
+
await kill_all_process();
|
|
49
|
+
},
|
|
50
|
+
async configureServer({ config }) {
|
|
51
|
+
const packagelocation = path.join(config.root, "node_modules", "sveltekit-python-vercel", "esm/src/vite");
|
|
52
|
+
// copy asll +server.py files to package directory
|
|
53
|
+
run$.verbose = false;
|
|
54
|
+
run$.env.PYTHONDONTWRITEBYTECODE = "1";
|
|
55
|
+
cd$(packagelocation);
|
|
56
|
+
const python_path = opts.python_path ?? (await which("python3"));
|
|
57
|
+
const host = opts.host ?? "0.0.0.0";
|
|
58
|
+
const port = opts.port ?? 8000;
|
|
59
|
+
const local_process = run$ `${python_path} -m sveltekit_python_vercel.serve --host ${host} --port ${port} --root ${config.root}`;
|
|
60
|
+
child_processes.push(local_process);
|
|
61
|
+
sveltekit_url ??= new URL(`http://${host}:${port}`);
|
|
62
|
+
cd$(config.root);
|
|
63
|
+
// local_process.quiet(); // let it be loud for now
|
|
64
|
+
local_process.nothrow();
|
|
65
|
+
local_process.stderr.on("data", (s) => {
|
|
66
|
+
console.log(s.toString().trimEnd()); //Logs stderr always and all of stdout if 'log': True
|
|
67
|
+
});
|
|
68
|
+
local_process.stderr.on("error", (s) => {
|
|
69
|
+
console.error(chalk.red("Error: Python Serve Failed"));
|
|
70
|
+
console.error(s.toString().trimEnd());
|
|
71
|
+
});
|
|
72
|
+
local_process.stdout.on("error", (s) => {
|
|
73
|
+
console.error(chalk.red("Error: Python Serve Failed"));
|
|
74
|
+
console.error(s.toString().trimEnd());
|
|
75
|
+
});
|
|
76
|
+
},
|
|
77
|
+
};
|
|
78
|
+
const plugin_python_build = {
|
|
79
|
+
name: "vite-plugin-sveltekit_python-build",
|
|
80
|
+
apply: "build",
|
|
81
|
+
async configResolved(config) {
|
|
82
|
+
console.log("BUILD DEBUG");
|
|
83
|
+
console.log("ROOT PATH: " + config.root);
|
|
84
|
+
console.log("LOADED VERCEL URL: " + loadEnv("", config.root, "").VERCEL_URL);
|
|
85
|
+
const packagelocation = path.join(config.root, "node_modules", "sveltekit-python-vercel", "esm/src/vite");
|
|
86
|
+
console.log("PACKAGE LOCATION: " + packagelocation);
|
|
87
|
+
const python_path = opts.python_path ?? (await which("python3"));
|
|
88
|
+
await run$ `cd ${packagelocation}`;
|
|
89
|
+
await run$ `${python_path} ${packagelocation}/sveltekit_python_vercel/build.py --root ${config.root}`;
|
|
90
|
+
// check if env var starts with http
|
|
91
|
+
let httpPrefix = "";
|
|
92
|
+
if (!loadEnv("", config.root, "").VERCEL_URL.startsWith("http")) {
|
|
93
|
+
httpPrefix = "https://";
|
|
94
|
+
}
|
|
95
|
+
const api_url = path.join(httpPrefix + loadEnv("", config.root, "").VERCEL_URL);
|
|
96
|
+
// get current Vercel deploy URL
|
|
97
|
+
sveltekit_url = new URL(api_url);
|
|
98
|
+
console.log("Build API URL: " + sveltekit_url.toString());
|
|
99
|
+
},
|
|
100
|
+
};
|
|
101
|
+
const plugin_py_server_endpoint_serve = {
|
|
102
|
+
name: "vite-plugin-sveltekit_python-server-endpoint",
|
|
103
|
+
apply: "serve",
|
|
104
|
+
transform(src, id) {
|
|
105
|
+
// console.log("Transform function called for", id); // Add this line
|
|
106
|
+
if (/\.py$/.test(id)) {
|
|
107
|
+
if (sveltekit_url === undefined)
|
|
108
|
+
throw new Error(`${plugin_python_serve.name} failed to produce a sveltekit_url`);
|
|
109
|
+
return {
|
|
110
|
+
code: get_pyServerEndpointAsString(sveltekit_url, true),
|
|
111
|
+
map: null, // provide source map if available
|
|
112
|
+
};
|
|
113
|
+
}
|
|
114
|
+
},
|
|
115
|
+
};
|
|
116
|
+
const plugin_py_server_endpoint_build = {
|
|
117
|
+
name: "vite-plugin-sveltekit_python-server-endpoint",
|
|
118
|
+
apply: "build",
|
|
119
|
+
transform(src, id) {
|
|
120
|
+
// console.log("Transform function called for", id); // Add this line
|
|
121
|
+
if (/\.py$/.test(id)) {
|
|
122
|
+
if (sveltekit_url === undefined)
|
|
123
|
+
throw new Error(`${plugin_python_serve.name} failed to produce a sveltekit_url`);
|
|
124
|
+
return {
|
|
125
|
+
code: get_pyServerEndpointAsString(sveltekit_url, false),
|
|
126
|
+
map: null, // provide source map if available
|
|
127
|
+
};
|
|
128
|
+
}
|
|
129
|
+
},
|
|
130
|
+
};
|
|
131
|
+
return [
|
|
132
|
+
plugin_python_serve,
|
|
133
|
+
plugin_python_build,
|
|
134
|
+
plugin_py_server_endpoint_serve,
|
|
135
|
+
plugin_py_server_endpoint_build,
|
|
136
|
+
];
|
|
137
|
+
}
|
|
File without changes
|
|
@@ -0,0 +1,6 @@
|
|
|
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`;
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import argparse
|
|
2
|
+
import shutil
|
|
3
|
+
import glob
|
|
4
|
+
|
|
5
|
+
from pathlib import Path
|
|
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
|
+
if not api_route.parent.exists():
|
|
30
|
+
api_route.parent.mkdir(parents=True)
|
|
31
|
+
|
|
32
|
+
# copy module path to api_route
|
|
33
|
+
shutil.copy(module_path, api_route.parent)
|
|
34
|
+
|
|
35
|
+
# create __init__.py if it doesn't exist
|
|
36
|
+
if not (api_route.parent / "__init__.py").exists():
|
|
37
|
+
(api_route.parent / "__init__.py").touch()
|
|
38
|
+
|
|
39
|
+
print(f"PYTHON ENDPOINT: Copied {module_path} to {api_route.parent}")
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import os
|
|
2
|
+
import glob
|
|
3
|
+
import importlib
|
|
4
|
+
import importlib.util
|
|
5
|
+
from pathlib import Path
|
|
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
|
+
mod = importlib.import_module(module_name, module_package)
|
|
27
|
+
|
|
28
|
+
if hasattr(mod, 'GET'):
|
|
29
|
+
app.add_api_route(api_route, mod.GET, methods=["GET"])
|
|
30
|
+
print(f"PYTHON ENDPOINT: Added {module_path} [GET] at {api_route}")
|
|
31
|
+
|
|
32
|
+
if hasattr(mod, 'POST'):
|
|
33
|
+
app.add_api_route(api_route, mod.POST, methods=["POST"])
|
|
34
|
+
print(f"PYTHON ENDPOINT: Added {module_path} [POST] at {api_route}")
|
|
35
|
+
|
|
36
|
+
if hasattr(mod, 'PATCH'):
|
|
37
|
+
app.add_api_route(api_route, mod.PATCH, methods=["PATCH"])
|
|
38
|
+
print(f"PYTHON ENDPOINT: Added {module_path} [PATCH] at {api_route}")
|
|
39
|
+
|
|
40
|
+
if hasattr(mod, 'PUT'):
|
|
41
|
+
app.add_api_route(api_route, mod.PUT, methods=["PUT"])
|
|
42
|
+
print(f"PYTHON ENDPOINT: Added {module_path} [PUT] at {api_route}")
|
|
43
|
+
|
|
44
|
+
if hasattr(mod, 'DELETE'):
|
|
45
|
+
app.add_api_route(api_route, mod.DELETE, methods=["DELETE"])
|
|
46
|
+
print(f"PYTHON ENDPOINT: Added {module_path} [DELETE] at {api_route}")
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
@app.exception_handler(Exception)
|
|
50
|
+
async def unicorn_exception_handler(request: Request, exc: Exception):
|
|
51
|
+
return JSONResponse(
|
|
52
|
+
status_code=500,
|
|
53
|
+
content={"error": f"{exc}"},
|
|
54
|
+
)
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
import uvicorn
|
|
2
|
+
import argparse
|
|
3
|
+
import os
|
|
4
|
+
import importlib
|
|
5
|
+
import importlib.util
|
|
6
|
+
import glob
|
|
7
|
+
import shutil
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
|
|
10
|
+
from fastapi import FastAPI, Request
|
|
11
|
+
from fastapi.responses import JSONResponse
|
|
12
|
+
|
|
13
|
+
parser = argparse.ArgumentParser(description="Run Sveltekit Python Server")
|
|
14
|
+
parser.add_argument("--host", default="0.0.0.0", help="Server hostname")
|
|
15
|
+
parser.add_argument("--port", type=int, default=8000, help="Server port")
|
|
16
|
+
parser.add_argument("--root", default=".", help="Directory where the API is located")
|
|
17
|
+
args = parser.parse_args()
|
|
18
|
+
|
|
19
|
+
app = FastAPI()
|
|
20
|
+
|
|
21
|
+
def app_factory():
|
|
22
|
+
return app # return the app object
|
|
23
|
+
|
|
24
|
+
if __name__ == "__main__":
|
|
25
|
+
|
|
26
|
+
root_dir = Path(args.root).absolute()
|
|
27
|
+
api_dir = Path("./sveltekit_python_vercel").absolute()
|
|
28
|
+
|
|
29
|
+
# Add all +server.py routes to web_app
|
|
30
|
+
for module_path in glob.glob(str(root_dir / 'src/routes/**/+server.py'), recursive=True):
|
|
31
|
+
|
|
32
|
+
# replace the root_dir with api_dir
|
|
33
|
+
api_route = api_dir / Path(module_path).absolute().relative_to(root_dir/ "src/routes")
|
|
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
|
+
print(f"PYTHON ENDPOINT: Copied {module_path} to {api_route.parent}")
|
|
41
|
+
|
|
42
|
+
# Get the module name from the module path
|
|
43
|
+
module_name = api_route.stem
|
|
44
|
+
|
|
45
|
+
# Import the module dynamically
|
|
46
|
+
spec = importlib.util.spec_from_file_location(module_name, api_route)
|
|
47
|
+
mod = importlib.util.module_from_spec(spec)
|
|
48
|
+
spec.loader.exec_module(mod)
|
|
49
|
+
|
|
50
|
+
# Get the relative path of the module from the API directory
|
|
51
|
+
rel_path = api_route.relative_to(api_dir)
|
|
52
|
+
# Convert the relative path to a string and remove the file extension
|
|
53
|
+
api_path = "/" + str(rel_path.parent)
|
|
54
|
+
|
|
55
|
+
print("ADDING API PATH:", rel_path, api_path)
|
|
56
|
+
|
|
57
|
+
if hasattr(mod, 'GET'):
|
|
58
|
+
app.add_api_route(api_path, mod.GET, methods=["GET"])
|
|
59
|
+
|
|
60
|
+
if hasattr(mod, 'POST'):
|
|
61
|
+
app.add_api_route(api_path, mod.POST, methods=["POST"])
|
|
62
|
+
|
|
63
|
+
if hasattr(mod, 'PATCH'):
|
|
64
|
+
app.add_api_route(api_path, mod.PATCH, methods=["PATCH"])
|
|
65
|
+
|
|
66
|
+
if hasattr(mod, 'PUT'):
|
|
67
|
+
app.add_api_route(api_path, mod.PUT, methods=["PUT"])
|
|
68
|
+
|
|
69
|
+
if hasattr(mod, 'DELETE'):
|
|
70
|
+
app.add_api_route(api_path, mod.DELETE, methods=["DELETE"])
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
config = uvicorn.Config(app_factory, host=args.host, port=args.port, log_level="info", factory=True)
|
|
74
|
+
server = uvicorn.Server(config)
|
|
75
|
+
print(f"Hosting on http://{args.host}:{args.port}")
|
|
76
|
+
server.run()
|
package/package.json
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
{
|
|
2
|
+
"module": "./esm/mod.js",
|
|
3
|
+
"types": "./types/mod.d.ts",
|
|
4
|
+
"name": "sveltekit-python-vercel",
|
|
5
|
+
"version": "v0.1.0",
|
|
6
|
+
"description": "Write Sveltekit server endpoints in Python and seamlessly deploy to Vercel",
|
|
7
|
+
"repository": {
|
|
8
|
+
"type": "git",
|
|
9
|
+
"url": "git+https://github.com/astrojarred/sveltekit-python-vercel.git"
|
|
10
|
+
},
|
|
11
|
+
"homepage": "https://github.com/astrojarred/sveltekit-python-vercel#readme",
|
|
12
|
+
"license": "MIT",
|
|
13
|
+
"exports": {
|
|
14
|
+
".": {
|
|
15
|
+
"import": "./esm/mod.js",
|
|
16
|
+
"types": "./types/mod.d.ts"
|
|
17
|
+
},
|
|
18
|
+
"./vite": {
|
|
19
|
+
"import": "./esm/src/vite/mod.js",
|
|
20
|
+
"types": "./types/src/vite/mod.d.ts"
|
|
21
|
+
},
|
|
22
|
+
"./package.json": "./package.json"
|
|
23
|
+
},
|
|
24
|
+
"typesVersions": {
|
|
25
|
+
"*": {
|
|
26
|
+
"vite": [
|
|
27
|
+
"./types/src/vite/mod.d.ts"
|
|
28
|
+
]
|
|
29
|
+
}
|
|
30
|
+
},
|
|
31
|
+
"keywords": [
|
|
32
|
+
"sveltekit-python-vercel",
|
|
33
|
+
"svelte-kit",
|
|
34
|
+
"sveltekit",
|
|
35
|
+
"svelte",
|
|
36
|
+
"vercel",
|
|
37
|
+
"python"
|
|
38
|
+
],
|
|
39
|
+
"engines": {
|
|
40
|
+
"node": ">=16.0.0"
|
|
41
|
+
},
|
|
42
|
+
"author": "astrojarred",
|
|
43
|
+
"bugs": {
|
|
44
|
+
"url": "https://github.com/astrojarred/sveltekit-python-vercel/issues"
|
|
45
|
+
},
|
|
46
|
+
"dependencies": {
|
|
47
|
+
"vite": "^4.0.0",
|
|
48
|
+
"zx": "^7.0.0"
|
|
49
|
+
},
|
|
50
|
+
"peerDependencies": {
|
|
51
|
+
"vite": "^4.0.0"
|
|
52
|
+
}
|
|
53
|
+
}
|
package/types/mod.d.ts
ADDED