Skip to content

Commit

Permalink
Chore: Update Singleton Pattern
Browse files Browse the repository at this point in the history
Chore: Update Container
  • Loading branch information
David Peña authored and davisfelipe committed Apr 24, 2021
1 parent ec83c82 commit aef1e22
Show file tree
Hide file tree
Showing 11 changed files with 131 additions and 66 deletions.
20 changes: 20 additions & 0 deletions Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
FROM python:3.8-slim-buster
EXPOSE 8080

ENV PYTHONUNBUFFERED 1
ENV APP_HOME /app

COPY requirements.txt .

RUN pip install --no-cache-dir -U pip \
&& pip install --no-cache-dir -r requirements.txt

WORKDIR ${APP_HOME}

COPY src src
COPY main.py .
COPY docker-entrypoint.sh .
COPY .env .

ENTRYPOINT ["/bin/bash"]
CMD ["./docker-entrypoint.sh"]
32 changes: 32 additions & 0 deletions docker-compose.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
version: "3.5"
services:
user_app:
build: .
container_name: cdslab_models_app
env_file: .env
image: cdslab_user
networks:
- cdslab_models
ports:
- 5000:5000
volumes:
- ./src:/app/src

user_mongo:
container_name: cdslab_models_mongo
environment:
MONGO_INITDB_ROOT_USERNAME: cdsuser
MONGO_INITDB_ROOT_PASSWORD: cdspass
image: mongo:3-xenial
networks:
- cdslab_models
ports:
- 27017:27017
volumes:
- /tmp/data/cdslab_models/:/data/db


networks:
cdslab_models:
name: cdslab_user
driver: bridge
7 changes: 7 additions & 0 deletions docker-entrypoint.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
#!/bin/bash

if [ -z "${PORT}" ] ; then PORT=8080; fi

if [ -z "${HOST}" ] ; then HOST=0.0.0.0; fi

uvicorn main:app --port=${PORT} --host=${HOST} --reload
2 changes: 2 additions & 0 deletions main.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
import uvicorn

from src.api import app
from src.config import settings
from src.use_cases.cmodels import CmodelUseCases

__all__ = ['app']

if __name__ == '__main__':
CmodelUseCases.update_cmodels_collection()
Expand Down
2 changes: 2 additions & 0 deletions requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ iniconfig==1.1.1
mccabe==0.6.1
mongomock==3.22.1
packaging==20.9; python_version >= '2.7' and python_version not in '3.0, 3.1, 3.2, 3.3'
pandas==1.2.4
pluggy==0.13.1; python_version >= '2.7' and python_version not in '3.0, 3.1, 3.2, 3.3'
py==1.10.0; python_version >= '2.7' and python_version not in '3.0, 3.1, 3.2, 3.3'
pycodestyle==2.7.0; python_version >= '2.7' and python_version not in '3.0, 3.1, 3.2, 3.3'
Expand All @@ -24,6 +25,7 @@ pyparsing==2.4.7; python_version >= '2.6' and python_version not in '3.0, 3.1, 3
pytest-cov==2.11.1
pytest==6.2.3
python-dotenv==0.17.0
python-multipart==0.0.5
requests==2.25.1
sentinels==1.0.0
six==1.15.0; python_version >= '2.7' and python_version not in '3.0, 3.1, 3.2, 3.3'
Expand Down
10 changes: 4 additions & 6 deletions src/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,21 +5,19 @@
from src.config import settings
from src.routers.main import main_router


app = FastAPI()


app.add_middleware(
TrustedHostMiddleware,
allowed_hosts=settings["ALLOWED_HOSTS"].split(",")
allowed_hosts=settings.get("ALLOWED_HOSTS", "*").split(",")
)

app.add_middleware(
CORSMiddleware,
allow_credentials=True,
allow_origins=settings["ALLOWED_ORIGINS"].split(","),
allow_methods=settings["ALLOWED_METHODS"].split(","),
allow_headers=settings["ALLOWED_HEADERS"].split(",")
allow_origins=settings.get("ALLOWED_ORIGINS", "*").split(","),
allow_methods=settings.get("ALLOWED_METHODS", "*").split(","),
allow_headers=settings.get("ALLOWED_HEADERS", "*").split(",")
)

app.include_router(
Expand Down
110 changes: 53 additions & 57 deletions src/db/mongo.py
Original file line number Diff line number Diff line change
@@ -1,63 +1,59 @@
from typing import Generator, Tuple

from pymongo import MongoClient
from pymongo.database import Database
from pymongo.collection import Collection
from pymongo.database import Database

from src.config import db_config


def api_get_db_connection(
db_uri: str = db_config['MONGO_URI'],
) -> Generator[MongoClient, None, None]:
"""Creates connection to Mongodb server.
Yields
------
db_connection: MongoClient
Object containing the db connection.
"""
db_connection = MongoClient(db_uri)

try:
yield db_connection
finally:
db_connection.close()


def get_db(
db_uri: str = db_config['MONGO_URI'],
db_name: str = db_config['MONGO_DB']
) -> Tuple[MongoClient, Database]:
"""Gets Mongodb connection and database.
Parameters
----------
db_uri: str
Mongo server URI.
db_name: str
Mongo database name.
Returns
-------
db_connection : MongoClient
db : pymongo.database.Database
"""
db_connection = MongoClient(db_uri)
db: Database = db_connection[db_name]

return db_connection, db


def get_collection(
coll_name: str = db_config['CMODELS_COLL']
) -> Tuple[MongoClient, Collection]:
"""
Returns
-------
db_connection: pymongo.MongoClient
coll: pymongo.collection.Collection
"""
db_connection, db = get_db()
coll: Collection = db[coll_name]
return db_connection, coll
from src.utils.patterns import Singleton


class MongoConnection(metaclass=Singleton):
db_uri = db_config.get('MONGO_URI')
db_name = db_config.get('MONGO_DB')
collection_name = db_config.get('CMODELS_COLL')

def api_get_db_connection(self) -> Generator[MongoClient, None, None]:
"""Creates connection to Mongodb server.
Yields
------
db_connection: MongoClient
Object containing the db connection.
"""
db_connection = MongoClient(self.db_uri)

try:
yield db_connection
finally:
db_connection.close()

def get_db(self) -> Tuple[MongoClient, Database]:
"""Gets Mongodb connection and database.
Returns
-------
db_connection : MongoClient
db : pymongo.database.Database
"""
db_connection = MongoClient(self.db_uri)
db: Database = db_connection[self.db_name]

return db_connection, db

def get_collection(
self,
collection_name: str = None
) -> Tuple[MongoClient, Collection]:
"""
Returns
-------
db_connection: pymongo.MongoClient
coll: pymongo.collection.Collection
"""
if not collection_name:
collection_name = self.collection_name
pass
db_connection, db = self.get_db()
coll: Collection = db[collection_name]
return db_connection, coll
2 changes: 1 addition & 1 deletion src/interfaces/crud.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
from pymongo.mongo_client import MongoClient


class MongoCRUD():
class MongoCRUD:
def __init__(
self,
db_connection: MongoClient,
Expand Down
1 change: 1 addition & 0 deletions src/routers/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
main_router_prefix = ""
main_router = APIRouter(prefix=main_router_prefix)


@main_router.get('/')
async def hello(request: Request):
return {'hello': 'world'}
4 changes: 2 additions & 2 deletions src/use_cases/cmodels.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
from src.db.mongo import get_collection
from src.db.mongo import MongoConnection
from src.interfaces.cmodels import CModelsInterface


class CmodelUseCases:
@staticmethod
def update_cmodels_collection():
db_connection, cmodels_coll = get_collection()
db_connection, cmodels_coll = MongoConnection().get_collection()
cmodels_interface = CModelsInterface(db_connection, cmodels_coll)
cmodels_interface.insert_all_cmodel_documents()
7 changes: 7 additions & 0 deletions src/utils/patterns.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
class Singleton(type):
_instances = {}

def __call__(cls, *args, **kwargs):
if cls not in cls._instances:
cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs)
return cls._instances[cls]

0 comments on commit aef1e22

Please sign in to comment.