Skip to content

Commit

Permalink
Add function to save API request to database (#125)
Browse files Browse the repository at this point in the history
* Add function to save API request to database

* edited  logging

* changed directories of database

* added tests

* added tests

* solved linting issues
  • Loading branch information
suleman1412 authored Apr 10, 2024
1 parent 11cbc1e commit 7dd989f
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 1 deletion.
30 changes: 30 additions & 0 deletions pvsite_datamodel/write/database.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
"""
Functions to read from the database and format.
"""
import logging

from pvsite_datamodel.read.user import get_user_by_email as get_user_by_db
from pvsite_datamodel.sqlmodels import APIRequestSQL

logger = logging.getLogger(__name__)


def save_api_call_to_db(url, session, user=None):
"""
Save api call to database.
"""
url = str(url)
if user is None:
email = "unknown"
else:
email = user.email

# get user from db
user = get_user_by_db(session=session, email=email)
# make api call
logger.info(f"Saving api call ({url=}) to database for user {email}")
api_request = APIRequestSQL(url=url, user=user)

# commit to database
session.add(api_request)
session.commit()
11 changes: 10 additions & 1 deletion tests/test_write.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,9 @@
from sqlalchemy.exc import SQLAlchemyError
from sqlalchemy.orm import Session

from pvsite_datamodel.sqlmodels import ForecastSQL, ForecastValueSQL, GenerationSQL
from pvsite_datamodel.read.user import get_user_by_email
from pvsite_datamodel.sqlmodels import APIRequestSQL, ForecastSQL, ForecastValueSQL, GenerationSQL
from pvsite_datamodel.write.database import save_api_call_to_db
from pvsite_datamodel.write.forecast import insert_forecast_values
from pvsite_datamodel.write.generation import insert_generation_values
from pvsite_datamodel.write.user_and_site import (
Expand Down Expand Up @@ -244,3 +246,10 @@ def test_change_user_site_group(db_session):

assert user_site_group == site_group2.site_group_name
assert user == "[email protected]"


def test_save_api_call_to_db(db_session):
user = get_user_by_email(session=db_session, email="[email protected]")
url = "test"
save_api_call_to_db(url=url, session=db_session, user=user)
assert len(db_session.query(APIRequestSQL).all()) == 1

0 comments on commit 7dd989f

Please sign in to comment.