fastapi-sqlalchemy-ease 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,9 @@
1
+ Metadata-Version: 2.4
2
+ Name: fastapi-sqlalchemy-ease
3
+ Version: 0.1.0
4
+ Summary: A reusable SQLAlchemy extension for FastAPI
5
+ Requires-Python: >=3.8
6
+ Requires-Dist: sqlalchemy>=2.0.0
7
+ Dynamic: requires-dist
8
+ Dynamic: requires-python
9
+ Dynamic: summary
@@ -0,0 +1,16 @@
1
+ # fastapi-sqlalchemy
2
+ A reusable SQLAlchemy extension for FastAPI.
3
+
4
+ ## Installation
5
+ ```bash
6
+ pip install fastapi-sqlalchemy
7
+ ```
8
+
9
+ ## Usage
10
+ ```python
11
+ from fastapi_sqlalchemy import SQLAlchemy
12
+
13
+ db = SQLAlchemy()
14
+ DATABASE_URI = "sqlite:///site.db"
15
+ db.init_app(DATABASE_URI)
16
+ ```
@@ -0,0 +1,12 @@
1
+ from .core import SQLAlchemy
2
+ from .exceptions import DatabaseError, DatabaseNotInitializedError
3
+
4
+ __version__='0.1.0'
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,7 @@
1
+ class DatabaseError(Exception):
2
+ """Base error - all other errors inherit from this"""
3
+ pass
4
+
5
+ class DatabaseNotInitializedError(DatabaseError):
6
+ """Raised when someone uses db before calling init_app()"""
7
+ pass
@@ -0,0 +1,9 @@
1
+ Metadata-Version: 2.4
2
+ Name: fastapi-sqlalchemy-ease
3
+ Version: 0.1.0
4
+ Summary: A reusable SQLAlchemy extension for FastAPI
5
+ Requires-Python: >=3.8
6
+ Requires-Dist: sqlalchemy>=2.0.0
7
+ Dynamic: requires-dist
8
+ Dynamic: requires-python
9
+ Dynamic: summary
@@ -0,0 +1,11 @@
1
+ README.md
2
+ pyproject.toml
3
+ setup.py
4
+ fastapi_sqlalchemy_ease/__init__.py
5
+ fastapi_sqlalchemy_ease/core.py
6
+ fastapi_sqlalchemy_ease/exceptions.py
7
+ fastapi_sqlalchemy_ease.egg-info/PKG-INFO
8
+ fastapi_sqlalchemy_ease.egg-info/SOURCES.txt
9
+ fastapi_sqlalchemy_ease.egg-info/dependency_links.txt
10
+ fastapi_sqlalchemy_ease.egg-info/requires.txt
11
+ fastapi_sqlalchemy_ease.egg-info/top_level.txt
@@ -0,0 +1 @@
1
+ fastapi_sqlalchemy_ease
@@ -0,0 +1,3 @@
1
+ [build-system]
2
+ requires = ["setuptools>=61.0", "wheel"]
3
+ build-backend = "setuptools.build_meta"
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,12 @@
1
+ from setuptools import setup, find_packages
2
+
3
+ setup(
4
+ name='fastapi-sqlalchemy-ease',
5
+ version='0.1.0',
6
+ description="A reusable SQLAlchemy extension for FastAPI",
7
+ packages=find_packages(),
8
+ python_requires='>=3.8',
9
+ install_requires=[
10
+ 'sqlalchemy>=2.0.0'
11
+ ],
12
+ )