Skip to content

Commit 1cfdedd

Browse files
author
Ewen-Zippedscript
committed
Added examples
1 parent ec5bd2b commit 1cfdedd

File tree

8 files changed

+426
-0
lines changed

8 files changed

+426
-0
lines changed

examples/legacy/app.py

+83
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,83 @@
1+
from typing import Optional
2+
3+
from fastapi import FastAPI
4+
from models import User, db
5+
from pydantic import BaseModel
6+
7+
from fastapi_sqlalchemy import DBSessionMiddleware
8+
9+
app = FastAPI()
10+
11+
# Add DB session middleware with db_url specified
12+
app.add_middleware(DBSessionMiddleware, db_url="sqlite:///example.db")
13+
14+
15+
# Endpoint to retrieve all users
16+
@app.get("/users")
17+
def get_users():
18+
"""
19+
Retrieve a list of all users.
20+
21+
Returns:
22+
List[User]: A list of User objects.
23+
"""
24+
return db.session.query(User).all()
25+
26+
27+
# Pydantic model for creating new users
28+
class UserCreate(BaseModel):
29+
name: str
30+
email: str
31+
32+
33+
# Endpoint to add a new user
34+
@app.post("/add_user")
35+
def add_user(user_data: UserCreate):
36+
"""
37+
Add a new user to the database.
38+
39+
Args:
40+
user_data (UserCreate): User data including name and email.
41+
42+
Returns:
43+
dict: A message indicating the success of the operation.
44+
"""
45+
user = User(**user_data.dict())
46+
db.session.add(user)
47+
db.session.commit()
48+
return {"message": "User created successfully"}
49+
50+
51+
# Pydantic model for updating user information
52+
class UserUpdate(UserCreate):
53+
id: int
54+
name: Optional[str]
55+
email: Optional[str]
56+
57+
58+
# Endpoint to update user information
59+
@app.post("/update_user")
60+
def update_user(user_data: UserUpdate):
61+
"""
62+
Update user information in the database.
63+
64+
Args:
65+
user_data (UserUpdate): User data including ID, name, and email for updating.
66+
67+
Returns:
68+
dict: A message indicating the success of the operation.
69+
"""
70+
user = db.session.query(User).filter_by(id=user_data.id).first()
71+
if user_data.name:
72+
user.name = user_data.name
73+
if user_data.email:
74+
user.email = user_data.email
75+
db.session.add(user)
76+
db.session.commit()
77+
return {"message": "User updated successfully"}
78+
79+
80+
if __name__ == "__main__":
81+
import uvicorn
82+
83+
uvicorn.run(app, host="127.0.0.1", port=8000)

examples/legacy/models.py

+17
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
from sqlalchemy import Column, Integer, String, create_engine
2+
from sqlalchemy.orm import declarative_base, sessionmaker
3+
4+
from fastapi_sqlalchemy import db
5+
6+
7+
# Define the User class representing the "users" database table
8+
# Using the SQLAlchemy Base property instead of defining your own
9+
class User(db.Base):
10+
__tablename__ = "users"
11+
12+
id = Column(Integer, primary_key=True)
13+
name = Column(String)
14+
email = Column(String)
15+
16+
def __repr__(self):
17+
return f"User(id={self.id}, name='{self.name}',email='{self.email}')"

examples/multi_db/app.py

+118
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,118 @@
1+
# Import necessary modules and classes
2+
from typing import Optional
3+
4+
from fastapi import FastAPI
5+
from models.posts import Post, post_db # Import the Post model and post_db database instance
6+
from models.users import User, user_db # Import the User model and user_db database instance
7+
from pydantic import BaseModel
8+
9+
from fastapi_sqlalchemy import (
10+
DBSessionMiddleware, # Import the DBSessionMiddleware for database sessions
11+
)
12+
13+
# Create a FastAPI application instance
14+
app = FastAPI()
15+
16+
# Add the DBSessionMiddleware as a middleware to the FastAPI app, connecting it to the specified databases
17+
app.add_middleware(DBSessionMiddleware, db=[post_db, user_db])
18+
19+
20+
# Define an endpoint for retrieving all users
21+
@app.get("/users")
22+
def get_users():
23+
"""
24+
Endpoint to retrieve a list of all users.
25+
Returns:
26+
List[User]: A list of User objects representing all users in the database.
27+
"""
28+
return User.get_all()
29+
30+
31+
# Define a Pydantic model for creating a new user
32+
class UserCreate(BaseModel):
33+
name: str
34+
email: str
35+
36+
37+
# Define an endpoint for adding a new user
38+
@app.post("/add_user")
39+
def add_user(user_data: UserCreate):
40+
"""
41+
Endpoint to add a new user to the database.
42+
Args:
43+
user_data (UserCreate): User data provided in the request body.
44+
Returns:
45+
dict: A message indicating the success of the operation.
46+
"""
47+
user = User(**user_data.dict())
48+
user.save()
49+
return {"message": "User created successfully"}
50+
51+
52+
# Define a Pydantic model for updating user information
53+
class UserUpdate(UserCreate):
54+
id: int
55+
name: Optional[str]
56+
email: Optional[str]
57+
58+
59+
# Define an endpoint for updating user information
60+
@app.post("/update_user")
61+
def update_user(user_data: UserUpdate):
62+
"""
63+
Endpoint to update user information in the database.
64+
Args:
65+
user_data (UserUpdate): User data provided in the request body.
66+
Returns:
67+
dict: A message indicating the success of the operation.
68+
"""
69+
user = User.get(id=user_data.id)
70+
user.update(**user_data.dict())
71+
user.save()
72+
return {"message": "User updated successfully"}
73+
74+
75+
# Define a Pydantic model for retrieving posts by user ID
76+
class UserPosts(BaseModel):
77+
user_id: int
78+
79+
80+
# Define an endpoint for retrieving posts by user ID
81+
@app.get("/posts")
82+
def get_posts(user: UserPosts):
83+
"""
84+
Endpoint to retrieve posts by a specific user ID.
85+
Args:
86+
user (UserPosts): User ID provided in the query parameters.
87+
Returns:
88+
List[Post]: A list of Post objects belonging to the specified user.
89+
"""
90+
posts = Post.get_all(user_id=user.user_id)
91+
return posts
92+
93+
94+
# Define a Pydantic model for creating a new post
95+
class PostCreate(UserPosts):
96+
title: str
97+
content: str
98+
99+
100+
# Define an endpoint for adding a new post
101+
@app.post("/add_post")
102+
def add_post(post_data: PostCreate):
103+
"""
104+
Endpoint to add a new post to the database.
105+
Args:
106+
post_data (PostCreate): Post data provided in the request body.
107+
Returns:
108+
dict: A message indicating the success of the operation.
109+
"""
110+
post = Post(**post_data.dict())
111+
post.save()
112+
return {"message": "Post created successfully"}
113+
114+
115+
if __name__ == "__main__":
116+
import uvicorn
117+
118+
uvicorn.run(app, host="127.0.0.1", port=8000)

examples/multi_db/models/__init__.py

+52
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
import inspect
2+
from typing import Dict, List
3+
4+
from sqlalchemy import Column
5+
6+
from fastapi_sqlalchemy import ModelBase
7+
8+
9+
class BaseModel(ModelBase):
10+
@classmethod
11+
def new(cls, **kwargs):
12+
obj = cls(**kwargs)
13+
obj.save()
14+
return obj
15+
16+
@classmethod
17+
def get(cls, **kwargs):
18+
result: cls = cls.query.filter_by(**kwargs).first()
19+
return result
20+
21+
@classmethod
22+
def get_all(cls, **kwargs):
23+
result: List[cls] = cls.query.filter_by(**kwargs).all()
24+
return result
25+
26+
def update(self, **kwargs):
27+
for column, value in kwargs.items():
28+
setattr(self, column, value)
29+
30+
self.save()
31+
return self
32+
33+
def __repr__(self):
34+
try:
35+
columns = dict(
36+
(column.name, getattr(self, column.name)) for column in self.__table__.columns
37+
)
38+
39+
except:
40+
o = {}
41+
members = inspect.getmembers(self)
42+
for name, obj in members:
43+
if type(obj) == Column:
44+
o[name] = obj
45+
columns = o
46+
47+
column_strings = []
48+
for column, value in columns.items():
49+
column_strings.append(f"{column}: {value}")
50+
51+
repr = f"<{self.__class__.__name__} {', '.join(column_strings)}>"
52+
return repr

examples/multi_db/models/posts.py

+20
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
from sqlalchemy import Column, Integer, MetaData, String, create_engine
2+
from sqlalchemy.orm import DeclarativeMeta, declarative_base, sessionmaker
3+
4+
from fastapi_sqlalchemy import SQLAlchemy
5+
6+
from . import BaseModel
7+
8+
# Create a SQLAlchemy instance with a connection to the SQLite database "post.db"
9+
post_db = SQLAlchemy("sqlite:///post.db")
10+
11+
12+
# Define the User class representing the "posts" database table
13+
# using the SQLAlchemy Base property instead of defining your own
14+
# And inheriting from the BaseModel class for type hinting and helpful builtin methods and properties
15+
class Post(BaseModel, post_db.Base):
16+
__tablename__ = "posts"
17+
id = Column(Integer, primary_key=True)
18+
title = Column(String)
19+
content = Column(String)
20+
user_id = Column(Integer)

examples/multi_db/models/users.py

+36
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
# Import necessary modules and classes
2+
from sqlalchemy import Column, Integer, String, create_engine # Import SQLAlchemy components
3+
from sqlalchemy.orm import ( # Import SQLAlchemy components
4+
DeclarativeMeta,
5+
declarative_base,
6+
sessionmaker,
7+
)
8+
9+
from fastapi_sqlalchemy import SQLAlchemy # Import the SQLAlchemy extension
10+
11+
from . import BaseModel # Import the custom BaseModel
12+
13+
# Create a SQLAlchemy instance with a connection to the SQLite database "user.db"
14+
user_db = SQLAlchemy("sqlite:///user.db")
15+
16+
17+
# Define the User class representing the "users" database table
18+
# Using the SQLAlchemy Base property instead of defining your own
19+
# And inheriting from the BaseModel class for type hinting and helpful builtin methods and properties
20+
class User(BaseModel, user_db.Base):
21+
"""
22+
Represents a user in the database.
23+
24+
Attributes:
25+
id (int): The primary key of the user.
26+
name (str): The name of the user.
27+
email (str): The email address of the user.
28+
"""
29+
30+
# Name of the database table associated with this class
31+
__tablename__ = "users"
32+
33+
# Columns corresponding to the attributes of the User class
34+
id = Column(Integer, primary_key=True)
35+
name = Column(String)
36+
email = Column(String)

0 commit comments

Comments
 (0)