snapserve 1.1.0__tar.gz

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.
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,136 @@
1
+ Metadata-Version: 2.4
2
+ Name: snapserve
3
+ Version: 1.1.0
4
+ Author-email: Panuthep Tasawong <panutheptasawong@gmail.com>
5
+ License-Expression: Apache-2.0
6
+ Project-URL: Homepage, https://github.com/panuthept/snapserve
7
+ Requires-Python: >=3.14
8
+ Description-Content-Type: text/markdown
9
+ License-File: LICENSE
10
+ Requires-Dist: fastapi
11
+ Requires-Dist: uvicorn
12
+ Requires-Dist: requests
13
+ Requires-Dist: typer
14
+ Provides-Extra: dev
15
+ Requires-Dist: pytest>=6.0; extra == "dev"
16
+ Requires-Dist: tqdm; extra == "dev"
17
+ Dynamic: license-file
18
+
19
+ # SnapServe
20
+
21
+ > Turn your Python functions, classes, and objects into callable services instantly.
22
+
23
+ **SnapServe** is a lightweight framework that exposes your Python code as a local service with a single command. It lets you serve functions, classes, or stateful objects without writing any API boilerplate, and interact with them through a simple Python client.
24
+
25
+ Instead of building and maintaining server code (e.g., with FastAPI or Flask), you focus on your application logic, SnapServe handles the serving layer and execution for you.
26
+
27
+ ## 📦 Install
28
+ ```bash
29
+ pip install snapserve
30
+ ```
31
+
32
+ ## 🚀 Quick Start
33
+ ### 🔹 Serve Functions
34
+ Expose one or more functions with a single command:
35
+
36
+ ```python
37
+ # calculator.py
38
+ def add(a: float, b: float) -> float:
39
+ return a + b
40
+
41
+ def subtract(a: float, b: float) -> float:
42
+ return a - b
43
+ ```
44
+ ```bash
45
+ snapserve serve calculator:add,subtract
46
+ ```
47
+ ```
48
+ 🌐 SnapServe is live:
49
+ (function) add(a: float, b: float) -> float
50
+ (function) subtract(a: float, b: float) -> float
51
+ ```
52
+
53
+ Call them from Python:
54
+
55
+ ```python
56
+ from snapserve import remote
57
+
58
+ add = remote("add")
59
+ subtract = remote("subtract")
60
+
61
+ print(add(5, 3)) # → 8
62
+ print(subtract(5, 3)) # → 2
63
+ ```
64
+
65
+ SnapServe supports multiple Python abstractions with a unified interface.
66
+
67
+ ### 🔹 Serve Classes
68
+ Serve a class definition. Each call creates a new isolated instance on the server.
69
+
70
+ ```python
71
+ # calculator_class.py
72
+ class Calculator:
73
+ def add(self, a: float, b: float) -> float:
74
+ return a + b
75
+
76
+ def subtract(self, a: float, b: float) -> float:
77
+ return a - b
78
+ ```
79
+ ```bash
80
+ snapserve serve calculator_class:Calculator
81
+ ```
82
+ ```python
83
+ from snapserve import remote
84
+
85
+ Calculator = remote("Calculator")
86
+
87
+ calc = Calculator()
88
+ print(calc.add(5, 3)) # → 8
89
+ print(calc.subtract(5, 3)) # → 2
90
+ ```
91
+
92
+ ### 🔹 Serve Objects (Stateful)
93
+ Serve an existing object to preserve state across calls.
94
+
95
+ ```python
96
+ # calculator_class.py
97
+ class Calculator:
98
+ def __init__(self):
99
+ self.last_result = None
100
+
101
+ def add(self, a: float, b: float) -> float:
102
+ self.last_result = a + b
103
+ return self.last_result
104
+
105
+ def subtract(self, a: float, b: float) -> float:
106
+ self.last_result = a - b
107
+ return self.last_result
108
+
109
+ calc = Calculator()
110
+ ```
111
+ ```bash
112
+ snapserve serve calculator_class:calc
113
+ ```
114
+ ```python
115
+ from snapserve import remote
116
+
117
+ calc = remote("calc")
118
+ print(calc.add(5, 3)) # → 8
119
+ print(calc.last_result) # → 8
120
+ print(calc.subtract(5, 3)) # → 2
121
+ print(calc.last_result) # → 2
122
+ ```
123
+
124
+ ## 🔧 Configuration
125
+ snapserve provides flexible runtime configuration via CLI flags:
126
+
127
+ ```bash
128
+ snapserve serve calculator:add,subtract \
129
+ --host localhost \ # Bind address (default: localhost)
130
+ --port 8080 \ # Port (default: 8000)
131
+ --workers 4 \ # Worker threads (default: 2 × CPU cores)
132
+ --max-concurrency 100 \ # Max concurrent requests
133
+ --timeout 30 \ # Request timeout (seconds)
134
+ --cachable \ # Enable result caching
135
+ --cache-size 10000 # Cache capacity
136
+ ```
@@ -0,0 +1,118 @@
1
+ # SnapServe
2
+
3
+ > Turn your Python functions, classes, and objects into callable services instantly.
4
+
5
+ **SnapServe** is a lightweight framework that exposes your Python code as a local service with a single command. It lets you serve functions, classes, or stateful objects without writing any API boilerplate, and interact with them through a simple Python client.
6
+
7
+ Instead of building and maintaining server code (e.g., with FastAPI or Flask), you focus on your application logic, SnapServe handles the serving layer and execution for you.
8
+
9
+ ## 📦 Install
10
+ ```bash
11
+ pip install snapserve
12
+ ```
13
+
14
+ ## 🚀 Quick Start
15
+ ### 🔹 Serve Functions
16
+ Expose one or more functions with a single command:
17
+
18
+ ```python
19
+ # calculator.py
20
+ def add(a: float, b: float) -> float:
21
+ return a + b
22
+
23
+ def subtract(a: float, b: float) -> float:
24
+ return a - b
25
+ ```
26
+ ```bash
27
+ snapserve serve calculator:add,subtract
28
+ ```
29
+ ```
30
+ 🌐 SnapServe is live:
31
+ (function) add(a: float, b: float) -> float
32
+ (function) subtract(a: float, b: float) -> float
33
+ ```
34
+
35
+ Call them from Python:
36
+
37
+ ```python
38
+ from snapserve import remote
39
+
40
+ add = remote("add")
41
+ subtract = remote("subtract")
42
+
43
+ print(add(5, 3)) # → 8
44
+ print(subtract(5, 3)) # → 2
45
+ ```
46
+
47
+ SnapServe supports multiple Python abstractions with a unified interface.
48
+
49
+ ### 🔹 Serve Classes
50
+ Serve a class definition. Each call creates a new isolated instance on the server.
51
+
52
+ ```python
53
+ # calculator_class.py
54
+ class Calculator:
55
+ def add(self, a: float, b: float) -> float:
56
+ return a + b
57
+
58
+ def subtract(self, a: float, b: float) -> float:
59
+ return a - b
60
+ ```
61
+ ```bash
62
+ snapserve serve calculator_class:Calculator
63
+ ```
64
+ ```python
65
+ from snapserve import remote
66
+
67
+ Calculator = remote("Calculator")
68
+
69
+ calc = Calculator()
70
+ print(calc.add(5, 3)) # → 8
71
+ print(calc.subtract(5, 3)) # → 2
72
+ ```
73
+
74
+ ### 🔹 Serve Objects (Stateful)
75
+ Serve an existing object to preserve state across calls.
76
+
77
+ ```python
78
+ # calculator_class.py
79
+ class Calculator:
80
+ def __init__(self):
81
+ self.last_result = None
82
+
83
+ def add(self, a: float, b: float) -> float:
84
+ self.last_result = a + b
85
+ return self.last_result
86
+
87
+ def subtract(self, a: float, b: float) -> float:
88
+ self.last_result = a - b
89
+ return self.last_result
90
+
91
+ calc = Calculator()
92
+ ```
93
+ ```bash
94
+ snapserve serve calculator_class:calc
95
+ ```
96
+ ```python
97
+ from snapserve import remote
98
+
99
+ calc = remote("calc")
100
+ print(calc.add(5, 3)) # → 8
101
+ print(calc.last_result) # → 8
102
+ print(calc.subtract(5, 3)) # → 2
103
+ print(calc.last_result) # → 2
104
+ ```
105
+
106
+ ## 🔧 Configuration
107
+ snapserve provides flexible runtime configuration via CLI flags:
108
+
109
+ ```bash
110
+ snapserve serve calculator:add,subtract \
111
+ --host localhost \ # Bind address (default: localhost)
112
+ --port 8080 \ # Port (default: 8000)
113
+ --workers 4 \ # Worker threads (default: 2 × CPU cores)
114
+ --max-concurrency 100 \ # Max concurrent requests
115
+ --timeout 30 \ # Request timeout (seconds)
116
+ --cachable \ # Enable result caching
117
+ --cache-size 10000 # Cache capacity
118
+ ```
@@ -0,0 +1,35 @@
1
+ [build-system]
2
+ requires = ["setuptools>=61.0", "wheel"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "snapserve"
7
+ version = "1.1.0"
8
+ readme = "README.md"
9
+ requires-python = ">=3.14"
10
+ license = "Apache-2.0"
11
+ authors = [
12
+ {name = "Panuthep Tasawong", email = "panutheptasawong@gmail.com"},
13
+ ]
14
+ dependencies = [
15
+ "fastapi",
16
+ "uvicorn",
17
+ "requests",
18
+ "typer",
19
+ ]
20
+
21
+ [project.optional-dependencies]
22
+ dev = ["pytest>=6.0", "tqdm"]
23
+
24
+ [project.urls]
25
+ Homepage = "https://github.com/panuthept/snapserve"
26
+
27
+ [tool.setuptools]
28
+ package-dir = {"" = "."}
29
+
30
+ [tool.setuptools.packages.find]
31
+ where = ["."]
32
+ include = ["snapserve*"]
33
+
34
+ [project.scripts]
35
+ snapserve = "snapserve.cli.main:app"
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1 @@
1
+ from .client import remote
@@ -0,0 +1,6 @@
1
+ import typer
2
+ from .serve import serve_app
3
+
4
+
5
+ app = typer.Typer()
6
+ app.add_typer(serve_app)
@@ -0,0 +1,35 @@
1
+ import typer
2
+ from typing import Annotated
3
+ from snapserve.server import Server
4
+ from snapserve.dataclasses import Attribute
5
+ from snapserve.loaders import load_attributes
6
+
7
+
8
+ serve_app = typer.Typer()
9
+ @serve_app.command("serve")
10
+ def serve(
11
+ module_path: Annotated[str, typer.Argument(..., help="The path to the module to serve, in the format 'module_path:variable_name'.")],
12
+ host: Annotated[str, typer.Option("--host", "-h", help="The host to bind the server to.")] = "localhost",
13
+ port: Annotated[int, typer.Option("--port", "-p", help="The port to bind the server to.")] = 8000,
14
+ workers: Annotated[int, typer.Option("--workers", "-w", help="The number of worker processes to use.")] = None,
15
+ max_concurrency: Annotated[int, typer.Option("--max-concurrency", "-m", help="The maximum number of concurrent requests to allow.")] = None,
16
+ timeout: Annotated[int, typer.Option("--timeout", "-t", help="The timeout for requests in seconds.")] = None,
17
+ cachable: Annotated[bool, typer.Option("--cacheable", "-c", is_flag=True, help="Whether to enable caching for the served application.")] = False,
18
+ cache_size: Annotated[int, typer.Option("--cache-size", help="The maximum size of the cache.")] = 1024,
19
+ daemon: Annotated[bool, typer.Option("--daemon", "-d", is_flag=True, help="Whether to run the server in daemon mode.")] = False,
20
+ ):
21
+ """
22
+ Serve Python functions, classes, and objects as an API.
23
+ """
24
+ attributes: dict[str, Attribute] = load_attributes(module_path)
25
+ server = Server(
26
+ attributes=attributes,
27
+ host=host,
28
+ port=port,
29
+ workers=workers,
30
+ max_concurrency=max_concurrency,
31
+ timeout=timeout,
32
+ cachable=cachable,
33
+ cache_size=cache_size,
34
+ )
35
+ server.run()
@@ -0,0 +1,112 @@
1
+ import requests
2
+ from functools import partial
3
+
4
+
5
+ def validate_endpoint(endpoint: str, base_url: str = "http://localhost:8000"):
6
+ url = f"{base_url}/{endpoint}"
7
+ try:
8
+ response = requests.options(url)
9
+ response.raise_for_status()
10
+ except requests.RequestException as e:
11
+ raise ValueError(f"Endpoint '{endpoint}' is not available at {base_url}") from e
12
+
13
+ def get_client(endpoint: str, base_url: str = "http://localhost:8000") -> "Client":
14
+ url = f"{base_url}/{endpoint}"
15
+ response = requests.get(url)
16
+ response.raise_for_status()
17
+ data = response.json()
18
+ attr_type = data.get("type")
19
+ if attr_type == "function":
20
+ return FunctionClient(endpoint, base_url)
21
+ elif attr_type == "class":
22
+ return ClassClient(endpoint, base_url)
23
+ elif attr_type == "object":
24
+ return ObjectClient(
25
+ endpoint=endpoint,
26
+ base_url=base_url,
27
+ methods=data.get("methods", []),
28
+ attributes=data.get("attributes", [])
29
+ )
30
+ else:
31
+ raise ValueError(f"Unsupported attribute type: {attr_type}")
32
+
33
+ def remote(endpoint: str, base_url: str = "http://localhost:8000") -> "Client":
34
+ validate_endpoint(endpoint, base_url)
35
+ return get_client(endpoint, base_url)
36
+
37
+ class Client:
38
+ def __init__(self, endpoint: str, base_url: str = "http://localhost:8000"):
39
+ self.base_url = base_url
40
+ self.endpoint = endpoint
41
+
42
+ class FunctionClient(Client):
43
+ def __call__(self, *args, **kwargs):
44
+ payload = {"args": args, "kwargs": kwargs}
45
+ url = f"{self.base_url}/{self.endpoint}"
46
+ response = requests.post(url, json=payload)
47
+ response.raise_for_status()
48
+ return response.json()["result"]
49
+
50
+ class ObjectClient(Client):
51
+ def __init__(
52
+ self,
53
+ endpoint: str,
54
+ base_url: str = "http://localhost:8000",
55
+ methods: list[str] = None,
56
+ attributes: list[str] = None,
57
+ obj_id: str = None
58
+ ):
59
+ super().__init__(endpoint, base_url)
60
+ self.methods = methods or []
61
+ self.attributes = attributes or []
62
+ self.obj_id = obj_id
63
+
64
+ def __call__(self, *args, **kwargs):
65
+ if "__call__" not in self.methods:
66
+ raise AttributeError(f"Object does not have a __call__ method.")
67
+ return self._call_method(self.obj_id, "__call__", self.endpoint, self.base_url, *args, **kwargs)
68
+
69
+ def __getattr__(self, method_or_attribute_name: str):
70
+ if method_or_attribute_name not in self.methods and method_or_attribute_name not in self.attributes:
71
+ raise AttributeError(f"Object does not have a method or attribute named '{method_or_attribute_name}'.")
72
+
73
+ if method_or_attribute_name in self.methods:
74
+ return partial(self._call_method, self.obj_id, method_or_attribute_name, self.endpoint, self.base_url)
75
+ else:
76
+ return self._get_attribute(self.obj_id, method_or_attribute_name, self.endpoint, self.base_url)
77
+
78
+ @staticmethod
79
+ def _call_method(obj_id: str, method_name: str, endpoint: str, base_url: str, *args, **kwargs):
80
+ url = f"{base_url}/{endpoint}"
81
+ payload = {"id": obj_id, "method_or_attribute_name": method_name, "args": args, "kwargs": kwargs}
82
+ response = requests.post(url, json=payload)
83
+ response.raise_for_status()
84
+ return response.json()["result"]
85
+
86
+ @staticmethod
87
+ def _get_attribute(obj_id: str, attr_name: str, endpoint: str, base_url: str):
88
+ url = f"{base_url}/{endpoint}"
89
+ payload = {"id": obj_id, "method_or_attribute_name": attr_name}
90
+ response = requests.post(url, json=payload)
91
+ response.raise_for_status()
92
+ return response.json()["result"]
93
+
94
+ class ClassClient(Client):
95
+ def __call__(self, *args, **kwargs):
96
+ payload = {"args": args, "kwargs": kwargs}
97
+ url = f"{self.base_url}/{self.endpoint}"
98
+ response = requests.post(url, json=payload)
99
+ response.raise_for_status()
100
+ obj_id = response.json()["result"]
101
+
102
+ response = url = f"{self.base_url}/"
103
+ response = requests.get(url)
104
+ response.raise_for_status()
105
+ attribute = response.json()["attributes"][obj_id]
106
+ return ObjectClient(
107
+ endpoint=self.endpoint,
108
+ base_url=self.base_url,
109
+ methods=attribute.get("methods", []),
110
+ attributes=attribute.get("attributes", []),
111
+ obj_id=obj_id
112
+ )
@@ -0,0 +1,40 @@
1
+ import inspect
2
+ from typing import Any
3
+ from dataclasses import dataclass
4
+ from snapserve.utils.inspect import get_attr_type
5
+
6
+
7
+ @dataclass
8
+ class Attribute:
9
+ attr: Any
10
+ type: str = ""
11
+ signature: str = ""
12
+ methods: list[str] = None
13
+ attributes: list[str] = None
14
+
15
+ def __post_init__(self):
16
+ self.type = get_attr_type(self.attr)
17
+ if self.type == "function":
18
+ self.signature = str(inspect.signature(self.attr))
19
+ elif self.type == "class":
20
+ self.signature = str(inspect.signature(self.attr.__init__))
21
+ elif self.type == "object":
22
+ class_name = self.attr.__class__.__name__
23
+ sig = inspect.signature(self.attr.__init__)
24
+ params = list(sig.parameters.values())
25
+ parts = []
26
+ for param in params:
27
+ if hasattr(self.attr, param.name):
28
+ value = getattr(self.attr, param.name)
29
+ parts.append(f"{param.name}={value!r}")
30
+ class_params = f"({", ".join(parts)})"
31
+ self.signature = f"{class_name}{class_params}"
32
+
33
+ self.methods = [
34
+ name for name, value in inspect.getmembers(self.attr, predicate=inspect.ismethod)
35
+ if name == "__call__" or (not name.startswith("__") and not name.endswith("__"))
36
+ ]
37
+ self.attributes = [
38
+ name for name, value in inspect.getmembers(self.attr)
39
+ if not callable(value) and (not name.startswith("__") and not name.endswith("__"))
40
+ ]
@@ -0,0 +1,16 @@
1
+ from snapserve.dataclasses import Attribute
2
+ from snapserve.utils.loaders import load_module
3
+
4
+
5
+ def load_attributes(module_path: str) -> dict[str, Attribute]:
6
+ module = load_module(module_path)
7
+
8
+ attributes = {}
9
+ for attr_name in module_path.split(":")[1].split(","):
10
+ attr_name = attr_name.strip()
11
+ if not hasattr(module, attr_name):
12
+ raise AttributeError(f"Module '{module.__name__}' does not have an attribute named '{attr_name}'.")
13
+ attr = getattr(module, attr_name)
14
+ attributes[attr_name] = Attribute(attr, attr_name)
15
+
16
+ return attributes
@@ -0,0 +1,238 @@
1
+ import os
2
+ import uuid
3
+ import time
4
+ import json
5
+ import atexit
6
+ import uvicorn
7
+ import asyncio
8
+ import threading
9
+ import contextlib
10
+ from typing import Any
11
+ from snapserve.dataclasses import Attribute
12
+ from concurrent.futures import ThreadPoolExecutor
13
+ from fastapi import Request, FastAPI, HTTPException
14
+
15
+
16
+ class CacheManager:
17
+ def __init__(self, max_size: int = 1024):
18
+ self.max_size = max_size
19
+ self.cache: dict[str, Any] = {}
20
+ self.access_times: dict[str, float] = {}
21
+
22
+ def get(self, key: str) -> Any:
23
+ if key in self.cache:
24
+ self.access_times[key] = time.time()
25
+ return self.cache[key]
26
+ else:
27
+ return None
28
+
29
+ def set(self, key: str, value: Any) -> None:
30
+ if len(self.cache) >= self.max_size:
31
+ # Evict least recently used item
32
+ oldest_key = min(self.access_times, key=lambda k: self.access_times[k])
33
+ del self.cache[oldest_key]
34
+ del self.access_times[oldest_key]
35
+ self.cache[key] = value
36
+ self.access_times[key] = time.time()
37
+
38
+ class Server:
39
+ def __init__(
40
+ self,
41
+ attributes: dict[str, Attribute],
42
+ host: str = "localhost",
43
+ port: int = 8000,
44
+ workers: int = None,
45
+ max_concurrency: int = None,
46
+ timeout: int = None,
47
+ cachable: bool = False,
48
+ cache_size: int = 1024,
49
+ ):
50
+ self.attributes = attributes
51
+ self.host = host
52
+ self.port = port
53
+
54
+ self.app = create_app(
55
+ attributes=self.attributes,
56
+ workers=workers,
57
+ max_concurrency=max_concurrency,
58
+ timeout=timeout,
59
+ cachable=cachable,
60
+ cache_size=cache_size,
61
+ )
62
+
63
+ def run(self):
64
+ config = uvicorn.Config(
65
+ self.app,
66
+ host=self.host,
67
+ port=self.port,
68
+ log_level="warning",
69
+ )
70
+ server = uvicorn.Server(config)
71
+ thread = threading.Thread(target=server.run, daemon=True)
72
+ thread.start()
73
+
74
+ print("🌐 PyServe is live:")
75
+ for attr_name, attribute in self.attributes.items():
76
+ print(f"- http://{self.host}:{self.port}/{attr_name} ({attribute.type})")
77
+
78
+ print()
79
+ print("🛑 Press Ctrl+C to stop")
80
+ # --------------------------------------------------------------------------------------
81
+ # Shutdown handling
82
+ # --------------------------------------------------------------------------------------
83
+ def shutdown():
84
+ if server.should_exit:
85
+ return
86
+ server.should_exit = True
87
+ thread.join()
88
+ print("✅ Shutdown complete")
89
+ atexit.register(shutdown)
90
+
91
+ while thread.is_alive():
92
+ thread.join(timeout=1)
93
+
94
+ def create_app(
95
+ attributes: dict[str, Attribute],
96
+ workers: int = None,
97
+ max_concurrency: int = None,
98
+ timeout: int = None,
99
+ cachable: bool = False,
100
+ cache_size: int = 1024,
101
+ ):
102
+ app = FastAPI()
103
+ thread_executor = ThreadPoolExecutor(max_workers=workers or (2 * os.cpu_count() + 1))
104
+ semaphore = asyncio.Semaphore(max_concurrency) if max_concurrency else contextlib.nullcontext()
105
+ cache_manager = CacheManager(max_size=cache_size) if cachable else None
106
+ # ------------------------------------------------------------------------------------------
107
+ # Attribute handlers
108
+ # ------------------------------------------------------------------------------------------
109
+ def execute_function(attribute: Attribute, payload: dict) -> Any:
110
+ args = payload.get("args", [])
111
+ kwargs = payload.get("kwargs", {})
112
+ # Run function
113
+ return attribute.attr(*args, **kwargs)
114
+
115
+ def execute_class(attribute: Attribute, payload: dict) -> Any:
116
+ args = payload.get("args", [])
117
+ kwargs = payload.get("kwargs", {})
118
+ # Instantiate class
119
+ obj = attribute.attr(*args, **kwargs)
120
+ obj_id = uuid.uuid4().hex
121
+ # Create new attribute for the object instance
122
+ attributes[obj_id] = Attribute(obj)
123
+ return obj_id
124
+
125
+ def execute_object(attribute: Attribute, payload: dict) -> Any:
126
+ args = payload.get("args", [])
127
+ kwargs = payload.get("kwargs", {})
128
+ method_or_attribute_name = payload["method_or_attribute_name"]
129
+ if method_or_attribute_name in attribute.methods:
130
+ method = getattr(attribute.attr, method_or_attribute_name)
131
+ return method(*args, **kwargs)
132
+ elif method_or_attribute_name in attribute.attributes:
133
+ attribute_value = getattr(attribute.attr, method_or_attribute_name)
134
+ return attribute_value
135
+ else:
136
+ raise HTTPException(status_code=400, detail=f"Object does not have a method or attribute named '{method_or_attribute_name}'.")
137
+
138
+ def execute_attribute(attr_name: str, payload: dict) -> Any:
139
+ if payload.get("id"):
140
+ obj_id = payload["id"]
141
+ if obj_id not in attributes:
142
+ raise HTTPException(status_code=400, detail=f"Object with id '{obj_id}' not found.")
143
+ attribute: Attribute = attributes[obj_id]
144
+ else:
145
+ attribute: Attribute = attributes[attr_name]
146
+
147
+ if attribute.type == "function":
148
+ result = execute_function(attribute, payload)
149
+ elif attribute.type == "class":
150
+ result = execute_class(attribute, payload)
151
+ else:
152
+ result = execute_object(attribute, payload)
153
+
154
+ # Update cache if enabled
155
+ if cache_manager:
156
+ with threading.Lock():
157
+ cache_key = f"{attr_name}:{json.dumps(payload, sort_keys=True)}"
158
+ cache_manager.set(cache_key, result)
159
+ return result
160
+
161
+ async def handle_request(attr_name: str, payload: dict) -> Any:
162
+ loop = asyncio.get_running_loop()
163
+ # Use cache if enabled
164
+ if cache_manager:
165
+ cache_key = f"{attr_name}:{json.dumps(payload, sort_keys=True)}"
166
+ cached_result = cache_manager.get(cache_key)
167
+ if cached_result is not None:
168
+ return cached_result
169
+ # Execute the attribute in a thread to avoid blocking the event loop
170
+ async with semaphore:
171
+ return await loop.run_in_executor(
172
+ thread_executor,
173
+ execute_attribute,
174
+ attr_name,
175
+ payload
176
+ )
177
+ # ------------------------------------------------------------------------------------------
178
+ # Endpoints
179
+ # ------------------------------------------------------------------------------------------
180
+ @app.get("/")
181
+ async def root():
182
+ return {
183
+ "status": "online",
184
+ "workload": thread_executor._work_queue.qsize(),
185
+ "message": "Welcome to PyServe!",
186
+ "attributes": {
187
+ attr_name: {
188
+ "type": attribute.type,
189
+ "signature": attribute.signature,
190
+ "methods": attribute.methods,
191
+ "attributes": attribute.attributes,
192
+ } for attr_name, attribute in attributes.items()
193
+ }
194
+ }
195
+
196
+ for attr_name in attributes.keys():
197
+ @app.get(f"/{attr_name}")
198
+ async def get_attribute(attr_name=attr_name):
199
+ attribute = attributes[attr_name]
200
+ return {
201
+ "name": attr_name,
202
+ "type": attribute.type,
203
+ "signature": attribute.signature,
204
+ "methods": attribute.methods,
205
+ "attributes": attribute.attributes,
206
+ }
207
+
208
+ @app.post(f"/{attr_name}")
209
+ async def call_attribute(request: Request, attr_name=attr_name):
210
+ try:
211
+ payload = await request.json()
212
+ except Exception:
213
+ raise HTTPException(status_code=400, detail="Invalid JSON payload.")
214
+ try:
215
+ coro = handle_request(attr_name, payload)
216
+ if timeout:
217
+ result = await asyncio.wait_for(coro, timeout=timeout)
218
+ else:
219
+ result = await coro
220
+ return {"result": result}
221
+ except asyncio.TimeoutError:
222
+ raise HTTPException(status_code=504, detail="Request timed out.")
223
+ except HTTPException:
224
+ raise
225
+ except Exception as e:
226
+ raise HTTPException(status_code=500, detail=str(e))
227
+
228
+ @app.options(f"/{attr_name}")
229
+ async def options_attribute(attr_name=attr_name):
230
+ return {"allowed_methods": ["GET", "POST", "OPTIONS"]}
231
+ # ------------------------------------------------------------------------------------------
232
+ # Shutdown handling
233
+ # ------------------------------------------------------------------------------------------
234
+ def shutdown():
235
+ thread_executor.shutdown(wait=True)
236
+ atexit.register(shutdown)
237
+
238
+ return app
@@ -0,0 +1,10 @@
1
+ import inspect
2
+
3
+
4
+ def get_attr_type(attr) -> str:
5
+ if inspect.isfunction(attr):
6
+ return "function"
7
+ elif inspect.isclass(attr):
8
+ return "class"
9
+ else:
10
+ return "object"
@@ -0,0 +1,16 @@
1
+ import os
2
+ import sys
3
+ import importlib
4
+ from types import ModuleType
5
+
6
+
7
+ def load_module(module_path: str) -> ModuleType:
8
+ if ":" not in module_path or module_path.count(":") > 1:
9
+ raise ValueError(f"Module path '{module_path}' is invalid. It should be in the format 'module_path:variable_name'.")
10
+
11
+ # Add the current working directory to sys.path to allow importing from there
12
+ sys.path.insert(0, os.getcwd())
13
+
14
+ module_path, _ = module_path.split(":")
15
+ module = importlib.import_module(module_path)
16
+ return module
@@ -0,0 +1,136 @@
1
+ Metadata-Version: 2.4
2
+ Name: snapserve
3
+ Version: 1.1.0
4
+ Author-email: Panuthep Tasawong <panutheptasawong@gmail.com>
5
+ License-Expression: Apache-2.0
6
+ Project-URL: Homepage, https://github.com/panuthept/snapserve
7
+ Requires-Python: >=3.14
8
+ Description-Content-Type: text/markdown
9
+ License-File: LICENSE
10
+ Requires-Dist: fastapi
11
+ Requires-Dist: uvicorn
12
+ Requires-Dist: requests
13
+ Requires-Dist: typer
14
+ Provides-Extra: dev
15
+ Requires-Dist: pytest>=6.0; extra == "dev"
16
+ Requires-Dist: tqdm; extra == "dev"
17
+ Dynamic: license-file
18
+
19
+ # SnapServe
20
+
21
+ > Turn your Python functions, classes, and objects into callable services instantly.
22
+
23
+ **SnapServe** is a lightweight framework that exposes your Python code as a local service with a single command. It lets you serve functions, classes, or stateful objects without writing any API boilerplate, and interact with them through a simple Python client.
24
+
25
+ Instead of building and maintaining server code (e.g., with FastAPI or Flask), you focus on your application logic, SnapServe handles the serving layer and execution for you.
26
+
27
+ ## 📦 Install
28
+ ```bash
29
+ pip install snapserve
30
+ ```
31
+
32
+ ## 🚀 Quick Start
33
+ ### 🔹 Serve Functions
34
+ Expose one or more functions with a single command:
35
+
36
+ ```python
37
+ # calculator.py
38
+ def add(a: float, b: float) -> float:
39
+ return a + b
40
+
41
+ def subtract(a: float, b: float) -> float:
42
+ return a - b
43
+ ```
44
+ ```bash
45
+ snapserve serve calculator:add,subtract
46
+ ```
47
+ ```
48
+ 🌐 SnapServe is live:
49
+ (function) add(a: float, b: float) -> float
50
+ (function) subtract(a: float, b: float) -> float
51
+ ```
52
+
53
+ Call them from Python:
54
+
55
+ ```python
56
+ from snapserve import remote
57
+
58
+ add = remote("add")
59
+ subtract = remote("subtract")
60
+
61
+ print(add(5, 3)) # → 8
62
+ print(subtract(5, 3)) # → 2
63
+ ```
64
+
65
+ SnapServe supports multiple Python abstractions with a unified interface.
66
+
67
+ ### 🔹 Serve Classes
68
+ Serve a class definition. Each call creates a new isolated instance on the server.
69
+
70
+ ```python
71
+ # calculator_class.py
72
+ class Calculator:
73
+ def add(self, a: float, b: float) -> float:
74
+ return a + b
75
+
76
+ def subtract(self, a: float, b: float) -> float:
77
+ return a - b
78
+ ```
79
+ ```bash
80
+ snapserve serve calculator_class:Calculator
81
+ ```
82
+ ```python
83
+ from snapserve import remote
84
+
85
+ Calculator = remote("Calculator")
86
+
87
+ calc = Calculator()
88
+ print(calc.add(5, 3)) # → 8
89
+ print(calc.subtract(5, 3)) # → 2
90
+ ```
91
+
92
+ ### 🔹 Serve Objects (Stateful)
93
+ Serve an existing object to preserve state across calls.
94
+
95
+ ```python
96
+ # calculator_class.py
97
+ class Calculator:
98
+ def __init__(self):
99
+ self.last_result = None
100
+
101
+ def add(self, a: float, b: float) -> float:
102
+ self.last_result = a + b
103
+ return self.last_result
104
+
105
+ def subtract(self, a: float, b: float) -> float:
106
+ self.last_result = a - b
107
+ return self.last_result
108
+
109
+ calc = Calculator()
110
+ ```
111
+ ```bash
112
+ snapserve serve calculator_class:calc
113
+ ```
114
+ ```python
115
+ from snapserve import remote
116
+
117
+ calc = remote("calc")
118
+ print(calc.add(5, 3)) # → 8
119
+ print(calc.last_result) # → 8
120
+ print(calc.subtract(5, 3)) # → 2
121
+ print(calc.last_result) # → 2
122
+ ```
123
+
124
+ ## 🔧 Configuration
125
+ snapserve provides flexible runtime configuration via CLI flags:
126
+
127
+ ```bash
128
+ snapserve serve calculator:add,subtract \
129
+ --host localhost \ # Bind address (default: localhost)
130
+ --port 8080 \ # Port (default: 8000)
131
+ --workers 4 \ # Worker threads (default: 2 × CPU cores)
132
+ --max-concurrency 100 \ # Max concurrent requests
133
+ --timeout 30 \ # Request timeout (seconds)
134
+ --cachable \ # Enable result caching
135
+ --cache-size 10000 # Cache capacity
136
+ ```
@@ -0,0 +1,27 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ ./snapserve/__init__.py
5
+ ./snapserve/client.py
6
+ ./snapserve/dataclasses.py
7
+ ./snapserve/loaders.py
8
+ ./snapserve/server.py
9
+ ./snapserve/cli/main.py
10
+ ./snapserve/cli/serve.py
11
+ ./snapserve/utils/inspect.py
12
+ ./snapserve/utils/loaders.py
13
+ snapserve/__init__.py
14
+ snapserve/client.py
15
+ snapserve/dataclasses.py
16
+ snapserve/loaders.py
17
+ snapserve/server.py
18
+ snapserve.egg-info/PKG-INFO
19
+ snapserve.egg-info/SOURCES.txt
20
+ snapserve.egg-info/dependency_links.txt
21
+ snapserve.egg-info/entry_points.txt
22
+ snapserve.egg-info/requires.txt
23
+ snapserve.egg-info/top_level.txt
24
+ snapserve/cli/main.py
25
+ snapserve/cli/serve.py
26
+ snapserve/utils/inspect.py
27
+ snapserve/utils/loaders.py
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ snapserve = snapserve.cli.main:app
@@ -0,0 +1,8 @@
1
+ fastapi
2
+ uvicorn
3
+ requests
4
+ typer
5
+
6
+ [dev]
7
+ pytest>=6.0
8
+ tqdm
@@ -0,0 +1 @@
1
+ snapserve