fastapi-sqlalchemy-ease 0.1.4__py3-none-any.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.
- fastapi_sqlalchemy_ease/__init__.py +12 -0
- fastapi_sqlalchemy_ease/core.py +143 -0
- fastapi_sqlalchemy_ease/exceptions.py +7 -0
- fastapi_sqlalchemy_ease-0.1.4.dist-info/METADATA +109 -0
- fastapi_sqlalchemy_ease-0.1.4.dist-info/RECORD +8 -0
- fastapi_sqlalchemy_ease-0.1.4.dist-info/WHEEL +5 -0
- fastapi_sqlalchemy_ease-0.1.4.dist-info/licenses/LICENSE +21 -0
- fastapi_sqlalchemy_ease-0.1.4.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
from .core import SQLAlchemy
|
|
2
|
+
from .exceptions import DatabaseError, DatabaseNotInitializedError
|
|
3
|
+
|
|
4
|
+
__version__='0.1.4'
|
|
5
|
+
|
|
6
|
+
# when someone call: from fastapi_sqlalchemy import SQLAlchemy
|
|
7
|
+
# only these things are available
|
|
8
|
+
__all__ = [
|
|
9
|
+
"SQLAlchemy",
|
|
10
|
+
"DatabaseError",
|
|
11
|
+
"DatabaseNotInitializedError",
|
|
12
|
+
]
|
|
@@ -0,0 +1,143 @@
|
|
|
1
|
+
from sqlalchemy import (
|
|
2
|
+
create_engine,
|
|
3
|
+
Column, Integer, String, Text, Float, Boolean,
|
|
4
|
+
Date, DateTime, Time,
|
|
5
|
+
JSON, LargeBinary,
|
|
6
|
+
Numeric,
|
|
7
|
+
ForeignKey,
|
|
8
|
+
UniqueConstraint, CheckConstraint,
|
|
9
|
+
Index, Table
|
|
10
|
+
)
|
|
11
|
+
from sqlalchemy.orm import declarative_base, sessionmaker, Session, relationship
|
|
12
|
+
from typing import Generator, Optional
|
|
13
|
+
from .exceptions import DatabaseNotInitializedError
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class SQLAlchemy:
|
|
17
|
+
# Singleton - ensures only one instance exists in the app
|
|
18
|
+
_instance = None
|
|
19
|
+
|
|
20
|
+
# All sqlalchemy types as class attributes
|
|
21
|
+
'''Data types'''
|
|
22
|
+
Column = Column
|
|
23
|
+
String = String
|
|
24
|
+
Integer = Integer
|
|
25
|
+
Float = Float
|
|
26
|
+
Boolean = Boolean
|
|
27
|
+
Text = Text
|
|
28
|
+
Date = Date
|
|
29
|
+
DateTime = DateTime
|
|
30
|
+
Time = Time
|
|
31
|
+
JSON = JSON
|
|
32
|
+
LargeBinary = LargeBinary
|
|
33
|
+
Numeric = Numeric
|
|
34
|
+
|
|
35
|
+
'''Relationships and Constraints'''
|
|
36
|
+
ForeignKey = ForeignKey
|
|
37
|
+
UniqueConstraint = UniqueConstraint
|
|
38
|
+
CheckConstraint = CheckConstraint
|
|
39
|
+
Index = Index
|
|
40
|
+
Table = Table
|
|
41
|
+
relationship = relationship
|
|
42
|
+
|
|
43
|
+
def __new__(cls):
|
|
44
|
+
if cls._instance is None:
|
|
45
|
+
cls._instance = super().__new__(cls)
|
|
46
|
+
return cls._instance
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def __init__(self):
|
|
50
|
+
# Everything starts as None Until db.init_app() is called
|
|
51
|
+
self.engine = None
|
|
52
|
+
self._SessionLocal = None
|
|
53
|
+
self._Model = None
|
|
54
|
+
self._initialized = False
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def init_app(self, DATABASE_URI: str, connect_args: Optional[dict]=None):
|
|
58
|
+
'''
|
|
59
|
+
Docstring for init_app
|
|
60
|
+
|
|
61
|
+
used to Initialized database.
|
|
62
|
+
|
|
63
|
+
DATABASE_URI: database url, type : string
|
|
64
|
+
connect_args: used only when initializing sqlite db
|
|
65
|
+
'''
|
|
66
|
+
|
|
67
|
+
engine_kwargs={}
|
|
68
|
+
|
|
69
|
+
if connect_args:
|
|
70
|
+
engine_kwargs['connect_args'] = connect_args # sqlite need this
|
|
71
|
+
else:
|
|
72
|
+
engine_kwargs['pool_pre_ping'] = True # Keeps connection alive for PostgreSQL/MySQL
|
|
73
|
+
|
|
74
|
+
# Engine connection to database
|
|
75
|
+
self.engine = create_engine(DATABASE_URI, **engine_kwargs)
|
|
76
|
+
|
|
77
|
+
# SessionLocal - Factory data creates new sessions
|
|
78
|
+
self._SessionLocal = sessionmaker(autoflush=False ,bind=self.engine)
|
|
79
|
+
|
|
80
|
+
# Model - base class, all our database models will inherit from
|
|
81
|
+
self._Model = declarative_base()
|
|
82
|
+
|
|
83
|
+
self._initialized = True
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
@property
|
|
87
|
+
def Model(self):
|
|
88
|
+
'''
|
|
89
|
+
Docstring for Model
|
|
90
|
+
|
|
91
|
+
Base class for creating database models
|
|
92
|
+
User writes: class User(db.Model):
|
|
93
|
+
'''
|
|
94
|
+
|
|
95
|
+
if not self._initialized:
|
|
96
|
+
raise DatabaseNotInitializedError('Database not Intialized, call db.init_app() first.')
|
|
97
|
+
|
|
98
|
+
return self._Model
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def create_all(self):
|
|
102
|
+
'''
|
|
103
|
+
Docstring for create_all
|
|
104
|
+
|
|
105
|
+
create all tables in the database
|
|
106
|
+
'''
|
|
107
|
+
|
|
108
|
+
if not self._initialized:
|
|
109
|
+
raise DatabaseNotInitializedError('Database not Intialized, call db.init_app() first.')
|
|
110
|
+
|
|
111
|
+
self._Model.metadata.create_all(self.engine)
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def drop_all(self):
|
|
115
|
+
'''
|
|
116
|
+
Docstring for drop_all
|
|
117
|
+
|
|
118
|
+
delete all tables from the database.
|
|
119
|
+
'''
|
|
120
|
+
if not self._initialized:
|
|
121
|
+
raise DatabaseNotInitializedError('Database not Intialized, call db.init_app() first.')
|
|
122
|
+
|
|
123
|
+
self._Model.metadata.drop_all(self.engine)
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def Session(self) -> Generator[Session, None, None]:
|
|
127
|
+
'''
|
|
128
|
+
Docstring for Session
|
|
129
|
+
|
|
130
|
+
creates a new session per request.
|
|
131
|
+
must use with Depends in FastAPI().
|
|
132
|
+
Auto closes sessions after request is done.
|
|
133
|
+
|
|
134
|
+
'''
|
|
135
|
+
|
|
136
|
+
if not self._initialized:
|
|
137
|
+
raise DatabaseNotInitializedError('Database not Intialized, call db.init_app() first.')
|
|
138
|
+
|
|
139
|
+
session = self._SessionLocal()
|
|
140
|
+
try:
|
|
141
|
+
yield session # Give session to the route
|
|
142
|
+
finally:
|
|
143
|
+
session.close() #always close after one requst
|
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: fastapi-sqlalchemy-ease
|
|
3
|
+
Version: 0.1.4
|
|
4
|
+
Summary: A reusable SQLAlchemy extension for FastAPI
|
|
5
|
+
Requires-Python: >=3.8
|
|
6
|
+
Description-Content-Type: text/markdown
|
|
7
|
+
License-File: LICENSE
|
|
8
|
+
Requires-Dist: sqlalchemy>=2.0.0
|
|
9
|
+
Dynamic: description
|
|
10
|
+
Dynamic: description-content-type
|
|
11
|
+
Dynamic: license-file
|
|
12
|
+
Dynamic: requires-dist
|
|
13
|
+
Dynamic: requires-python
|
|
14
|
+
Dynamic: summary
|
|
15
|
+
|
|
16
|
+
# fastapi-sqlalchemy-ease
|
|
17
|
+
|
|
18
|
+
fastapi-sqlalchemy-ease is a singleton-based SQLAlchemy extension for FastAPI. It provides a centralized interface for database initialization, model declaration, and session management, inspired by the simplicity of Flask-SQLAlchemy.
|
|
19
|
+
|
|
20
|
+
## ◽ Key Features
|
|
21
|
+
|
|
22
|
+
- Singleton Design: Ensures a single database instance across your entire FastAPI application.
|
|
23
|
+
|
|
24
|
+
- Consolidated API: Access all SQLAlchemy types (Integer, String, ForeignKey, etc.) directly from the db object.
|
|
25
|
+
|
|
26
|
+
- Auto-Cleanup: Includes a generator-based session handler designed for FastAPI's Depends to ensure sessions are always closed.
|
|
27
|
+
|
|
28
|
+
- Built-in Lifecycle Management: Simple methods for create_all() and drop_all().
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
## ◽ Installation
|
|
32
|
+
|
|
33
|
+
pip install fastapi-sqlalchemy-ease
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
## ◽ Usage Guide
|
|
38
|
+
|
|
39
|
+
### 1. Basic setup
|
|
40
|
+
Initialize your database instance in a centralized file (e.g. database.py).
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
from fastapi_sqlalchemy_ease import SQLAlchemy
|
|
44
|
+
|
|
45
|
+
'''Create the singleton instance'''
|
|
46
|
+
db = SQLAlchemy()
|
|
47
|
+
|
|
48
|
+
'''Initialize with your URI'''
|
|
49
|
+
DATABASE_URI = "sqlite:///./test.db"
|
|
50
|
+
|
|
51
|
+
'''Use connect_args={"check_same_thread": False} for SQLite'''
|
|
52
|
+
db.init_app(DATABASE_URI, connect_args={"check_same_thread": False})
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
### 2. Defining Models
|
|
57
|
+
No need to import types from SQLAlchemy; use the db instance directly.
|
|
58
|
+
|
|
59
|
+
class User(db.Model):
|
|
60
|
+
__tablename__ = "users"
|
|
61
|
+
|
|
62
|
+
id = db.Column(db.Integer, primary_key=True)
|
|
63
|
+
username = db.Column(db.String, unique=True, nullable=False)
|
|
64
|
+
created_at = db.Column(db.DateTime)
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
### 3. Creating Tables
|
|
69
|
+
You can trigger table creation easily.
|
|
70
|
+
|
|
71
|
+
db.create_all()
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
### 3. Database Operations in Routes
|
|
76
|
+
Use db.Session with FastAPI's Depends to get a clean session for every request.
|
|
77
|
+
|
|
78
|
+
from fastapi import FastAPI, Depends
|
|
79
|
+
from .. import db
|
|
80
|
+
|
|
81
|
+
app = FastAPI()
|
|
82
|
+
|
|
83
|
+
@app.get("/users")
|
|
84
|
+
def read_users(session: Session = Depends(db.Session)):
|
|
85
|
+
users = session.query(User).all()
|
|
86
|
+
return users
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
## ◽ Available Attributes
|
|
91
|
+
Your db instance provides easy access to standard SQLAlchemy types and constraints:
|
|
92
|
+
|
|
93
|
+
Category - Available Attributes
|
|
94
|
+
|
|
95
|
+
Data Types - String, Integer, Float, Boolean, Text, Date, DateTime, JSON, Numeric
|
|
96
|
+
Constraints - ForeignKey, UniqueConstraint, CheckConstraint, Index
|
|
97
|
+
ORM - relationship, Table, Column
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
## ◽ Error Handling
|
|
102
|
+
The library includes a DatabaseNotInitializedError. If you attempt to access db.Model, db.Session, or lifecycle methods before calling db.init_app(), a clear exception will be raised to help you debug quickly.
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
## 📄 License
|
|
107
|
+
Distributed under the MIT License.
|
|
108
|
+
|
|
109
|
+
--
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
fastapi_sqlalchemy_ease/__init__.py,sha256=iSppUZlZ6IKZuuDzaoc0pjDer-EEg1gtr5PjSMUgm3w,303
|
|
2
|
+
fastapi_sqlalchemy_ease/core.py,sha256=nQSzioMp6TiD7yuKD7niImA2BSL2PQLCKnCzk0eFWrA,3920
|
|
3
|
+
fastapi_sqlalchemy_ease/exceptions.py,sha256=6YU6mJvOGXC9D0mPH99GjMWpj21NA5jD8II7DWEcHaA,222
|
|
4
|
+
fastapi_sqlalchemy_ease-0.1.4.dist-info/licenses/LICENSE,sha256=jVnW2ZK4LFNHmDZE-xj0EyVpbHVMpwO7FcTk_We8qrA,1068
|
|
5
|
+
fastapi_sqlalchemy_ease-0.1.4.dist-info/METADATA,sha256=13RjpemmXPdFHY0tLpQxHN7THFuG1U-WQTxFRcvA71c,3144
|
|
6
|
+
fastapi_sqlalchemy_ease-0.1.4.dist-info/WHEEL,sha256=wUyA8OaulRlbfwMtmQsvNngGrxQHAvkKcvRmdizlJi0,92
|
|
7
|
+
fastapi_sqlalchemy_ease-0.1.4.dist-info/top_level.txt,sha256=Y9kRilavMJot8bwOZymZ0cRjiBNIzsVqx9EwvXGiq-8,24
|
|
8
|
+
fastapi_sqlalchemy_ease-0.1.4.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Hardik Soni
|
|
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.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
fastapi_sqlalchemy_ease
|