Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Issue/9/insert cmodels in database #20

Merged
merged 52 commits into from
Apr 25, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
52 commits
Select commit Hold shift + click to select a range
7e1ba19
Merge branch 'basic_api_config' of https://github.com/fenfisdi/cdslab…
Anturion Apr 10, 2021
762f731
add: requirements file
Anturion Apr 12, 2021
e703c3b
Build: collection cmodels
Anturion Apr 12, 2021
d31b7ae
pull: remote branch
Anturion Apr 13, 2021
f891880
Merge branch 'dev' of https://github.com/fenfisdi/cdslab_cmodels_api …
Anturion Apr 13, 2021
9bab012
fix: cmodels flow updated"
Anturion Apr 15, 2021
accbec1
Merge branch 'dev' of https://github.com/fenfisdi/cdslab_cmodels_api …
Anturion Apr 15, 2021
63a9a7f
build: db cmodels, insert cmodels collection method
Anturion Apr 15, 2021
ed2b520
Build: use cases cmodels
Anturion Apr 16, 2021
55cc2a1
fix:updated insert_cmodels_document
Anturion Apr 16, 2021
aada177
fix: model cmodel
Anturion Apr 16, 2021
002e25d
fix: remove unnecessary imports
Anturion Apr 19, 2021
1abb89d
fix: remove unnecessary imports
Anturion Apr 19, 2021
3bab513
build: utils cmodels file and create id cmodels method in usecases
Anturion Apr 19, 2021
981e07d
build: test of cmodels created
Anturion Apr 19, 2021
65b8443
fix: style
jearistiz Apr 20, 2021
41a2a54
.gitignore: .DS_Store
jearistiz Apr 20, 2021
49a0f07
refactor: src.interfaces.cmodel_interface.cmodel_collection -> src.db…
jearistiz Apr 20, 2021
93e9c43
refactor: crud
jearistiz Apr 20, 2021
6a42b36
refactor: compartmentl models db-related stuff
jearistiz Apr 21, 2021
842d011
fix: sonnarcloud-reported bugs
jearistiz Apr 21, 2021
76dedd9
refactor: inserting cmodels in db
jearistiz Apr 21, 2021
547c09c
fix: updated model
Anturion Apr 22, 2021
79f87f0
fix: cmodels
Anturion Apr 22, 2021
1d695ba
Merge branch 'issue/9/insert_cmodels_in_database' of https://github.c…
Anturion Apr 22, 2021
ec83c82
refactor: changed back cmodels documents creation to main.py
jearistiz Apr 22, 2021
aef427e
build: test get_collection method
Anturion Apr 23, 2021
678cd9b
build: test cmodel interface
Anturion Apr 23, 2021
887bb13
Merge branch 'issue/9/insert_cmodels_in_database' of https://github.c…
Anturion Apr 23, 2021
0541d80
fix: test_cmodel_interface
Anturion Apr 23, 2021
1298ea0
build: test delete crud method
Anturion Apr 23, 2021
ce731a8
Update src/interfaces/cmodels.py
jearistiz Apr 23, 2021
51ff8da
Update src/use_cases/cmodels.py
jearistiz Apr 23, 2021
d2e2f69
Update main.py
jearistiz Apr 23, 2021
c615607
Update src/interfaces/cmodels.py
jearistiz Apr 23, 2021
f8192ea
Update src/interfaces/cmodels.py
jearistiz Apr 23, 2021
af450a9
fix: style - sort imports
jearistiz Apr 23, 2021
91331f3
fix: interface tests
Anturion Apr 23, 2021
451a2f5
refactor: interfaces and appropiate tests
jearistiz Apr 23, 2021
65edffc
tests: cmodel use_cases
jearistiz Apr 23, 2021
3a91fa2
refactor: renamed attributes in src.interfaces test cases
jearistiz Apr 23, 2021
1a155cc
chore: updated requirements.txt
jearistiz Apr 23, 2021
7c416b0
fix: style
jearistiz Apr 23, 2021
88b970d
fix: style src/models/db/cmodels.py
jearistiz Apr 23, 2021
27dcb68
deleted src/models/db/cmodels.AllCModels (not needed)
jearistiz Apr 23, 2021
6d4d874
Merge branch 'issue/9/insert_cmodels_in_database' of https://github.c…
jearistiz Apr 23, 2021
29c836f
fix: style in tests/interfaces/test_cmodels.py
jearistiz Apr 23, 2021
aef1e22
Chore: Update Singleton Pattern
Apr 24, 2021
673260f
Merge branch 'feature/update_features' into issue/9/merge_docker_db_s…
jearistiz Apr 24, 2021
7095f08
fix: test cases run appropriately
jearistiz Apr 24, 2021
31ecb49
fix: type hint
jearistiz Apr 24, 2021
930fbdb
fix: typo and setters' logic in src.db.mongo
jearistiz Apr 25, 2021
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -151,3 +151,6 @@ cython_debug/

# Experiments
experiments/

# MacOS
.DS_Store
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"]
2 changes: 1 addition & 1 deletion Pipfile.lock

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

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
11 changes: 9 additions & 2 deletions main.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,18 @@
from src.db.mongo import MongoClientSingleton
import uvicorn

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

if __name__ == '__main__':
__all__ = ['app']

if __name__ == '__main__':
mongo_singleton = MongoClientSingleton()
CmodelUseCases(mongo_singleton).update_cmodels_collection()
uvicorn.run(
"src.api:app",
host=settings['HOST'],
host=settings.get('HOST'),
port=int(settings['PORT']),
reload=True,
debug=True,
Expand Down
2 changes: 2 additions & 0 deletions requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,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 @@ -33,6 +34,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
9 changes: 4 additions & 5 deletions src/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,18 +7,17 @@

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
4 changes: 2 additions & 2 deletions src/config.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
from dotenv import dotenv_values


settings = dotenv_values(".env")
db_config = dotenv_values(".db_config")
settings = dotenv_values('.env')
db_config = dotenv_values('.db_config')
122 changes: 81 additions & 41 deletions src/db/mongo.py
Original file line number Diff line number Diff line change
@@ -1,47 +1,87 @@
from typing import Generator, Tuple
from typing import Generator, Optional, Tuple, Union

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

from src.config import db_config
from src.utils.patterns import Singleton


class MongoClientSingleton(metaclass=Singleton):
db_uri: Optional[str] = db_config.get('MONGO_URI'),

def __init__(
self,
db_connection: MongoClient = MongoClient(db_uri),
db: Union[str, Database] = db_config.get('MONGO_DB'),
coll: Union[str, Collection] = db_config.get('CMODELS_COLL')
) -> None:
self.db_connection = db_connection
self.db = db
self.coll = 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.
"""
try:
yield self.db_connection
finally:
self.db_connection.close()

def get_db(
self,
db: Optional[str] = None
) -> Tuple[MongoClient, Database]:
"""Gets Mongodb connection and database.

Returns
-------
db_connection : MongoClient
db : pymongo.database.Database
"""
if db and isinstance(db, str):
self.db = db
return self.db_connection, self.db

def get_collection(
self,
coll: Optional[str] = None
) -> Tuple[MongoClient, Collection]:
"""
Returns
-------
db_connection: pymongo.MongoClient
coll: pymongo.collection.Collection
"""
if coll and isinstance(coll, str):
self.coll = coll
return self.db_connection, self.coll

@property
def db(self):
return self._db

@db.setter
def db(self, value): # noqa
if isinstance(value, str):
self._db = self.db_connection[value]
elif isinstance(value, Database) or isinstance(value, mongomock.Database):
self._db = value

@property
def coll(self):
return self._coll

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
@coll.setter
def coll(self, value): # noqa
if isinstance(value, str):
self._coll = self.db[value]
elif isinstance(value, Collection) or isinstance(value, mongomock.Collection):
self._coll = value
5 changes: 0 additions & 5 deletions src/interfaces/cmodel_interface.py

This file was deleted.

60 changes: 60 additions & 0 deletions src/interfaces/cmodels.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
from datetime import datetime

from src.db.mongo import MongoClientSingleton
from src.models.db.cmodels import (
CompartmentalModel,
CompartmentalModelEnum
)
from src.interfaces.crud import MongoCRUD


class CModelsInterface:

def __init__(
self,
mongo_singleton: MongoClientSingleton
) -> None:
self.mongo_singleton = mongo_singleton
self.crud = MongoCRUD(self.mongo_singleton)

def insert_one_cmodel_document(self, model: CompartmentalModel):

cmodel_document = model.dict(by_alias=True)

existent_model = self.crud.read(model.id)

if existent_model:
pruned_existent_model = CModelsInterface._prune_db_document(
existent_model
)
pruned_current_model = CModelsInterface._prune_db_document(
cmodel_document
)
if pruned_existent_model == pruned_current_model:
# TODO: log cmodel exists f'Cmodel exists: {model.name}'
return existent_model
else:
model.updated_at = datetime.utcnow()
updated_model = self.crud.update(
model.id,
model.dict(by_alias=True)
)
# TODO log updated cmodel f'Updated cmodel: {model.name}'
return updated_model
else:
model_inserted = self.crud.insert(cmodel_document)
# TODO: log created cmodel f'Created cmodel: {model.name}'
return model_inserted

def insert_all_cmodel_documents(self):
return [
self.insert_one_cmodel_document(model)
for model in CompartmentalModelEnum.values()
]

@staticmethod
def _prune_db_document(model_in_db: dict) -> dict:
if model_in_db:
model_in_db.pop('inserted_at')
model_in_db.pop('updated_at')
return model_in_db
Loading