hypern 0.3.0__cp310-cp310-win32.whl

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.
Files changed (69) hide show
  1. hypern/__init__.py +4 -0
  2. hypern/application.py +405 -0
  3. hypern/args_parser.py +59 -0
  4. hypern/auth/__init__.py +0 -0
  5. hypern/auth/authorization.py +2 -0
  6. hypern/background.py +4 -0
  7. hypern/caching/__init__.py +0 -0
  8. hypern/caching/base/__init__.py +8 -0
  9. hypern/caching/base/backend.py +3 -0
  10. hypern/caching/base/key_maker.py +8 -0
  11. hypern/caching/cache_manager.py +56 -0
  12. hypern/caching/cache_tag.py +10 -0
  13. hypern/caching/custom_key_maker.py +11 -0
  14. hypern/caching/redis_backend.py +3 -0
  15. hypern/cli/__init__.py +0 -0
  16. hypern/cli/commands.py +0 -0
  17. hypern/config.py +149 -0
  18. hypern/datastructures.py +40 -0
  19. hypern/db/__init__.py +0 -0
  20. hypern/db/nosql/__init__.py +25 -0
  21. hypern/db/nosql/addons/__init__.py +4 -0
  22. hypern/db/nosql/addons/color.py +16 -0
  23. hypern/db/nosql/addons/daterange.py +30 -0
  24. hypern/db/nosql/addons/encrypted.py +53 -0
  25. hypern/db/nosql/addons/password.py +134 -0
  26. hypern/db/nosql/addons/unicode.py +10 -0
  27. hypern/db/sql/__init__.py +179 -0
  28. hypern/db/sql/addons/__init__.py +14 -0
  29. hypern/db/sql/addons/color.py +16 -0
  30. hypern/db/sql/addons/daterange.py +23 -0
  31. hypern/db/sql/addons/datetime.py +22 -0
  32. hypern/db/sql/addons/encrypted.py +58 -0
  33. hypern/db/sql/addons/password.py +171 -0
  34. hypern/db/sql/addons/ts_vector.py +46 -0
  35. hypern/db/sql/addons/unicode.py +15 -0
  36. hypern/db/sql/repository.py +290 -0
  37. hypern/enum.py +13 -0
  38. hypern/exceptions.py +97 -0
  39. hypern/hypern.cp310-win32.pyd +0 -0
  40. hypern/hypern.pyi +295 -0
  41. hypern/i18n/__init__.py +0 -0
  42. hypern/logging/__init__.py +3 -0
  43. hypern/logging/logger.py +82 -0
  44. hypern/middleware/__init__.py +5 -0
  45. hypern/middleware/base.py +18 -0
  46. hypern/middleware/cors.py +38 -0
  47. hypern/middleware/i18n.py +1 -0
  48. hypern/middleware/limit.py +176 -0
  49. hypern/openapi/__init__.py +5 -0
  50. hypern/openapi/schemas.py +53 -0
  51. hypern/openapi/swagger.py +3 -0
  52. hypern/processpool.py +137 -0
  53. hypern/py.typed +0 -0
  54. hypern/reload.py +60 -0
  55. hypern/response/__init__.py +3 -0
  56. hypern/response/response.py +134 -0
  57. hypern/routing/__init__.py +4 -0
  58. hypern/routing/dispatcher.py +67 -0
  59. hypern/routing/endpoint.py +30 -0
  60. hypern/routing/parser.py +100 -0
  61. hypern/routing/route.py +284 -0
  62. hypern/scheduler.py +5 -0
  63. hypern/security.py +44 -0
  64. hypern/worker.py +30 -0
  65. hypern/ws.py +16 -0
  66. hypern-0.3.0.dist-info/METADATA +128 -0
  67. hypern-0.3.0.dist-info/RECORD +69 -0
  68. hypern-0.3.0.dist-info/WHEEL +4 -0
  69. hypern-0.3.0.dist-info/licenses/LICENSE +24 -0
hypern/__init__.py ADDED
@@ -0,0 +1,4 @@
1
+ from .application import Hypern
2
+ from .hypern import Request, Response
3
+
4
+ __all__ = ["Hypern", "Request", "Response"]
hypern/application.py ADDED
@@ -0,0 +1,405 @@
1
+ # -*- coding: utf-8 -*-
2
+ from __future__ import annotations
3
+
4
+ import asyncio
5
+ from typing import Any, Callable, List, TypeVar
6
+
7
+ import orjson
8
+ from typing_extensions import Annotated, Doc
9
+
10
+ from hypern.datastructures import Contact, HTTPMethod, Info, License
11
+ from hypern.hypern import FunctionInfo, Router, Route as InternalRoute, WebsocketRouter
12
+ from hypern.openapi import SchemaGenerator, SwaggerUI
13
+ from hypern.processpool import run_processes
14
+ from hypern.response import HTMLResponse, JSONResponse
15
+ from hypern.routing import Route
16
+ from hypern.scheduler import Scheduler
17
+ from hypern.middleware import Middleware
18
+ from hypern.args_parser import ArgsConfig
19
+ from hypern.ws import WebsocketRoute
20
+
21
+ AppType = TypeVar("AppType", bound="Hypern")
22
+
23
+
24
+ class Hypern:
25
+ def __init__(
26
+ self: AppType,
27
+ routes: Annotated[
28
+ List[Route] | None,
29
+ Doc(
30
+ """
31
+ A list of routes to serve incoming HTTP and WebSocket requests.
32
+ You can define routes using the `Route` class from `Hypern.routing`.
33
+ **Example**
34
+ ---
35
+ ```python
36
+ class DefaultRoute(HTTPEndpoint):
37
+ async def get(self, global_dependencies):
38
+ return PlainTextResponse("/hello")
39
+ Route("/test", DefaultRoute)
40
+
41
+ # Or you can define routes using the decorator
42
+ route = Route("/test)
43
+ @route.get("/route")
44
+ def def_get():
45
+ return PlainTextResponse("Hello")
46
+ ```
47
+ """
48
+ ),
49
+ ] = None,
50
+ websockets: Annotated[
51
+ List[WebsocketRoute] | None,
52
+ Doc(
53
+ """
54
+ A list of routes to serve incoming WebSocket requests.
55
+ You can define routes using the `WebsocketRoute` class from `Hypern
56
+ """
57
+ ),
58
+ ] = None,
59
+ title: Annotated[
60
+ str,
61
+ Doc(
62
+ """
63
+ The title of the API.
64
+
65
+ It will be added to the generated OpenAPI (e.g. visible at `/docs`).
66
+
67
+ Read more in the
68
+ """
69
+ ),
70
+ ] = "Hypern",
71
+ summary: Annotated[
72
+ str | None,
73
+ Doc(
74
+ """"
75
+ A short summary of the API.
76
+
77
+ It will be added to the generated OpenAPI (e.g. visible at `/docs`).
78
+ """
79
+ ),
80
+ ] = None,
81
+ description: Annotated[
82
+ str,
83
+ Doc(
84
+ """
85
+ A description of the API. Supports Markdown (using
86
+ [CommonMark syntax](https://commonmark.org/)).
87
+
88
+ It will be added to the generated OpenAPI (e.g. visible at `/docs`).
89
+ """
90
+ ),
91
+ ] = "",
92
+ version: Annotated[
93
+ str,
94
+ Doc(
95
+ """
96
+ The version of the API.
97
+
98
+ **Note** This is the version of your application, not the version of
99
+ the OpenAPI specification nor the version of Application being used.
100
+
101
+ It will be added to the generated OpenAPI (e.g. visible at `/docs`).
102
+ """
103
+ ),
104
+ ] = "0.0.1",
105
+ contact: Annotated[
106
+ Contact | None,
107
+ Doc(
108
+ """
109
+ A dictionary with the contact information for the exposed API.
110
+
111
+ It can contain several fields.
112
+
113
+ * `name`: (`str`) The name of the contact person/organization.
114
+ * `url`: (`str`) A URL pointing to the contact information. MUST be in
115
+ the format of a URL.
116
+ * `email`: (`str`) The email address of the contact person/organization.
117
+ MUST be in the format of an email address.
118
+ """
119
+ ),
120
+ ] = None,
121
+ openapi_url: Annotated[
122
+ str | None,
123
+ Doc(
124
+ """
125
+ The URL where the OpenAPI schema will be served from.
126
+
127
+ If you set it to `None`, no OpenAPI schema will be served publicly, and
128
+ the default automatic endpoints `/docs` and `/redoc` will also be
129
+ disabled.
130
+ """
131
+ ),
132
+ ] = "/openapi.json",
133
+ docs_url: Annotated[
134
+ str | None,
135
+ Doc(
136
+ """
137
+ The path to the automatic interactive API documentation.
138
+ It is handled in the browser by Swagger UI.
139
+
140
+ The default URL is `/docs`. You can disable it by setting it to `None`.
141
+
142
+ If `openapi_url` is set to `None`, this will be automatically disabled.
143
+ """
144
+ ),
145
+ ] = "/docs",
146
+ license_info: Annotated[
147
+ License | None,
148
+ Doc(
149
+ """
150
+ A dictionary with the license information for the exposed API.
151
+
152
+ It can contain several fields.
153
+
154
+ * `name`: (`str`) **REQUIRED** (if a `license_info` is set). The
155
+ license name used for the API.
156
+ * `identifier`: (`str`) An [SPDX](https://spdx.dev/) license expression
157
+ for the API. The `identifier` field is mutually exclusive of the `url`
158
+ field. Available since OpenAPI 3.1.0
159
+ * `url`: (`str`) A URL to the license used for the API. This MUST be
160
+ the format of a URL.
161
+
162
+ It will be added to the generated OpenAPI (e.g. visible at `/docs`).
163
+
164
+ **Example**
165
+
166
+ ```python
167
+ app = Hypern(
168
+ license_info={
169
+ "name": "Apache 2.0",
170
+ "url": "https://www.apache.org/licenses/LICENSE-2.0.html",
171
+ }
172
+ )
173
+ ```
174
+ """
175
+ ),
176
+ ] = None,
177
+ scheduler: Annotated[
178
+ Scheduler | None,
179
+ Doc(
180
+ """
181
+ A scheduler to run background tasks.
182
+ """
183
+ ),
184
+ ] = None,
185
+ default_injectables: Annotated[
186
+ dict[str, Any] | None,
187
+ Doc(
188
+ """
189
+ A dictionary of default injectables to be passed to all routes.
190
+ """
191
+ ),
192
+ ] = None,
193
+ *args: Any,
194
+ **kwargs: Any,
195
+ ) -> None:
196
+ super().__init__(*args, **kwargs)
197
+ self.router = Router(path="/")
198
+ self.websocket_router = WebsocketRouter(path="/")
199
+ self.scheduler = scheduler
200
+ self.injectables = default_injectables or {}
201
+ self.middleware_before_request = []
202
+ self.middleware_after_request = []
203
+ self.response_headers = {}
204
+ self.args = ArgsConfig()
205
+
206
+ for route in routes or []:
207
+ self.router.extend_route(route(app=self).routes)
208
+
209
+ for websocket_route in websockets or []:
210
+ self.websocket_router.add_route(websocket_route)
211
+
212
+ if openapi_url and docs_url:
213
+ self.__add_openapi(
214
+ info=Info(
215
+ title=title,
216
+ summary=summary,
217
+ description=description,
218
+ version=version,
219
+ contact=contact,
220
+ license=license_info,
221
+ ),
222
+ openapi_url=openapi_url,
223
+ docs_url=docs_url,
224
+ )
225
+
226
+ def __add_openapi(
227
+ self,
228
+ info: Info,
229
+ openapi_url: str,
230
+ docs_url: str,
231
+ ):
232
+ """
233
+ Adds OpenAPI schema and documentation routes to the application.
234
+
235
+ Args:
236
+ info (Info): An instance of the Info class containing metadata about the API.
237
+ openapi_url (str): The URL path where the OpenAPI schema will be served.
238
+ docs_url (str): The URL path where the Swagger UI documentation will be served.
239
+
240
+ The method defines two internal functions:
241
+ - schema: Generates and returns the OpenAPI schema as a JSON response.
242
+ - template_render: Renders and returns the Swagger UI documentation as an HTML response.
243
+
244
+ The method then adds routes to the application for serving the OpenAPI schema and the Swagger UI documentation.
245
+ """
246
+
247
+ def schema(*args, **kwargs):
248
+ schemas = SchemaGenerator(
249
+ {
250
+ "openapi": "3.0.0",
251
+ "info": info.model_dump(),
252
+ "components": {"securitySchemes": {}},
253
+ }
254
+ )
255
+ return JSONResponse(content=orjson.dumps(schemas.get_schema(self)))
256
+
257
+ def template_render(*args, **kwargs):
258
+ swagger = SwaggerUI(
259
+ title="Swagger",
260
+ openapi_url=openapi_url,
261
+ )
262
+ template = swagger.get_html_content()
263
+ return HTMLResponse(template)
264
+
265
+ self.add_route(HTTPMethod.GET, openapi_url, schema)
266
+ self.add_route(HTTPMethod.GET, docs_url, template_render)
267
+
268
+ def add_response_header(self, key: str, value: str):
269
+ """
270
+ Adds a response header to the response headers dictionary.
271
+
272
+ Args:
273
+ key (str): The header field name.
274
+ value (str): The header field value.
275
+ """
276
+ self.response_headers[key] = value
277
+
278
+ def before_request(self):
279
+ """
280
+ A decorator to register a function to be executed before each request.
281
+
282
+ This decorator can be used to add middleware functions that will be
283
+ executed before the main request handler. The function can be either
284
+ synchronous or asynchronous.
285
+
286
+ Returns:
287
+ function: The decorator function that registers the middleware.
288
+ """
289
+
290
+ def decorator(func):
291
+ is_async = asyncio.iscoroutinefunction(func)
292
+ func_info = FunctionInfo(handler=func, is_async=is_async)
293
+ self.middleware_before_request.append(func_info)
294
+ return func
295
+
296
+ return decorator
297
+
298
+ def after_request(self):
299
+ """
300
+ Decorator to register a function to be called after each request.
301
+
302
+ This decorator can be used to register both synchronous and asynchronous functions.
303
+ The registered function will be wrapped in a FunctionInfo object and appended to the
304
+ middleware_after_request list.
305
+
306
+ Returns:
307
+ function: The decorator function that registers the given function.
308
+ """
309
+
310
+ def decorator(func):
311
+ is_async = asyncio.iscoroutinefunction(func)
312
+ func_info = FunctionInfo(handler=func, is_async=is_async)
313
+ self.middleware_after_request.append(func_info)
314
+ return func
315
+
316
+ return decorator
317
+
318
+ def inject(self, key: str, value: Any):
319
+ """
320
+ Injects a key-value pair into the injectables dictionary.
321
+
322
+ Args:
323
+ key (str): The key to be added to the injectables dictionary.
324
+ value (Any): The value to be associated with the key.
325
+
326
+ Returns:
327
+ self: Returns the instance of the class to allow method chaining.
328
+ """
329
+ self.injectables[key] = value
330
+ return self
331
+
332
+ def add_middleware(self, middleware: Middleware):
333
+ """
334
+ Adds middleware to the application.
335
+
336
+ This method attaches the middleware to the application instance and registers
337
+ its `before_request` and `after_request` hooks if they are defined.
338
+
339
+ Args:
340
+ middleware (Middleware): The middleware instance to be added.
341
+
342
+ Returns:
343
+ self: The application instance with the middleware added.
344
+ """
345
+ setattr(middleware, "app", self)
346
+ before_request = getattr(middleware, "before_request", None)
347
+ after_request = getattr(middleware, "after_request", None)
348
+
349
+ if before_request:
350
+ self.before_request()(before_request)
351
+ if after_request:
352
+ self.after_request()(after_request)
353
+ return self
354
+
355
+ def start(
356
+ self,
357
+ ):
358
+ """
359
+ Starts the server with the specified configuration.
360
+ Raises:
361
+ ValueError: If an invalid port number is entered when prompted.
362
+
363
+ """
364
+ if self.scheduler:
365
+ self.scheduler.start()
366
+
367
+ run_processes(
368
+ host=self.args.host,
369
+ port=self.args.port,
370
+ workers=self.args.workers,
371
+ processes=self.args.processes,
372
+ max_blocking_threads=self.args.max_blocking_threads,
373
+ router=self.router,
374
+ websocket_router=self.websocket_router,
375
+ injectables=self.injectables,
376
+ before_request=self.middleware_before_request,
377
+ after_request=self.middleware_after_request,
378
+ response_headers=self.response_headers,
379
+ reload=self.args.reload,
380
+ )
381
+
382
+ def add_route(self, method: HTTPMethod, endpoint: str, handler: Callable[..., Any]):
383
+ """
384
+ Adds a route to the router.
385
+
386
+ Args:
387
+ method (HTTPMethod): The HTTP method for the route (e.g., GET, POST).
388
+ endpoint (str): The endpoint path for the route.
389
+ handler (Callable[..., Any]): The function that handles requests to the route.
390
+
391
+ """
392
+ is_async = asyncio.iscoroutinefunction(handler)
393
+ func_info = FunctionInfo(handler=handler, is_async=is_async)
394
+ route = InternalRoute(path=endpoint, function=func_info, method=method.name)
395
+ self.router.add_route(route=route)
396
+
397
+ def add_websocket(self, ws_route: WebsocketRoute):
398
+ """
399
+ Adds a WebSocket route to the WebSocket router.
400
+
401
+ Args:
402
+ ws_route (WebsocketRoute): The WebSocket route to be added to the router.
403
+ """
404
+ for route in ws_route.routes:
405
+ self.websocket_router.add_route(route=route)
hypern/args_parser.py ADDED
@@ -0,0 +1,59 @@
1
+ import argparse
2
+
3
+
4
+ class ArgsConfig:
5
+ def __init__(self) -> None:
6
+ parser = argparse.ArgumentParser(description="Hypern: A Versatile Python and Rust Framework")
7
+ self.parser = parser
8
+ parser.add_argument(
9
+ "--host",
10
+ type=str,
11
+ default=None,
12
+ required=False,
13
+ help="Choose the host. [Defaults to `127.0.0.1`]",
14
+ )
15
+
16
+ parser.add_argument(
17
+ "--port",
18
+ type=int,
19
+ default=None,
20
+ required=False,
21
+ help="Choose the port. [Defaults to `5000`]",
22
+ )
23
+
24
+ parser.add_argument(
25
+ "--processes",
26
+ type=int,
27
+ default=None,
28
+ required=False,
29
+ help="Choose the number of processes. [Default: 1]",
30
+ )
31
+ parser.add_argument(
32
+ "--workers",
33
+ type=int,
34
+ default=None,
35
+ required=False,
36
+ help="Choose the number of workers. [Default: 1]",
37
+ )
38
+
39
+ parser.add_argument(
40
+ "--max-blocking-threads",
41
+ type=int,
42
+ default=None,
43
+ required=False,
44
+ help="Choose the maximum number of blocking threads. [Default: 100]",
45
+ )
46
+
47
+ parser.add_argument(
48
+ "--reload",
49
+ action="store_true",
50
+ help="It restarts the server based on file changes.",
51
+ )
52
+ args, _ = parser.parse_known_args()
53
+
54
+ self.host = args.host or "127.0.0.1"
55
+ self.port = args.port or 5000
56
+ self.max_blocking_threads = args.max_blocking_threads or 100
57
+ self.processes = args.processes or 1
58
+ self.workers = args.workers or 1
59
+ self.reload = args.reload or False
File without changes
@@ -0,0 +1,2 @@
1
+ class Authorization:
2
+ pass
hypern/background.py ADDED
@@ -0,0 +1,4 @@
1
+ from .hypern import BackgroundTask
2
+ from .hypern import BackgroundTasks
3
+
4
+ __all__ = ["BackgroundTask", "BackgroundTasks"]
File without changes
@@ -0,0 +1,8 @@
1
+ # -*- coding: utf-8 -*-
2
+ from .backend import BaseBackend
3
+ from .key_maker import BaseKeyMaker
4
+
5
+ __all__ = [
6
+ "BaseKeyMaker",
7
+ "BaseBackend",
8
+ ]
@@ -0,0 +1,3 @@
1
+ from hypern.hypern import BaseBackend
2
+
3
+ __all__ = ["BaseBackend"]
@@ -0,0 +1,8 @@
1
+ # -*- coding: utf-8 -*-
2
+ from abc import ABC, abstractmethod
3
+ from typing import Callable
4
+
5
+
6
+ class BaseKeyMaker(ABC):
7
+ @abstractmethod
8
+ async def make(self, function: Callable, prefix: str, identify_key: str) -> str: ...
@@ -0,0 +1,56 @@
1
+ # -*- coding: utf-8 -*-
2
+ from functools import wraps
3
+ from typing import Callable, Dict, Type
4
+
5
+ from .base import BaseBackend, BaseKeyMaker
6
+ from .cache_tag import CacheTag
7
+ import orjson
8
+
9
+
10
+ class CacheManager:
11
+ def __init__(self):
12
+ self.backend = None
13
+ self.key_maker = None
14
+
15
+ def init(self, backend: BaseBackend, key_maker: BaseKeyMaker) -> None:
16
+ self.backend = backend
17
+ self.key_maker = key_maker
18
+
19
+ def cached(self, tag: CacheTag, ttl: int = 60, identify: Dict = {}) -> Type[Callable]:
20
+ def _cached(function):
21
+ @wraps(function)
22
+ async def __cached(*args, **kwargs):
23
+ if not self.backend or not self.key_maker:
24
+ raise ValueError("Backend or KeyMaker not initialized")
25
+
26
+ _identify_key = []
27
+ for key, values in identify.items():
28
+ _obj = kwargs.get(key, None)
29
+ if not _obj:
30
+ raise ValueError(f"Caching: Identify key {key} not found in kwargs")
31
+ for attr in values:
32
+ _identify_key.append(f"{attr}={getattr(_obj, attr)}")
33
+ _identify_key = ":".join(_identify_key)
34
+
35
+ key = await self.key_maker.make(function=function, prefix=tag.value, identify_key=_identify_key)
36
+
37
+ cached_response = self.backend.get(key=key)
38
+ if cached_response:
39
+ return orjson.loads(cached_response)
40
+
41
+ response = await function(*args, **kwargs)
42
+ self.backend.set(response=orjson.dumps(response).decode("utf-8"), key=key, ttl=ttl)
43
+ return response
44
+
45
+ return __cached
46
+
47
+ return _cached # type: ignore
48
+
49
+ async def remove_by_tag(self, tag: CacheTag) -> None:
50
+ await self.backend.delete_startswith(value=tag.value)
51
+
52
+ async def remove_by_prefix(self, prefix: str) -> None:
53
+ await self.backend.delete_startswith(value=prefix)
54
+
55
+
56
+ Cache = CacheManager()
@@ -0,0 +1,10 @@
1
+ # -*- coding: utf-8 -*-
2
+ from enum import Enum
3
+
4
+
5
+ class CacheTag(Enum):
6
+ GET_HEALTH_CHECK = "get_health_check"
7
+ GET_USER_INFO = "get_user_info"
8
+ GET_CATEGORIES = "get_categories"
9
+ GET_HISTORY = "get_chat_history"
10
+ GET_QUESTION = "get_question"
@@ -0,0 +1,11 @@
1
+ # -*- coding: utf-8 -*-
2
+ from typing import Callable
3
+ import inspect
4
+
5
+ from hypern.caching.base import BaseKeyMaker
6
+
7
+
8
+ class CustomKeyMaker(BaseKeyMaker):
9
+ async def make(self, function: Callable, prefix: str, identify_key: str = "") -> str:
10
+ path = f"{prefix}:{inspect.getmodule(function).__name__}.{function.__name__}:{identify_key}" # type: ignore
11
+ return str(path)
@@ -0,0 +1,3 @@
1
+ from hypern.hypern import RedisBackend
2
+
3
+ __all__ = ["RedisBackend"]
hypern/cli/__init__.py ADDED
File without changes
hypern/cli/commands.py ADDED
File without changes