Skip to content

Commit

Permalink
Merge pull request #1 from sinasezza/sinasezza
Browse files Browse the repository at this point in the history
feat(config/database): connection of app to mongodb database added to…
  • Loading branch information
sinasezza authored Jul 24, 2024
2 parents 250f1b3 + b64f623 commit 6c85339
Show file tree
Hide file tree
Showing 28 changed files with 237 additions and 60 deletions.
17 changes: 0 additions & 17 deletions app/config.py

This file was deleted.

41 changes: 0 additions & 41 deletions app/main.py

This file was deleted.

File renamed without changes.
File renamed without changes.
File renamed without changes.
34 changes: 34 additions & 0 deletions chatApp/config/config.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
from functools import lru_cache
from pathlib import Path

from dotenv import load_dotenv
from pydantic import Field
from pydantic_settings import BaseSettings, SettingsConfigDict

BASE_DIR = Path(__file__).resolve().parent.parent
load_dotenv(BASE_DIR / ".env")


class Settings(BaseSettings):
debug: bool = Field(default=False)
database_url: str = "mongodb://localhost:27017"
database_name: str = "chat_app"
jwt_secret_key: str = "your-secret-key"
jwt_algorithm: str = Field(default="HS256")

# CORS settings
cors_allow_origins: list[str] = Field(default=["*"])
cors_allow_credentials: bool = Field(default=True)
cors_allow_methods: list[str] = Field(default=["*"])
cors_allow_headers: list[str] = Field(default=["*"])

model_config = SettingsConfigDict(env_file=".env", env_file_encoding="utf-8")


@lru_cache
def get_settings() -> Settings:
return Settings()


UPLOAD_DIR = BASE_DIR / "uploads"
MAX_FILE_SIZE = 5 * 1024 * 1024 # 5 MB
23 changes: 23 additions & 0 deletions chatApp/config/database.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
from motor.motor_asyncio import AsyncIOMotorClient

from .config import get_settings

settings = get_settings()

# Global variable to hold the database client
db_client = None
db = None


async def connect_to_mongodb():
global db_client, db
db_client = AsyncIOMotorClient(settings.database_url, maxPoolSize=10, minPoolSize=1)
db = db_client[settings.database_name]
print("Connected to MongoDB")


async def close_mongodb_connection():
global db_client
if db_client:
db_client.close()
print("Closed MongoDB connection")
File renamed without changes.
File renamed without changes.
63 changes: 63 additions & 0 deletions chatApp/main.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
import socketio
import uvicorn
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware

from chatApp.config.config import get_settings
from chatApp.config.database import close_mongodb_connection, connect_to_mongodb
from chatApp.routes import auth, chat, user

# Fetch settings
settings = get_settings()

app = FastAPI()

# Configure CORS using settings
app.add_middleware(
CORSMiddleware,
allow_origins=settings.cors_allow_origins,
allow_credentials=settings.cors_allow_credentials,
allow_methods=settings.cors_allow_methods,
allow_headers=settings.cors_allow_headers,
)

# Create a Socket.IO server
sio = socketio.AsyncServer(async_mode="asgi", cors_allowed_origins="*")

# Wrap with ASGI application
socket_app = socketio.ASGIApp(sio, app)


@app.get("/")
async def root():
return {"message": "Welcome to the FastAPI Chat App"}


# Define lifespan event handlers
async def lifespan(app: FastAPI):
# On startup
await connect_to_mongodb()

yield

# On shutdown
await close_mongodb_connection()


app.include_router(auth.router)
app.include_router(chat.router)
app.include_router(user.router)


@sio.event
async def connect(sid, environ):
print(f"Client connected: {sid}")


@sio.event
async def disconnect(sid):
print(f"Client disconnected: {sid}")


if __name__ == "__main__":
uvicorn.run("main:socket_app", host="0.0.0.0", port=8000, reload=True)
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
3 changes: 3 additions & 0 deletions chatApp/routes/auth.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
from fastapi import APIRouter

router = APIRouter()
3 changes: 3 additions & 0 deletions chatApp/routes/chat.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
from fastapi import APIRouter

router = APIRouter()
3 changes: 3 additions & 0 deletions chatApp/routes/user.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
from fastapi import APIRouter

router = APIRouter()
File renamed without changes.
Empty file added chatApp/schemas/message.py
Empty file.
Empty file added chatApp/schemas/user.py
Empty file.
Empty file added chatApp/services/__init__.py
Empty file.
Empty file.
Empty file.
Empty file added chatApp/utils/__init__.py
Empty file.
2 changes: 2 additions & 0 deletions mypy.ini
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
[mypy]
ignore_missing_imports = True
95 changes: 94 additions & 1 deletion poetry.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

9 changes: 8 additions & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,16 @@ license = "MIT"
readme = "README.md"
package-mode = false

[tool.isort]
line_length = 88
profile = "black"
remove_redundant_aliases = true

[tool.poetry.dependencies]
python = "^3.10"
fastapi = {extras = ["all"], version = "^0.111.1"}
uvicorn = "^0.30.3"
python-socketio = "^5.11.3"
python-socketio = {extras = ["asyncio"], version = "^5.11.3"}
pymongo = "^4.8.0"
python-jose = {extras = ["cryptography"], version = "^3.3.0"}
passlib = {extras = ["bcrypt"], version = "^1.7.4"}
Expand All @@ -21,6 +26,8 @@ isort = "^5.13.2"
pydantic-settings = "^2.3.4"
pyjwt = "^2.8.0"
python-dotenv = "^1.0.1"
motor = "^3.5.1"
mypy = "^1.11.0"


[build-system]
Expand Down
4 changes: 4 additions & 0 deletions requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,9 @@ jinja2==3.1.4 ; python_version >= "3.10" and python_version < "4.0"
markdown-it-py==3.0.0 ; python_version >= "3.10" and python_version < "4.0"
markupsafe==2.1.5 ; python_version >= "3.10" and python_version < "4.0"
mdurl==0.1.2 ; python_version >= "3.10" and python_version < "4.0"
motor==3.5.1 ; python_version >= "3.10" and python_version < "4.0"
mypy-extensions==1.0.0 ; python_version >= "3.10" and python_version < "4.0"
mypy==1.11.0 ; python_version >= "3.10" and python_version < "4.0"
nodeenv==1.9.1 ; python_version >= "3.10" and python_version < "4.0"
orjson==3.10.6 ; python_version >= "3.10" and python_version < "4.0"
passlib[bcrypt]==1.7.4 ; python_version >= "3.10" and python_version < "4.0"
Expand Down Expand Up @@ -56,6 +59,7 @@ simple-websocket==1.0.0 ; python_version >= "3.10" and python_version < "4.0"
six==1.16.0 ; python_version >= "3.10" and python_version < "4.0"
sniffio==1.3.1 ; python_version >= "3.10" and python_version < "4.0"
starlette==0.37.2 ; python_version >= "3.10" and python_version < "4.0"
tomli==2.0.1 ; python_version >= "3.10" and python_version < "3.11"
typer==0.12.3 ; python_version >= "3.10" and python_version < "4.0"
typing-extensions==4.12.2 ; python_version >= "3.10" and python_version < "4.0"
ujson==5.10.0 ; python_version >= "3.10" and python_version < "4.0"
Expand Down

0 comments on commit 6c85339

Please sign in to comment.