fastapi-globals 0.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,13 @@
1
+ # Python-generated files
2
+ __pycache__/
3
+ *.py[oc]
4
+ /build/
5
+ /dist/
6
+ /wheels/
7
+ /*.egg-info
8
+ /uv.lock
9
+ /.coverage
10
+ /.tox
11
+
12
+ # Virtual environments
13
+ /.venv
@@ -0,0 +1,20 @@
1
+ The MIT License (MIT)
2
+ Copyright (c) 2022 TEAM23 GmbH
3
+
4
+ Permission is hereby granted, free of charge, to any person obtaining a copy
5
+ of this software and associated documentation files (the "Software"), to deal
6
+ in the Software without restriction, including without limitation the rights
7
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8
+ copies of the Software, and to permit persons to whom the Software is
9
+ furnished to do so, subject to the following conditions:
10
+
11
+ The above copyright notice and this permission notice shall be included in all
12
+ copies or substantial portions of the Software.
13
+
14
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
15
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
17
+ IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
18
+ DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
19
+ OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE
20
+ OR OTHER DEALINGS IN THE SOFTWARE.
@@ -0,0 +1,68 @@
1
+ Metadata-Version: 2.3
2
+ Name: fastapi-globals
3
+ Version: 0.1.0
4
+ Summary: Use request global variables in FastAPI
5
+ Requires-Python: >=3.9
6
+ Requires-Dist: fastapi<1.0,>=0.100
7
+ Description-Content-Type: text/markdown
8
+
9
+ # `fastapi-globals`
10
+
11
+ Allows you to use request global values. Can be used to store request speficic data, like state, database
12
+ connection, etc.
13
+
14
+ ## Installation
15
+
16
+ Just use `pip install fastapi-globals` to install the library.
17
+
18
+ **Note:** `fastapi-globals` is compatible with `fastapi` versions `0.100.0` and later on
19
+ Python `3.9`, `3.10`, `3.11`, `3.12` and `3.13`. This is also ensured running all tests on all those versions
20
+ using `tox`.
21
+
22
+ # Usage
23
+
24
+ Just import `g` and then access (set/get) attributes of it:
25
+ ```python
26
+ from fastapi_globals import g
27
+
28
+
29
+ g.foo = "foo"
30
+
31
+ # In some other code
32
+ assert g.foo == "foo"
33
+ ```
34
+
35
+ Best way to utilize the global `g` in your code is to set the desired
36
+ value in a FastAPI dependency, like so:
37
+ ```python
38
+ async def set_global_foo() -> None:
39
+ g.foo = "foo"
40
+
41
+
42
+ @app.get("/test/", dependencies=[Depends(set_global_foo)])
43
+ async def test():
44
+ assert g.foo == "foo"
45
+ ```
46
+
47
+ # Setup
48
+
49
+ Add the `GlobalsMiddleware` to your app:
50
+ ```python
51
+ app = fastapi.FastAPI(
52
+ title="Your app API",
53
+ )
54
+ app.add_middleware(GlobalsMiddleware) # <-- This line is necessary
55
+ ```
56
+
57
+ Then just use it. ;-)
58
+
59
+ # Default values
60
+
61
+ You may use `g.set_default("name", some_value)` to set a default value
62
+ for a global variable. This default value will then be used instead of `None`
63
+ when the variable is accessed before it was set.
64
+
65
+ Note that default values should only be set at startup time, never
66
+ inside dependencies or similar. Otherwise you may run into the issue that
67
+ the value was already used any thus have a value of `None` set already, which
68
+ would result in the default value not being used.
@@ -0,0 +1,60 @@
1
+ # `fastapi-globals`
2
+
3
+ Allows you to use request global values. Can be used to store request speficic data, like state, database
4
+ connection, etc.
5
+
6
+ ## Installation
7
+
8
+ Just use `pip install fastapi-globals` to install the library.
9
+
10
+ **Note:** `fastapi-globals` is compatible with `fastapi` versions `0.100.0` and later on
11
+ Python `3.9`, `3.10`, `3.11`, `3.12` and `3.13`. This is also ensured running all tests on all those versions
12
+ using `tox`.
13
+
14
+ # Usage
15
+
16
+ Just import `g` and then access (set/get) attributes of it:
17
+ ```python
18
+ from fastapi_globals import g
19
+
20
+
21
+ g.foo = "foo"
22
+
23
+ # In some other code
24
+ assert g.foo == "foo"
25
+ ```
26
+
27
+ Best way to utilize the global `g` in your code is to set the desired
28
+ value in a FastAPI dependency, like so:
29
+ ```python
30
+ async def set_global_foo() -> None:
31
+ g.foo = "foo"
32
+
33
+
34
+ @app.get("/test/", dependencies=[Depends(set_global_foo)])
35
+ async def test():
36
+ assert g.foo == "foo"
37
+ ```
38
+
39
+ # Setup
40
+
41
+ Add the `GlobalsMiddleware` to your app:
42
+ ```python
43
+ app = fastapi.FastAPI(
44
+ title="Your app API",
45
+ )
46
+ app.add_middleware(GlobalsMiddleware) # <-- This line is necessary
47
+ ```
48
+
49
+ Then just use it. ;-)
50
+
51
+ # Default values
52
+
53
+ You may use `g.set_default("name", some_value)` to set a default value
54
+ for a global variable. This default value will then be used instead of `None`
55
+ when the variable is accessed before it was set.
56
+
57
+ Note that default values should only be set at startup time, never
58
+ inside dependencies or similar. Otherwise you may run into the issue that
59
+ the value was already used any thus have a value of `None` set already, which
60
+ would result in the default value not being used.
@@ -0,0 +1,5 @@
1
+ from .globals import (
2
+ Globals as Globals,
3
+ GlobalsMiddleware as GlobalsMiddleware,
4
+ g as g,
5
+ )
@@ -0,0 +1,139 @@
1
+ """
2
+ Allow to use global variables inside the FastAPI application using async mode.
3
+
4
+ # Usage
5
+
6
+ Just import `g` and then access (set/get) attributes of it:
7
+ ```python
8
+ from fastapi_globals import g
9
+
10
+
11
+ g.foo = "foo"
12
+
13
+ # In some other code
14
+ assert g.foo == "foo"
15
+ ```
16
+
17
+ Best way to utilize the global `g` in your code is to set the desired
18
+ value in a FastAPI dependency, like so:
19
+ ```python
20
+ async def set_global_foo() -> None:
21
+ g.foo = "foo"
22
+
23
+
24
+ @app.get("/test/", dependencies=[Depends(set_global_foo)])
25
+ async def test():
26
+ assert g.foo == "foo"
27
+ ```
28
+
29
+ # Setup
30
+
31
+ Add the `GlobalsMiddleware` to your app:
32
+ ```python
33
+ app = fastapi.FastAPI(
34
+ title="Your app API",
35
+ )
36
+ app.add_middleware(GlobalsMiddleware) # <-- This line is necessary
37
+ ```
38
+
39
+ Then just use it. ;-)
40
+
41
+ # Default values
42
+
43
+ You may use `g.set_default("name", some_value)` to set a default value
44
+ for a global variable. This default value will then be used instead of `None`
45
+ when the variable is accessed before it was set.
46
+
47
+ Note that default values should only be set at startup time, never
48
+ inside dependencies or similar. Otherwise you may run into the issue that
49
+ the value was already used any thus have a value of `None` set already, which
50
+ would result in the default value not being used.
51
+ """
52
+ from collections.abc import Awaitable, Callable
53
+ from contextvars import ContextVar, copy_context
54
+ from typing import Any
55
+
56
+ from fastapi import Request, Response
57
+ from starlette.middleware.base import BaseHTTPMiddleware
58
+ from starlette.types import ASGIApp
59
+
60
+
61
+ class Globals:
62
+ __slots__ = ("_vars", "_defaults")
63
+
64
+ _vars: dict[str, ContextVar]
65
+ _defaults: dict[str, Any]
66
+
67
+ def __init__(self) -> None:
68
+ object.__setattr__(self, '_vars', {})
69
+ object.__setattr__(self, '_defaults', {})
70
+
71
+ def set_default(self, name: str, default: Any) -> None:
72
+ """Set a default value for a variable."""
73
+
74
+ # Ignore if default is already set and is the same value
75
+ if (
76
+ name in self._defaults
77
+ and default is self._defaults[name]
78
+ ):
79
+ return
80
+
81
+ # Ensure we don't have a value set already - the default will have
82
+ # no effect then
83
+ if name in self._vars:
84
+ raise RuntimeError(
85
+ f"Cannot set default as variable {name} was already set",
86
+ )
87
+
88
+ # Set the default already!
89
+ self._defaults[name] = default
90
+
91
+ def _get_default_value(self, name: str) -> Any:
92
+ """Get the default value for a variable."""
93
+
94
+ default = self._defaults.get(name, None)
95
+
96
+ return default() if callable(default) else default
97
+
98
+ def _ensure_var(self, name: str) -> None:
99
+ """Ensure a ContextVar exists for a variable."""
100
+
101
+ if name not in self._vars:
102
+ default = self._get_default_value(name)
103
+ self._vars[name] = ContextVar(f"globals:{name}", default=default)
104
+
105
+ def __getattr__(self, name: str) -> Any:
106
+ """Get the value of a variable."""
107
+
108
+ self._ensure_var(name)
109
+ return self._vars[name].get()
110
+
111
+ def __setattr__(self, name: str, value: Any) -> None:
112
+ """Set the value of a variable."""
113
+
114
+ self._ensure_var(name)
115
+ self._vars[name].set(value)
116
+
117
+
118
+ async def globals_middleware_dispatch(
119
+ request: Request,
120
+ call_next: Callable,
121
+ ) -> Response:
122
+ """Dispatch the request in a new context to allow globals to be used."""
123
+
124
+ ctx = copy_context()
125
+
126
+ def _call_next() -> Awaitable[Response]:
127
+ return call_next(request)
128
+
129
+ return await ctx.run(_call_next)
130
+
131
+
132
+ class GlobalsMiddleware(BaseHTTPMiddleware):
133
+ """Middleware to setup the globals context using globals_middleware_dispatch()."""
134
+
135
+ def __init__(self, app: ASGIApp) -> None:
136
+ super().__init__(app, globals_middleware_dispatch)
137
+
138
+
139
+ g = Globals()
File without changes
@@ -0,0 +1,31 @@
1
+ [project]
2
+ name = "fastapi-globals"
3
+ version = "0.1.0"
4
+ description = "Use request global variables in FastAPI"
5
+ readme = "README.md"
6
+ requires-python = ">=3.9"
7
+ dependencies = [
8
+ "fastapi>=0.100,<1.0",
9
+ ]
10
+
11
+ [dependency-groups]
12
+ dev = [
13
+ "trio>=0.27.0",
14
+ "httpx>=0.27.2",
15
+ "pytest-cov>=6.0.0",
16
+ "pytest>=8.3.3",
17
+ "anyio>=4.6.2.post1",
18
+ "pyright>=1.1.389",
19
+ "ruff>=0.8.0",
20
+ "tox>=4.23.2",
21
+ "tomlkit>=0.13.2",
22
+ ]
23
+
24
+ [build-system]
25
+ requires = ["hatchling"]
26
+ build-backend = "hatchling.build"
27
+
28
+ [tool.hatch.build]
29
+ include = [
30
+ "fastapi_globals",
31
+ ]